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