]> git.sesse.net Git - nageru/blob - mainwindow.cpp
Replace the R128 meters for each channel with a digital peak meter.
[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 "disk_space_estimator.h"
23 #include "flags.h"
24 #include "glwidget.h"
25 #include "input_mapping_dialog.h"
26 #include "lrameter.h"
27 #include "mixer.h"
28 #include "post_to_main_thread.h"
29 #include "ui_audio_miniview.h"
30 #include "ui_audio_expanded_view.h"
31 #include "ui_display.h"
32 #include "ui_mainwindow.h"
33 #include "vumeter.h"
34
35 class QResizeEvent;
36
37 using namespace std;
38 using namespace std::chrono;
39 using namespace std::placeholders;
40
41 Q_DECLARE_METATYPE(std::string);
42 Q_DECLARE_METATYPE(std::vector<std::string>);
43
44 MainWindow *global_mainwindow = nullptr;
45
46 namespace {
47
48 void schedule_cut_signal(int ignored)
49 {
50         global_mixer->schedule_cut();
51 }
52
53 void quit_signal(int ignored)
54 {
55         global_mainwindow->close();
56 }
57
58 void slave_knob(QDial *master, QDial *slave)
59 {
60         QWidget::connect(master, &QDial::valueChanged, [slave](int value){
61                 slave->blockSignals(true);
62                 slave->setValue(value);
63                 slave->blockSignals(false);
64         });
65         QWidget::connect(slave, &QDial::valueChanged, [master](int value){
66                 master->setValue(value);
67         });
68 }
69
70 void slave_checkbox(QCheckBox *master, QCheckBox *slave)
71 {
72         QWidget::connect(master, &QCheckBox::stateChanged, [slave](int state){
73                 slave->blockSignals(true);
74                 slave->setCheckState(Qt::CheckState(state));
75                 slave->blockSignals(false);
76         });
77         QWidget::connect(slave, &QCheckBox::stateChanged, [master](int state){
78                 master->setCheckState(Qt::CheckState(state));
79         });
80 }
81
82 void slave_fader(NonLinearFader *master, NonLinearFader *slave)
83 {
84         QWidget::connect(master, &NonLinearFader::dbValueChanged, [slave](double value) {
85                 slave->blockSignals(true);
86                 slave->setDbValue(value);
87                 slave->blockSignals(false);
88         });
89         QWidget::connect(slave, &NonLinearFader::dbValueChanged, [master](double value){
90                 master->setDbValue(value);
91         });
92 }
93
94 constexpr unsigned DB_NO_FLAGS = 0x0;
95 constexpr unsigned DB_WITH_SIGN = 0x1;
96 constexpr unsigned DB_BARE = 0x2;
97
98 string format_db(double db, unsigned flags)
99 {
100         string text;
101         if (flags & DB_WITH_SIGN) {
102                 if (isfinite(db)) {
103                         char buf[256];
104                         snprintf(buf, sizeof(buf), "%+.1f", db);
105                         text = buf;
106                 } else if (db < 0.0) {
107                         text = "-∞";
108                 } else {
109                         // Should never happen, really.
110                         text = "+∞";
111                 }
112         } else {
113                 if (isfinite(db)) {
114                         char buf[256];
115                         snprintf(buf, sizeof(buf), "%.1f", db);
116                         text = buf;
117                 } else if (db < 0.0) {
118                         text = "-∞";
119                 } else {
120                         // Should never happen, really.
121                         text = "∞";
122                 }
123         }
124         if (!(flags & DB_BARE)) {
125                 text += " dB";
126         }
127         return text;
128 }
129
130 }  // namespace
131
132 MainWindow::MainWindow()
133         : ui(new Ui::MainWindow)
134 {
135         global_mainwindow = this;
136         ui->setupUi(this);
137
138         global_disk_space_estimator = new DiskSpaceEstimator(bind(&MainWindow::report_disk_space, this, _1, _2));
139         disk_free_label = new QLabel(this);
140         disk_free_label->setStyleSheet("QLabel {padding-right: 5px;}");
141         ui->menuBar->setCornerWidget(disk_free_label);
142
143         ui->me_live->set_output(Mixer::OUTPUT_LIVE);
144         ui->me_preview->set_output(Mixer::OUTPUT_PREVIEW);
145
146         // The menus.
147         connect(ui->cut_action, &QAction::triggered, this, &MainWindow::cut_triggered);
148         connect(ui->exit_action, &QAction::triggered, this, &MainWindow::exit_triggered);
149         connect(ui->about_action, &QAction::triggered, this, &MainWindow::about_triggered);
150         connect(ui->input_mapping_action, &QAction::triggered, this, &MainWindow::input_mapping_triggered);
151
152         if (global_flags.x264_video_to_http) {
153                 connect(ui->x264_bitrate_action, &QAction::triggered, this, &MainWindow::x264_bitrate_triggered);
154         } else {
155                 ui->x264_bitrate_action->setEnabled(false);
156         }
157
158         // Hook up the transition buttons. (Keyboard shortcuts are set in set_transition_names().)
159         // TODO: Make them dynamic.
160         connect(ui->transition_btn1, &QPushButton::clicked, bind(&MainWindow::transition_clicked, this, 0));
161         connect(ui->transition_btn2, &QPushButton::clicked, bind(&MainWindow::transition_clicked, this, 1));
162         connect(ui->transition_btn3, &QPushButton::clicked, bind(&MainWindow::transition_clicked, this, 2));
163
164         // Aiee...
165         transition_btn1 = ui->transition_btn1;
166         transition_btn2 = ui->transition_btn2;
167         transition_btn3 = ui->transition_btn3;
168         qRegisterMetaType<string>("std::string");
169         qRegisterMetaType<vector<string>>("std::vector<std::string>");
170         connect(ui->me_live, &GLWidget::transition_names_updated, this, &MainWindow::set_transition_names);
171         qRegisterMetaType<Mixer::Output>("Mixer::Output");
172
173         // Hook up the prev/next buttons on the audio views.
174         connect(ui->compact_prev_page, &QAbstractButton::clicked, bind(&QStackedWidget::setCurrentIndex, ui->audio_views, 1));
175         connect(ui->compact_next_page, &QAbstractButton::clicked, bind(&QStackedWidget::setCurrentIndex, ui->audio_views, 1));
176         connect(ui->full_prev_page, &QAbstractButton::clicked, bind(&QStackedWidget::setCurrentIndex, ui->audio_views, 0));
177         connect(ui->full_next_page, &QAbstractButton::clicked, bind(&QStackedWidget::setCurrentIndex, ui->audio_views, 0));
178
179         last_audio_level_callback = steady_clock::now() - seconds(1);
180 }
181
182 void MainWindow::resizeEvent(QResizeEvent* event)
183 {
184         QMainWindow::resizeEvent(event);
185
186         // Ask for a relayout, but only after the event loop is done doing relayout
187         // on everything else.
188         QMetaObject::invokeMethod(this, "relayout", Qt::QueuedConnection);
189 }
190
191 void MainWindow::mixer_created(Mixer *mixer)
192 {
193         // Make the previews.
194         unsigned num_previews = mixer->get_num_channels();
195
196         for (unsigned i = 0; i < num_previews; ++i) {
197                 Mixer::Output output = Mixer::Output(Mixer::OUTPUT_INPUT0 + i);
198
199                 QWidget *preview = new QWidget(this);
200                 Ui::Display *ui_display = new Ui::Display;
201                 ui_display->setupUi(preview);
202                 ui_display->label->setText(mixer->get_channel_name(output).c_str());
203                 ui_display->display->set_output(output);
204                 ui->preview_displays->insertWidget(previews.size(), preview, 1);
205                 previews.push_back(ui_display);
206
207                 // Hook up the click.
208                 connect(ui_display->display, &GLWidget::clicked, bind(&MainWindow::channel_clicked, this, i));
209
210                 // Let the theme update the text whenever the resolution or color changed.
211                 connect(ui_display->display, &GLWidget::name_updated, this, &MainWindow::update_channel_name);
212                 connect(ui_display->display, &GLWidget::color_updated, this, &MainWindow::update_channel_color);
213
214                 // Hook up the keyboard key.
215                 QShortcut *shortcut = new QShortcut(QKeySequence(Qt::Key_1 + i), this);
216                 connect(shortcut, &QShortcut::activated, bind(&MainWindow::channel_clicked, this, i));
217
218                 // Hook up the white balance button (irrelevant if invisible).
219                 ui_display->wb_button->setVisible(mixer->get_supports_set_wb(output));
220                 connect(ui_display->wb_button, &QPushButton::clicked, bind(&MainWindow::wb_button_clicked, this, i));
221         }
222
223         setup_audio_miniview();
224         setup_audio_expanded_view();
225
226         slave_knob(ui->locut_cutoff_knob, ui->locut_cutoff_knob_2);
227         slave_knob(ui->limiter_threshold_knob, ui->limiter_threshold_knob_2);
228         slave_knob(ui->makeup_gain_knob, ui->makeup_gain_knob_2);
229         slave_checkbox(ui->makeup_gain_auto_checkbox, ui->makeup_gain_auto_checkbox_2);
230         slave_checkbox(ui->limiter_enabled, ui->limiter_enabled_2);
231
232         // TODO: Fetch all of the values these for completeness,
233         // not just the enable knobs implied by flags.
234 #if 0
235         // TODO: Reenable for simple audio.
236         ui->locut_enabled->setChecked(global_mixer->get_audio_mixer()->get_locut_enabled(0));
237         connect(ui->locut_enabled, &QCheckBox::stateChanged, [this](int state){
238                 global_mixer->get_audio_mixer()->set_locut_enabled(0, state == Qt::Checked);
239         });
240         ui->gainstaging_knob->setValue(global_mixer->get_audio_mixer()->get_gain_staging_db());
241         ui->gainstaging_auto_checkbox->setChecked(global_mixer->get_audio_mixer()->get_gain_staging_auto());
242         ui->compressor_enabled->setChecked(global_mixer->get_audio_mixer()->get_compressor_enabled());
243         connect(ui->gainstaging_knob, &QAbstractSlider::valueChanged, this, &MainWindow::gain_staging_knob_changed);
244         connect(ui->gainstaging_auto_checkbox, &QCheckBox::stateChanged, [this](int state){
245                 global_mixer->get_audio_mixer()->set_gain_staging_auto(state == Qt::Checked);
246         });
247         ui->compressor_threshold_db_display->setText(
248                 QString::fromStdString(format_db(mixer->get_audio_mixer()->get_compressor_threshold_dbfs(), DB_WITH_SIGN)));
249         ui->compressor_threshold_db_display->setText(buf);
250         connect(ui->compressor_threshold_knob, &QDial::valueChanged, this, &MainWindow::compressor_threshold_knob_changed);
251         connect(ui->compressor_enabled, &QCheckBox::stateChanged, [this](int state){
252                 global_mixer->get_audio_mixer()->set_compressor_enabled(state == Qt::Checked);
253         });
254 #else
255         ui->locut_enabled->setVisible(false);
256         ui->gainstaging_label->setVisible(false);
257         ui->gainstaging_knob->setVisible(false);
258         ui->gainstaging_db_display->setVisible(false);
259         ui->gainstaging_auto_checkbox->setVisible(false);
260         ui->compressor_threshold_label->setVisible(false);
261         ui->compressor_threshold_knob->setVisible(false);
262         ui->compressor_threshold_db_display->setVisible(false);
263         ui->compressor_enabled->setVisible(false);
264 #endif
265         ui->limiter_enabled->setChecked(global_mixer->get_audio_mixer()->get_limiter_enabled());
266         ui->makeup_gain_auto_checkbox->setChecked(global_mixer->get_audio_mixer()->get_final_makeup_gain_auto());
267
268         QString limiter_threshold_label(
269                 QString::fromStdString(format_db(mixer->get_audio_mixer()->get_limiter_threshold_dbfs(), DB_WITH_SIGN)));
270         ui->limiter_threshold_db_display->setText(limiter_threshold_label);
271         ui->limiter_threshold_db_display_2->setText(limiter_threshold_label);
272
273         connect(ui->locut_cutoff_knob, &QDial::valueChanged, this, &MainWindow::cutoff_knob_changed);
274         cutoff_knob_changed(ui->locut_cutoff_knob->value());
275
276         connect(ui->makeup_gain_knob, &QAbstractSlider::valueChanged, this, &MainWindow::final_makeup_gain_knob_changed);
277         connect(ui->makeup_gain_auto_checkbox, &QCheckBox::stateChanged, [this](int state){
278                 global_mixer->get_audio_mixer()->set_final_makeup_gain_auto(state == Qt::Checked);
279         });
280
281         connect(ui->limiter_threshold_knob, &QDial::valueChanged, this, &MainWindow::limiter_threshold_knob_changed);
282         connect(ui->limiter_enabled, &QCheckBox::stateChanged, [this](int state){
283                 global_mixer->get_audio_mixer()->set_limiter_enabled(state == Qt::Checked);
284         });
285         connect(ui->reset_meters_button, &QPushButton::clicked, this, &MainWindow::reset_meters_button_clicked);
286         mixer->get_audio_mixer()->set_audio_level_callback(bind(&MainWindow::audio_level_callback, this, _1, _2, _3, _4, _5, _6, _7, _8));
287
288         struct sigaction act;
289         memset(&act, 0, sizeof(act));
290         act.sa_handler = schedule_cut_signal;
291         act.sa_flags = SA_RESTART;
292         sigaction(SIGHUP, &act, nullptr);
293
294         // Mostly for debugging. Don't override SIGINT, that's so evil if
295         // shutdown isn't instant.
296         memset(&act, 0, sizeof(act));
297         act.sa_handler = quit_signal;
298         act.sa_flags = SA_RESTART;
299         sigaction(SIGUSR1, &act, nullptr);
300 }
301
302 void MainWindow::setup_audio_miniview()
303 {
304         // Remove any existing channels.
305         for (QLayoutItem *item; (item = ui->faders->takeAt(0)) != nullptr; ) {
306                 delete item->widget();
307                 delete item;
308         }
309         audio_miniviews.clear();
310
311         // Set up brand new ones from the input mapping.
312         InputMapping mapping = global_mixer->get_audio_mixer()->get_input_mapping();
313         audio_miniviews.resize(mapping.buses.size());
314         for (unsigned bus_index = 0; bus_index < mapping.buses.size(); ++bus_index) {
315                 QWidget *channel = new QWidget(this);
316                 Ui::AudioMiniView *ui_audio_miniview = new Ui::AudioMiniView;
317                 ui_audio_miniview->setupUi(channel);
318                 ui_audio_miniview->bus_desc_label->setFullText(
319                         QString::fromStdString(mapping.buses[bus_index].name));
320                 audio_miniviews[bus_index] = ui_audio_miniview;
321
322                 // Set up the peak meter.
323                 VUMeter *peak_meter = ui_audio_miniview->peak_meter;
324                 peak_meter->set_min_level(-30.0f);
325                 peak_meter->set_max_level(0.0f);
326                 peak_meter->set_ref_level(0.0f);
327
328                 // TODO: Set the fader position.
329                 ui->faders->addWidget(channel);
330
331                 connect(ui_audio_miniview->fader, &NonLinearFader::dbValueChanged,
332                         bind(&MainWindow::mini_fader_changed, this, bus_index, _1));
333         }
334 }
335
336 void MainWindow::setup_audio_expanded_view()
337 {
338         // Remove any existing channels.
339         for (QLayoutItem *item; (item = ui->buses->takeAt(0)) != nullptr; ) {
340                 delete item->widget();
341                 delete item;
342         }
343         audio_expanded_views.clear();
344
345         // Set up brand new ones from the input mapping.
346         InputMapping mapping = global_mixer->get_audio_mixer()->get_input_mapping();
347         audio_expanded_views.resize(mapping.buses.size());
348         for (unsigned bus_index = 0; bus_index < mapping.buses.size(); ++bus_index) {
349                 QWidget *channel = new QWidget(this);
350                 Ui::AudioExpandedView *ui_audio_expanded_view = new Ui::AudioExpandedView;
351                 ui_audio_expanded_view->setupUi(channel);
352                 ui_audio_expanded_view->bus_desc_label->setFullText(
353                         QString::fromStdString(mapping.buses[bus_index].name));
354                 audio_expanded_views[bus_index] = ui_audio_expanded_view;
355                 // TODO: Set the fader position.
356                 ui->buses->addWidget(channel);
357
358                 ui_audio_expanded_view->locut_enabled->setChecked(global_mixer->get_audio_mixer()->get_locut_enabled(bus_index));
359                 connect(ui_audio_expanded_view->locut_enabled, &QCheckBox::stateChanged, [this, bus_index](int state){
360                         global_mixer->get_audio_mixer()->set_locut_enabled(bus_index, state == Qt::Checked);
361                 });
362
363                 ui_audio_expanded_view->gainstaging_knob->setValue(global_mixer->get_audio_mixer()->get_gain_staging_db(bus_index));
364                 ui_audio_expanded_view->gainstaging_auto_checkbox->setChecked(global_mixer->get_audio_mixer()->get_gain_staging_auto(bus_index));
365                 ui_audio_expanded_view->compressor_enabled->setChecked(global_mixer->get_audio_mixer()->get_compressor_enabled(bus_index));
366
367                 connect(ui_audio_expanded_view->gainstaging_knob, &QAbstractSlider::valueChanged, bind(&MainWindow::gain_staging_knob_changed, this, bus_index, _1));
368                 connect(ui_audio_expanded_view->gainstaging_auto_checkbox, &QCheckBox::stateChanged, [this, bus_index](int state){
369                         global_mixer->get_audio_mixer()->set_gain_staging_auto(bus_index, state == Qt::Checked);
370                 });
371
372                 connect(ui_audio_expanded_view->compressor_threshold_knob, &QDial::valueChanged, bind(&MainWindow::compressor_threshold_knob_changed, this, bus_index, _1));
373                 connect(ui_audio_expanded_view->compressor_enabled, &QCheckBox::stateChanged, [this, bus_index](int state){
374                         global_mixer->get_audio_mixer()->set_compressor_enabled(bus_index, state == Qt::Checked);
375                 });
376
377                 slave_fader(audio_miniviews[bus_index]->fader, ui_audio_expanded_view->fader);
378
379                 // Set up the peak meter.
380                 VUMeter *peak_meter = ui_audio_expanded_view->peak_meter;
381                 peak_meter->set_min_level(-30.0f);
382                 peak_meter->set_max_level(0.0f);
383                 peak_meter->set_ref_level(0.0f);
384
385                 // Set up the compression attenuation meter.
386                 VUMeter *reduction_meter = ui_audio_expanded_view->reduction_meter;
387                 reduction_meter->set_min_level(0.0f);
388                 reduction_meter->set_max_level(10.0f);
389                 reduction_meter->set_ref_level(0.0f);
390                 reduction_meter->set_flip(true);
391         }
392 }
393
394 void MainWindow::mixer_shutting_down()
395 {
396         ui->me_live->clean_context();
397         ui->me_preview->clean_context();
398         for (Ui::Display *display : previews) {
399                 display->display->clean_context();
400         }
401 }
402
403 void MainWindow::cut_triggered()
404 {
405         global_mixer->schedule_cut();
406 }
407
408 void MainWindow::x264_bitrate_triggered()
409 {
410         bool ok;
411         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);
412         if (ok && new_bitrate >= 100 && new_bitrate <= 100000) {
413                 global_flags.x264_bitrate = new_bitrate;
414                 global_mixer->change_x264_bitrate(new_bitrate);
415         }
416 }
417
418 void MainWindow::exit_triggered()
419 {
420         close();
421 }
422
423 void MainWindow::about_triggered()
424 {
425         AboutDialog().exec();
426 }
427
428 void MainWindow::input_mapping_triggered()
429 {
430         if (InputMappingDialog().exec() == QDialog::Accepted) {
431                 setup_audio_miniview();
432                 setup_audio_expanded_view();
433         }
434 }
435
436 void MainWindow::gain_staging_knob_changed(unsigned bus_index, int value)
437 {
438         if (bus_index == 0) {
439                 ui->gainstaging_auto_checkbox->setCheckState(Qt::Unchecked);
440         }
441         if (bus_index < audio_expanded_views.size()) {
442                 audio_expanded_views[bus_index]->gainstaging_auto_checkbox->setCheckState(Qt::Unchecked);
443         }
444
445         float gain_db = value * 0.1f;
446         global_mixer->get_audio_mixer()->set_gain_staging_db(bus_index, gain_db);
447
448         // The label will be updated by the audio level callback.
449 }
450
451 void MainWindow::final_makeup_gain_knob_changed(int value)
452 {
453         ui->makeup_gain_auto_checkbox->setCheckState(Qt::Unchecked);
454
455         float gain_db = value * 0.1f;
456         global_mixer->get_audio_mixer()->set_final_makeup_gain_db(gain_db);
457
458         // The label will be updated by the audio level callback.
459 }
460
461 void MainWindow::cutoff_knob_changed(int value)
462 {
463         float octaves = value * 0.1f;
464         float cutoff_hz = 20.0 * pow(2.0, octaves);
465         global_mixer->get_audio_mixer()->set_locut_cutoff(cutoff_hz);
466
467         char buf[256];
468         snprintf(buf, sizeof(buf), "%ld Hz", lrintf(cutoff_hz));
469         ui->locut_cutoff_display->setText(buf);
470         ui->locut_cutoff_display_2->setText(buf);
471
472         for (unsigned bus_index = 0; bus_index < audio_expanded_views.size(); ++bus_index) {
473                 audio_expanded_views[bus_index]->locut_enabled->setText(
474                         QString("Lo-cut: ") + buf);
475         }
476 }
477
478 void MainWindow::report_disk_space(off_t free_bytes, double estimated_seconds_left)
479 {
480         char time_str[256];
481         if (estimated_seconds_left < 60.0) {
482                 strcpy(time_str, "<font color=\"red\">Less than a minute</font>");
483         } else if (estimated_seconds_left < 1800.0) {  // Less than half an hour: Xm Ys (red).
484                 int s = lrintf(estimated_seconds_left);
485                 int m = s / 60;
486                 s %= 60;
487                 snprintf(time_str, sizeof(time_str), "<font color=\"red\">%dm %ds</font>", m, s);
488         } else if (estimated_seconds_left < 3600.0) {  // Less than an hour: Xm.
489                 int m = lrintf(estimated_seconds_left / 60.0);
490                 snprintf(time_str, sizeof(time_str), "%dm", m);
491         } else if (estimated_seconds_left < 36000.0) {  // Less than ten hours: Xh Ym.
492                 int m = lrintf(estimated_seconds_left / 60.0);
493                 int h = m / 60;
494                 m %= 60;
495                 snprintf(time_str, sizeof(time_str), "%dh %dm", h, m);
496         } else {  // More than ten hours: Xh.
497                 int h = lrintf(estimated_seconds_left / 3600.0);
498                 snprintf(time_str, sizeof(time_str), "%dh", h);
499         }
500         char buf[256];
501         snprintf(buf, sizeof(buf), "Disk free: %'.0f MB (approx. %s)", free_bytes / 1048576.0, time_str);
502
503         std::string label = buf;
504
505         post_to_main_thread([this, label]{
506                 disk_free_label->setText(QString::fromStdString(label));
507                 ui->menuBar->setCornerWidget(disk_free_label);  // Need to set this again for the sizing to get right.
508         });
509 }
510
511 void MainWindow::limiter_threshold_knob_changed(int value)
512 {
513         float threshold_dbfs = value * 0.1f;
514         global_mixer->get_audio_mixer()->set_limiter_threshold_dbfs(threshold_dbfs);
515         ui->limiter_threshold_db_display->setText(
516                 QString::fromStdString(format_db(threshold_dbfs, DB_WITH_SIGN)));
517         ui->limiter_threshold_db_display_2->setText(
518                 QString::fromStdString(format_db(threshold_dbfs, DB_WITH_SIGN)));
519 }
520
521 void MainWindow::compressor_threshold_knob_changed(unsigned bus_index, int value)
522 {
523         float threshold_dbfs = value * 0.1f;
524         global_mixer->get_audio_mixer()->set_compressor_threshold_dbfs(bus_index, threshold_dbfs);
525
526         QString label(QString::fromStdString(format_db(threshold_dbfs, DB_WITH_SIGN)));
527         if (bus_index == 0) {
528                 ui->compressor_threshold_db_display->setText(label);
529         }
530         if (bus_index < audio_expanded_views.size()) {
531                 audio_expanded_views[bus_index]->compressor_threshold_db_display->setText(label);
532         }
533 }
534
535 void MainWindow::mini_fader_changed(int bus, double volume_db)
536 {
537         QString label(QString::fromStdString(format_db(volume_db, DB_WITH_SIGN)));
538         audio_miniviews[bus]->fader_label->setText(label);
539         audio_expanded_views[bus]->fader_label->setText(label);
540
541         global_mixer->get_audio_mixer()->set_fader_volume(bus, volume_db);
542 }
543
544 void MainWindow::reset_meters_button_clicked()
545 {
546         global_mixer->get_audio_mixer()->reset_meters();
547         ui->peak_display->setText(QString::fromStdString(format_db(-HUGE_VAL, DB_WITH_SIGN | DB_BARE)));
548         ui->peak_display->setStyleSheet("");
549 }
550
551 void MainWindow::audio_level_callback(float level_lufs, float peak_db, vector<AudioMixer::BusLevel> bus_levels,
552                                       float global_level_lufs,
553                                       float range_low_lufs, float range_high_lufs,
554                                       float final_makeup_gain_db,
555                                       float correlation)
556 {
557         steady_clock::time_point now = steady_clock::now();
558
559         // The meters are somewhat inefficient to update. Only update them
560         // every 100 ms or so (we get updates every 5–20 ms). Note that this
561         // means that the digital peak meters are ever so slightly too low
562         // (each update won't be a faithful representation of the highest peak
563         // since the previous update, since there are frames we won't draw),
564         // but the _peak_ of the peak meters will be correct (it's tracked in
565         // AudioMixer, not here), and that's much more important.
566         double last_update_age = duration<double>(now - last_audio_level_callback).count();
567         if (last_update_age < 0.100) {
568                 return;
569         }
570         last_audio_level_callback = now;
571
572         post_to_main_thread([=]() {
573                 ui->vu_meter->set_level(level_lufs);
574                 for (unsigned bus_index = 0; bus_index < bus_levels.size(); ++bus_index) {
575                         if (bus_index < audio_miniviews.size()) {
576                                 const AudioMixer::BusLevel &level = bus_levels[bus_index];
577                                 Ui::AudioMiniView *miniview = audio_miniviews[bus_index];
578                                 miniview->peak_meter->set_level(
579                                         level.current_level_dbfs[0], level.current_level_dbfs[1]);
580                                 miniview->peak_meter->set_peak(
581                                         level.peak_level_dbfs[0], level.peak_level_dbfs[1]);
582
583                                 Ui::AudioExpandedView *view = audio_expanded_views[bus_index];
584                                 view->peak_meter->set_level(
585                                         level.current_level_dbfs[0], level.current_level_dbfs[1]);
586                                 view->peak_meter->set_peak(
587                                         level.peak_level_dbfs[0], level.peak_level_dbfs[1]);
588                                 view->reduction_meter->set_level(level.compressor_attenuation_db);
589                                 view->gainstaging_knob->blockSignals(true);
590                                 view->gainstaging_knob->setValue(lrintf(level.gain_staging_db * 10.0f));
591                                 view->gainstaging_knob->blockSignals(false);
592                                 view->gainstaging_db_display->setText(
593                                         QString("Gain: ") +
594                                         QString::fromStdString(format_db(level.gain_staging_db, DB_WITH_SIGN)));
595                         }
596                 }
597                 ui->lra_meter->set_levels(global_level_lufs, range_low_lufs, range_high_lufs);
598                 ui->correlation_meter->set_correlation(correlation);
599
600                 ui->peak_display->setText(QString::fromStdString(format_db(peak_db, DB_BARE)));
601                 if (peak_db > -0.1f) {  // -0.1 dBFS is EBU peak limit.
602                         ui->peak_display->setStyleSheet("QLabel { background-color: red; color: white; }");
603                 } else {
604                         ui->peak_display->setStyleSheet("");
605                 }
606
607                 // NOTE: Will be invisible when using multitrack audio.
608                 ui->gainstaging_knob->blockSignals(true);
609                 ui->gainstaging_knob->setValue(lrintf(bus_levels[0].gain_staging_db * 10.0f));
610                 ui->gainstaging_knob->blockSignals(false);
611                 ui->gainstaging_db_display->setText(
612                         QString::fromStdString(format_db(bus_levels[0].gain_staging_db, DB_WITH_SIGN)));
613
614                 ui->makeup_gain_knob->blockSignals(true);
615                 ui->makeup_gain_knob->setValue(lrintf(final_makeup_gain_db * 10.0f));
616                 ui->makeup_gain_knob->blockSignals(false);
617                 ui->makeup_gain_db_display->setText(
618                         QString::fromStdString(format_db(final_makeup_gain_db, DB_WITH_SIGN)));
619                 ui->makeup_gain_db_display_2->setText(
620                         QString::fromStdString(format_db(final_makeup_gain_db, DB_WITH_SIGN)));
621         });
622 }
623
624 void MainWindow::relayout()
625 {
626         int height = ui->vertical_layout->geometry().height();
627
628         double remaining_height = height;
629
630         // Allocate the height; the most important part is to keep the main displays
631         // at 16:9 if at all possible.
632         double me_width = ui->me_preview->width();
633         double me_height = me_width * 9.0 / 16.0 + ui->label_preview->height() + ui->preview_vertical_layout->spacing();
634
635         // TODO: Scale the widths when we need to do this.
636         if (me_height / double(height) > 0.8) {
637                 me_height = height * 0.8;
638         }
639         remaining_height -= me_height + ui->vertical_layout->spacing();
640
641         // Space between the M/E displays and the audio strip.
642         remaining_height -= ui->vertical_layout->spacing();
643
644         // The label above the audio strip.
645         double compact_label_height = ui->compact_label->geometry().height() +
646                 ui->compact_audio_layout->spacing();
647         remaining_height -= compact_label_height;
648
649         // The previews will be constrained by the remaining height, and the width.
650         double preview_label_height = previews[0]->title_bar->geometry().height() +
651                 previews[0]->main_vertical_layout->spacing();
652         int preview_total_width = ui->preview_displays->geometry().width() - (previews.size() - 1) * ui->preview_displays->spacing();
653         double preview_height = min(remaining_height - preview_label_height, (preview_total_width / double(previews.size())) * 9.0 / 16.0);
654         remaining_height -= preview_height + preview_label_height + ui->vertical_layout->spacing();
655
656         ui->vertical_layout->setStretch(0, lrintf(me_height));
657         ui->vertical_layout->setStretch(1,
658                 lrintf(compact_label_height) +
659                 lrintf(remaining_height) +
660                 lrintf(preview_height + preview_label_height));  // Audio strip and previews together.
661
662         ui->compact_audio_layout->setStretch(0, lrintf(compact_label_height));
663         ui->compact_audio_layout->setStretch(1, lrintf(remaining_height));  // Audio strip.
664         ui->compact_audio_layout->setStretch(2, lrintf(preview_height + preview_label_height));
665
666         // Set the widths for the previews.
667         double preview_width = preview_height * 16.0 / 9.0;
668         for (unsigned i = 0; i < previews.size(); ++i) {
669                 ui->preview_displays->setStretch(i, lrintf(preview_width));
670         }
671
672         // The preview horizontal spacer.
673         double remaining_preview_width = preview_total_width - previews.size() * preview_width;
674         ui->preview_displays->setStretch(previews.size(), lrintf(remaining_preview_width));
675 }
676
677 void MainWindow::set_transition_names(vector<string> transition_names)
678 {
679         if (transition_names.size() < 1 || transition_names[0].empty()) {
680                 transition_btn1->setText(QString(""));
681         } else {
682                 transition_btn1->setText(QString::fromStdString(transition_names[0] + " (J)"));
683                 ui->transition_btn1->setShortcut(QKeySequence("J"));
684         }
685         if (transition_names.size() < 2 || transition_names[1].empty()) {
686                 transition_btn2->setText(QString(""));
687         } else {
688                 transition_btn2->setText(QString::fromStdString(transition_names[1] + " (K)"));
689                 ui->transition_btn2->setShortcut(QKeySequence("K"));
690         }
691         if (transition_names.size() < 3 || transition_names[2].empty()) {
692                 transition_btn3->setText(QString(""));
693         } else {
694                 transition_btn3->setText(QString::fromStdString(transition_names[2] + " (L)"));
695                 ui->transition_btn3->setShortcut(QKeySequence("L"));
696         }
697 }
698
699 void MainWindow::update_channel_name(Mixer::Output output, const string &name)
700 {
701         if (output >= Mixer::OUTPUT_INPUT0) {
702                 unsigned channel = output - Mixer::OUTPUT_INPUT0;
703                 previews[channel]->label->setText(name.c_str());
704         }
705 }
706
707 void MainWindow::update_channel_color(Mixer::Output output, const string &color)
708 {
709         if (output >= Mixer::OUTPUT_INPUT0) {
710                 unsigned channel = output - Mixer::OUTPUT_INPUT0;
711                 previews[channel]->frame->setStyleSheet(QString::fromStdString("background-color:" + color));
712         }
713 }
714
715 void MainWindow::transition_clicked(int transition_number)
716 {
717         global_mixer->transition_clicked(transition_number);
718 }
719
720 void MainWindow::channel_clicked(int channel_number)
721 {
722         if (current_wb_pick_display == channel_number) {
723                 // The picking was already done from eventFilter(), since we don't get
724                 // the mouse pointer here.
725         } else {
726                 global_mixer->channel_clicked(channel_number);
727         }
728 }
729
730 void MainWindow::wb_button_clicked(int channel_number)
731 {
732         current_wb_pick_display = channel_number;
733         QApplication::setOverrideCursor(Qt::CrossCursor);
734 }
735
736 bool MainWindow::eventFilter(QObject *watched, QEvent *event)
737 {
738         if (current_wb_pick_display != -1 &&
739             event->type() == QEvent::MouseButtonRelease &&
740             watched->isWidgetType()) {
741                 QApplication::restoreOverrideCursor();
742                 if (watched == previews[current_wb_pick_display]->display) {
743                         const QMouseEvent *mouse_event = (QMouseEvent *)event;
744                         set_white_balance(current_wb_pick_display, mouse_event->x(), mouse_event->y());
745                 } else {
746                         // The user clicked on something else, give up.
747                         // (The click goes through, which might not be ideal, but, yes.)
748                         current_wb_pick_display = -1;
749                 }
750         }
751         return false;
752 }
753
754 namespace {
755
756 double srgb_to_linear(double x)
757 {
758         if (x < 0.04045) {
759                 return x / 12.92;
760         } else {
761                 return pow((x + 0.055) / 1.055, 2.4);
762         }
763 }
764
765 }  // namespace
766
767 void MainWindow::set_white_balance(int channel_number, int x, int y)
768 {
769         // Set the white balance to neutral for the grab. It's probably going to
770         // flicker a bit, but hopefully this display is not live anyway.
771         global_mixer->set_wb(Mixer::OUTPUT_INPUT0 + channel_number, 0.5, 0.5, 0.5);
772         previews[channel_number]->display->updateGL();
773         QRgb reference_color = previews[channel_number]->display->grabFrameBuffer().pixel(x, y);
774
775         double r = srgb_to_linear(qRed(reference_color) / 255.0);
776         double g = srgb_to_linear(qGreen(reference_color) / 255.0);
777         double b = srgb_to_linear(qBlue(reference_color) / 255.0);
778         global_mixer->set_wb(Mixer::OUTPUT_INPUT0 + channel_number, r, g, b);
779         previews[channel_number]->display->updateGL();
780 }