]> git.sesse.net Git - nageru/blob - mainwindow.cpp
Use std::chrono for (almost) all time keeping.
[nageru] / mainwindow.cpp
1 #include "mainwindow.h"
2
3 #include <math.h>
4 #include <stdio.h>
5 #include <signal.h>
6 #include <algorithm>
7 #include <chrono>
8 #include <string>
9 #include <vector>
10 #include <QBoxLayout>
11 #include <QInputDialog>
12 #include <QKeySequence>
13 #include <QLabel>
14 #include <QMetaType>
15 #include <QPushButton>
16 #include <QResizeEvent>
17 #include <QShortcut>
18 #include <QSize>
19 #include <QString>
20
21 #include "aboutdialog.h"
22 #include "flags.h"
23 #include "glwidget.h"
24 #include "lrameter.h"
25 #include "mixer.h"
26 #include "post_to_main_thread.h"
27 #include "ui_display.h"
28 #include "ui_mainwindow.h"
29 #include "vumeter.h"
30
31 class QResizeEvent;
32
33 using namespace std;
34 using namespace std::chrono;
35 using namespace std::placeholders;
36
37 Q_DECLARE_METATYPE(std::string);
38 Q_DECLARE_METATYPE(std::vector<std::string>);
39
40 MainWindow *global_mainwindow = nullptr;
41
42 namespace {
43
44 void schedule_cut_signal(int ignored)
45 {
46         global_mixer->schedule_cut();
47 }
48
49 void quit_signal(int ignored)
50 {
51         global_mainwindow->close();
52 }
53
54 constexpr unsigned DB_NO_FLAGS = 0x0;
55 constexpr unsigned DB_WITH_SIGN = 0x1;
56 constexpr unsigned DB_BARE = 0x2;
57
58 string format_db(double db, unsigned flags)
59 {
60         string text;
61         if (flags & DB_WITH_SIGN) {
62                 if (isfinite(db)) {
63                         char buf[256];
64                         snprintf(buf, sizeof(buf), "%+.1f", db);
65                         text = buf;
66                 } else if (db < 0.0) {
67                         text = "-∞";
68                 } else {
69                         // Should never happen, really.
70                         text = "+∞";
71                 }
72         } else {
73                 if (isfinite(db)) {
74                         char buf[256];
75                         snprintf(buf, sizeof(buf), "%.1f", db);
76                         text = buf;
77                 } else if (db < 0.0) {
78                         text = "-∞";
79                 } else {
80                         // Should never happen, really.
81                         text = "∞";
82                 }
83         }
84         if (!(flags & DB_BARE)) {
85                 text += " dB";
86         }
87         return text;
88 }
89
90 }  // namespace
91
92 MainWindow::MainWindow()
93         : ui(new Ui::MainWindow)
94 {
95         global_mainwindow = this;
96         ui->setupUi(this);
97
98         ui->me_live->set_output(Mixer::OUTPUT_LIVE);
99         ui->me_preview->set_output(Mixer::OUTPUT_PREVIEW);
100
101         // The menus.
102         connect(ui->cut_action, &QAction::triggered, this, &MainWindow::cut_triggered);
103         connect(ui->exit_action, &QAction::triggered, this, &MainWindow::exit_triggered);
104         connect(ui->about_action, &QAction::triggered, this, &MainWindow::about_triggered);
105
106         if (global_flags.x264_video_to_http) {
107                 connect(ui->x264_bitrate_action, &QAction::triggered, this, &MainWindow::x264_bitrate_triggered);
108         } else {
109                 ui->x264_bitrate_action->setEnabled(false);
110         }
111
112         // Hook up the transition buttons. (Keyboard shortcuts are set in set_transition_names().)
113         // TODO: Make them dynamic.
114         connect(ui->transition_btn1, &QPushButton::clicked, bind(&MainWindow::transition_clicked, this, 0));
115         connect(ui->transition_btn2, &QPushButton::clicked, bind(&MainWindow::transition_clicked, this, 1));
116         connect(ui->transition_btn3, &QPushButton::clicked, bind(&MainWindow::transition_clicked, this, 2));
117
118         // Aiee...
119         transition_btn1 = ui->transition_btn1;
120         transition_btn2 = ui->transition_btn2;
121         transition_btn3 = ui->transition_btn3;
122         qRegisterMetaType<string>("std::string");
123         qRegisterMetaType<vector<string>>("std::vector<std::string>");
124         connect(ui->me_live, &GLWidget::transition_names_updated, this, &MainWindow::set_transition_names);
125         qRegisterMetaType<Mixer::Output>("Mixer::Output");
126
127         last_audio_level_callback = steady_clock::now() - seconds(1);
128 }
129
130 void MainWindow::resizeEvent(QResizeEvent* event)
131 {
132         QMainWindow::resizeEvent(event);
133
134         // Ask for a relayout, but only after the event loop is done doing relayout
135         // on everything else.
136         QMetaObject::invokeMethod(this, "relayout", Qt::QueuedConnection);
137 }
138
139 void MainWindow::mixer_created(Mixer *mixer)
140 {
141         // Make the previews.
142         unsigned num_previews = mixer->get_num_channels();
143
144         for (unsigned i = 0; i < num_previews; ++i) {
145                 Mixer::Output output = Mixer::Output(Mixer::OUTPUT_INPUT0 + i);
146
147                 QWidget *preview = new QWidget(this);
148                 Ui::Display *ui_display = new Ui::Display;
149                 ui_display->setupUi(preview);
150                 ui_display->label->setText(mixer->get_channel_name(output).c_str());
151                 ui_display->display->set_output(output);
152                 ui->preview_displays->insertWidget(previews.size(), preview, 1);
153                 previews.push_back(ui_display);
154
155                 // Hook up the click.
156                 connect(ui_display->display, &GLWidget::clicked, bind(&MainWindow::channel_clicked, this, i));
157
158                 // Let the theme update the text whenever the resolution or color changed.
159                 connect(ui_display->display, &GLWidget::name_updated, this, &MainWindow::update_channel_name);
160                 connect(ui_display->display, &GLWidget::color_updated, this, &MainWindow::update_channel_color);
161
162                 // Hook up the keyboard key.
163                 QShortcut *shortcut = new QShortcut(QKeySequence(Qt::Key_1 + i), this);
164                 connect(shortcut, &QShortcut::activated, bind(&MainWindow::channel_clicked, this, i));
165
166                 // Hook up the white balance button (irrelevant if invisible).
167                 ui_display->wb_button->setVisible(mixer->get_supports_set_wb(output));
168                 connect(ui_display->wb_button, &QPushButton::clicked, bind(&MainWindow::wb_button_clicked, this, i));
169         }
170
171         // TODO: Fetch all of the values these for completeness,
172         // not just the enable knobs implied by flags.
173         ui->locut_enabled->setChecked(global_mixer->get_locut_enabled());
174         ui->gainstaging_knob->setValue(global_mixer->get_gain_staging_db());
175         ui->gainstaging_auto_checkbox->setChecked(global_mixer->get_gain_staging_auto());
176         ui->compressor_enabled->setChecked(global_mixer->get_compressor_enabled());
177         ui->limiter_enabled->setChecked(global_mixer->get_limiter_enabled());
178         ui->makeup_gain_auto_checkbox->setChecked(global_mixer->get_final_makeup_gain_auto());
179
180         ui->limiter_threshold_db_display->setText(
181                 QString::fromStdString(format_db(mixer->get_limiter_threshold_dbfs(), DB_WITH_SIGN)));
182         ui->compressor_threshold_db_display->setText(
183                 QString::fromStdString(format_db(mixer->get_compressor_threshold_dbfs(), DB_WITH_SIGN)));
184
185         connect(ui->locut_cutoff_knob, &QDial::valueChanged, this, &MainWindow::cutoff_knob_changed);
186         cutoff_knob_changed(ui->locut_cutoff_knob->value());
187         connect(ui->locut_enabled, &QCheckBox::stateChanged, [this](int state){
188                 global_mixer->set_locut_enabled(state == Qt::Checked);
189         });
190
191         connect(ui->gainstaging_knob, &QAbstractSlider::valueChanged, this, &MainWindow::gain_staging_knob_changed);
192         connect(ui->gainstaging_auto_checkbox, &QCheckBox::stateChanged, [this](int state){
193                 global_mixer->set_gain_staging_auto(state == Qt::Checked);
194         });
195         connect(ui->makeup_gain_knob, &QAbstractSlider::valueChanged, this, &MainWindow::final_makeup_gain_knob_changed);
196         connect(ui->makeup_gain_auto_checkbox, &QCheckBox::stateChanged, [this](int state){
197                 global_mixer->set_final_makeup_gain_auto(state == Qt::Checked);
198         });
199
200         connect(ui->limiter_threshold_knob, &QDial::valueChanged, this, &MainWindow::limiter_threshold_knob_changed);
201         connect(ui->compressor_threshold_knob, &QDial::valueChanged, this, &MainWindow::compressor_threshold_knob_changed);
202         connect(ui->limiter_enabled, &QCheckBox::stateChanged, [this](int state){
203                 global_mixer->set_limiter_enabled(state == Qt::Checked);
204         });
205         connect(ui->compressor_enabled, &QCheckBox::stateChanged, [this](int state){
206                 global_mixer->set_compressor_enabled(state == Qt::Checked);
207         });
208         connect(ui->reset_meters_button, &QPushButton::clicked, this, &MainWindow::reset_meters_button_clicked);
209         mixer->set_audio_level_callback(bind(&MainWindow::audio_level_callback, this, _1, _2, _3, _4, _5, _6, _7, _8));
210
211         struct sigaction act;
212         memset(&act, 0, sizeof(act));
213         act.sa_handler = schedule_cut_signal;
214         act.sa_flags = SA_RESTART;
215         sigaction(SIGHUP, &act, nullptr);
216
217         // Mostly for debugging. Don't override SIGINT, that's so evil if
218         // shutdown isn't instant.
219         memset(&act, 0, sizeof(act));
220         act.sa_handler = quit_signal;
221         act.sa_flags = SA_RESTART;
222         sigaction(SIGUSR1, &act, nullptr);
223 }
224
225 void MainWindow::mixer_shutting_down()
226 {
227         ui->me_live->clean_context();
228         ui->me_preview->clean_context();
229         for (Ui::Display *display : previews) {
230                 display->display->clean_context();
231         }
232 }
233
234 void MainWindow::cut_triggered()
235 {
236         global_mixer->schedule_cut();
237 }
238
239 void MainWindow::x264_bitrate_triggered()
240 {
241         bool ok;
242         int new_bitrate = QInputDialog::getInt(this, "Change x264 bitrate", "Choose new bitrate for x264 HTTP output (from 100–100,000 kbit/sec):", global_flags.x264_bitrate, /*min=*/100, /*max=*/100000, /*step=*/100, &ok);
243         if (ok && new_bitrate >= 100 && new_bitrate <= 100000) {
244                 global_flags.x264_bitrate = new_bitrate;
245                 global_mixer->change_x264_bitrate(new_bitrate);
246         }
247 }
248
249 void MainWindow::exit_triggered()
250 {
251         close();
252 }
253
254 void MainWindow::about_triggered()
255 {
256         AboutDialog().exec();
257 }
258
259 void MainWindow::gain_staging_knob_changed(int value)
260 {
261         ui->gainstaging_auto_checkbox->setCheckState(Qt::Unchecked);
262
263         float gain_db = value * 0.1f;
264         global_mixer->set_gain_staging_db(gain_db);
265
266         // The label will be updated by the audio level callback.
267 }
268
269 void MainWindow::final_makeup_gain_knob_changed(int value)
270 {
271         ui->makeup_gain_auto_checkbox->setCheckState(Qt::Unchecked);
272
273         float gain_db = value * 0.1f;
274         global_mixer->set_final_makeup_gain_db(gain_db);
275
276         // The label will be updated by the audio level callback.
277 }
278
279 void MainWindow::cutoff_knob_changed(int value)
280 {
281         float octaves = value * 0.1f;
282         float cutoff_hz = 20.0 * pow(2.0, octaves);
283         global_mixer->set_locut_cutoff(cutoff_hz);
284
285         char buf[256];
286         snprintf(buf, sizeof(buf), "%ld Hz", lrintf(cutoff_hz));
287         ui->locut_cutoff_display->setText(buf);
288 }
289
290 void MainWindow::limiter_threshold_knob_changed(int value)
291 {
292         float threshold_dbfs = value * 0.1f;
293         global_mixer->set_limiter_threshold_dbfs(threshold_dbfs);
294         ui->limiter_threshold_db_display->setText(
295                 QString::fromStdString(format_db(threshold_dbfs, DB_WITH_SIGN)));
296 }
297
298 void MainWindow::compressor_threshold_knob_changed(int value)
299 {
300         float threshold_dbfs = value * 0.1f;
301         global_mixer->set_compressor_threshold_dbfs(threshold_dbfs);
302         ui->compressor_threshold_db_display->setText(
303                 QString::fromStdString(format_db(threshold_dbfs, DB_WITH_SIGN)));
304 }
305
306 void MainWindow::reset_meters_button_clicked()
307 {
308         global_mixer->reset_meters();
309         ui->peak_display->setText(QString::fromStdString(format_db(-HUGE_VAL, DB_WITH_SIGN | DB_BARE)));
310         ui->peak_display->setStyleSheet("");
311 }
312
313 void MainWindow::audio_level_callback(float level_lufs, float peak_db, float global_level_lufs,
314                                       float range_low_lufs, float range_high_lufs,
315                                       float gain_staging_db, float final_makeup_gain_db,
316                                       float correlation)
317 {
318         steady_clock::time_point now = steady_clock::now();
319
320         // The meters are somewhat inefficient to update. Only update them
321         // every 100 ms or so (we get updates every 5–20 ms).
322         double last_update_age = duration<double>(now - last_audio_level_callback).count();
323         if (last_update_age < 0.100) {
324                 return;
325         }
326         last_audio_level_callback = now;
327
328         post_to_main_thread([=]() {
329                 ui->vu_meter->set_level(level_lufs);
330                 ui->lra_meter->set_levels(global_level_lufs, range_low_lufs, range_high_lufs);
331                 ui->correlation_meter->set_correlation(correlation);
332
333                 ui->peak_display->setText(QString::fromStdString(format_db(peak_db, DB_BARE)));
334                 if (peak_db > -0.1f) {  // -0.1 dBFS is EBU peak limit.
335                         ui->peak_display->setStyleSheet("QLabel { background-color: red; color: white; }");
336                 } else {
337                         ui->peak_display->setStyleSheet("");
338                 }
339
340                 ui->gainstaging_knob->blockSignals(true);
341                 ui->gainstaging_knob->setValue(lrintf(gain_staging_db * 10.0f));
342                 ui->gainstaging_knob->blockSignals(false);
343                 ui->gainstaging_db_display->setText(
344                         QString::fromStdString(format_db(gain_staging_db, DB_WITH_SIGN)));
345
346                 ui->makeup_gain_knob->blockSignals(true);
347                 ui->makeup_gain_knob->setValue(lrintf(final_makeup_gain_db * 10.0f));
348                 ui->makeup_gain_knob->blockSignals(false);
349                 ui->makeup_gain_db_display->setText(
350                         QString::fromStdString(format_db(final_makeup_gain_db, DB_WITH_SIGN)));
351         });
352 }
353
354 void MainWindow::relayout()
355 {
356         int height = ui->vertical_layout->geometry().height();
357
358         double remaining_height = height;
359
360         // Allocate the height; the most important part is to keep the main displays
361         // at 16:9 if at all possible.
362         double me_width = ui->me_preview->width();
363         double me_height = me_width * 9.0 / 16.0 + ui->label_preview->height() + ui->preview_vertical_layout->spacing();
364
365         // TODO: Scale the widths when we need to do this.
366         if (me_height / double(height) > 0.8) {
367                 me_height = height * 0.8;
368         }
369         remaining_height -= me_height + ui->vertical_layout->spacing();
370
371         double audiostrip_height = ui->audiostrip->geometry().height();
372         remaining_height -= audiostrip_height + ui->vertical_layout->spacing();
373
374         // The previews will be constrained by the remaining height, and the width.
375         double preview_label_height = previews[0]->title_bar->geometry().height() +
376                 previews[0]->main_vertical_layout->spacing();
377         int preview_total_width = ui->preview_displays->geometry().width() - (previews.size() - 1) * ui->preview_displays->spacing();
378         double preview_height = min(remaining_height - preview_label_height, (preview_total_width / double(previews.size())) * 9.0 / 16.0);
379         remaining_height -= preview_height + preview_label_height + ui->vertical_layout->spacing();
380
381         ui->vertical_layout->setStretch(0, lrintf(me_height));
382         ui->vertical_layout->setStretch(1, 0);  // Don't stretch the audiostrip.
383         ui->vertical_layout->setStretch(2, max<int>(1, remaining_height));  // Spacer.
384         ui->vertical_layout->setStretch(3, lrintf(preview_height + preview_label_height));
385
386         // Set the widths for the previews.
387         double preview_width = preview_height * 16.0 / 9.0;
388         for (unsigned i = 0; i < previews.size(); ++i) {
389                 ui->preview_displays->setStretch(i, lrintf(preview_width));
390         }
391
392         // The preview horizontal spacer.
393         double remaining_preview_width = preview_total_width - previews.size() * preview_width;
394         ui->preview_displays->setStretch(previews.size(), lrintf(remaining_preview_width));
395 }
396
397 void MainWindow::set_transition_names(vector<string> transition_names)
398 {
399         if (transition_names.size() < 1 || transition_names[0].empty()) {
400                 transition_btn1->setText(QString(""));
401         } else {
402                 transition_btn1->setText(QString::fromStdString(transition_names[0] + " (J)"));
403                 ui->transition_btn1->setShortcut(QKeySequence("J"));
404         }
405         if (transition_names.size() < 2 || transition_names[1].empty()) {
406                 transition_btn2->setText(QString(""));
407         } else {
408                 transition_btn2->setText(QString::fromStdString(transition_names[1] + " (K)"));
409                 ui->transition_btn2->setShortcut(QKeySequence("K"));
410         }
411         if (transition_names.size() < 3 || transition_names[2].empty()) {
412                 transition_btn3->setText(QString(""));
413         } else {
414                 transition_btn3->setText(QString::fromStdString(transition_names[2] + " (L)"));
415                 ui->transition_btn3->setShortcut(QKeySequence("L"));
416         }
417 }
418
419 void MainWindow::update_channel_name(Mixer::Output output, const string &name)
420 {
421         if (output >= Mixer::OUTPUT_INPUT0) {
422                 unsigned channel = output - Mixer::OUTPUT_INPUT0;
423                 previews[channel]->label->setText(name.c_str());
424         }
425 }
426
427 void MainWindow::update_channel_color(Mixer::Output output, const string &color)
428 {
429         if (output >= Mixer::OUTPUT_INPUT0) {
430                 unsigned channel = output - Mixer::OUTPUT_INPUT0;
431                 previews[channel]->frame->setStyleSheet(QString::fromStdString("background-color:" + color));
432         }
433 }
434
435 void MainWindow::transition_clicked(int transition_number)
436 {
437         global_mixer->transition_clicked(transition_number);
438 }
439
440 void MainWindow::channel_clicked(int channel_number)
441 {
442         if (current_wb_pick_display == channel_number) {
443                 // The picking was already done from eventFilter(), since we don't get
444                 // the mouse pointer here.
445         } else {
446                 global_mixer->channel_clicked(channel_number);
447         }
448 }
449
450 void MainWindow::wb_button_clicked(int channel_number)
451 {
452         current_wb_pick_display = channel_number;
453         QApplication::setOverrideCursor(Qt::CrossCursor);
454 }
455
456 bool MainWindow::eventFilter(QObject *watched, QEvent *event)
457 {
458         if (current_wb_pick_display != -1 &&
459             event->type() == QEvent::MouseButtonRelease &&
460             watched->isWidgetType()) {
461                 QApplication::restoreOverrideCursor();
462                 if (watched == previews[current_wb_pick_display]->display) {
463                         const QMouseEvent *mouse_event = (QMouseEvent *)event;
464                         set_white_balance(current_wb_pick_display, mouse_event->x(), mouse_event->y());
465                 } else {
466                         // The user clicked on something else, give up.
467                         // (The click goes through, which might not be ideal, but, yes.)
468                         current_wb_pick_display = -1;
469                 }
470         }
471         return false;
472 }
473
474 namespace {
475
476 double srgb_to_linear(double x)
477 {
478         if (x < 0.04045) {
479                 return x / 12.92;
480         } else {
481                 return pow((x + 0.055) / 1.055, 2.4);
482         }
483 }
484
485 }  // namespace
486
487 void MainWindow::set_white_balance(int channel_number, int x, int y)
488 {
489         // Set the white balance to neutral for the grab. It's probably going to
490         // flicker a bit, but hopefully this display is not live anyway.
491         global_mixer->set_wb(Mixer::OUTPUT_INPUT0 + channel_number, 0.5, 0.5, 0.5);
492         previews[channel_number]->display->updateGL();
493         QRgb reference_color = previews[channel_number]->display->grabFrameBuffer().pixel(x, y);
494
495         double r = srgb_to_linear(qRed(reference_color) / 255.0);
496         double g = srgb_to_linear(qGreen(reference_color) / 255.0);
497         double b = srgb_to_linear(qBlue(reference_color) / 255.0);
498         global_mixer->set_wb(Mixer::OUTPUT_INPUT0 + channel_number, r, g, b);
499         previews[channel_number]->display->updateGL();
500 }