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