]> git.sesse.net Git - nageru/blob - nageru/mainwindow.cpp
Set CEF autoplay policy to be more lenient.
[nageru] / nageru / mainwindow.cpp
1 #include "mainwindow.h"
2
3 #include <assert.h>
4 #include <signal.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
8 #include <QAbstractButton>
9 #include <QAbstractSlider>
10 #include <QAction>
11 #include <QActionGroup>
12 #include <QApplication>
13 #include <QBoxLayout>
14 #include <QCheckBox>
15 #include <QDesktopServices>
16 #include <QDial>
17 #include <QDialog>
18 #include <QEvent>
19 #include <QFlags>
20 #include <QFrame>
21 #include <QImage>
22 #include <QInputDialog>
23 #include <QKeySequence>
24 #include <QLabel>
25 #include <QLayoutItem>
26 #include <QMainWindow>
27 #include <QMenuBar>
28 #include <QMessageBox>
29 #include <QMouseEvent>
30 #include <QObject>
31 #include <QPaintDevice>
32 #include <QPushButton>
33 #include <QRect>
34 #include <QRgb>
35 #include <QShortcut>
36 #include <QStackedWidget>
37 #include <QToolButton>
38 #include <QUrl>
39 #include <QWidget>
40 #include <algorithm>
41 #include <chrono>
42 #include <cmath>
43 #include <functional>
44 #include <limits>
45 #include <memory>
46 #include <string>
47 #include <sys/types.h>
48 #include <vector>
49
50 #include "audio_mixer.h"
51 #include "midi_mapper.h"
52 #include "shared/aboutdialog.h"
53 #include "alsa_pool.h"
54 #include "analyzer.h"
55 #include "clickable_label.h"
56 #include "context_menus.h"
57 #include "correlation_meter.h"
58 #include "shared/disk_space_estimator.h"
59 #include "ellipsis_label.h"
60 #include "flags.h"
61 #include "glwidget.h"
62 #include "input_mapping.h"
63 #include "input_mapping_dialog.h"
64 #include "lrameter.h"
65 #include "nageru_midi_mapping.pb.h"
66 #include "midi_mapping_dialog.h"
67 #include "mixer.h"
68 #include "nonlinear_fader.h"
69 #include "shared/post_to_main_thread.h"
70 #include "theme.h"
71 #include "ui_audio_expanded_view.h"
72 #include "ui_audio_miniview.h"
73 #include "ui_display.h"
74 #include "ui_mainwindow.h"
75 #include "vumeter.h"
76
77 using namespace std;
78 using namespace std::chrono;
79 using namespace std::placeholders;
80
81 Q_DECLARE_METATYPE(std::string);
82 Q_DECLARE_METATYPE(std::vector<std::string>);
83
84 MainWindow *global_mainwindow = nullptr;
85
86 // -0.1 dBFS is EBU peak limit. We use it consistently, even for the bus meters
87 // (which don't calculate interpolate peak, and in general don't follow EBU recommendations).
88 constexpr float peak_limit_dbfs = -0.1f;
89
90 namespace {
91
92 void schedule_cut_signal(int ignored)
93 {
94         global_mixer->schedule_cut();
95 }
96
97 void quit_signal(int ignored)
98 {
99         global_mainwindow->close();
100 }
101
102 void slave_knob(QDial *master, QDial *slave)
103 {
104         QWidget::connect(master, &QDial::valueChanged, [slave](int value){
105                 slave->blockSignals(true);
106                 slave->setValue(value);
107                 slave->blockSignals(false);
108         });
109         QWidget::connect(slave, &QDial::valueChanged, [master](int value){
110                 master->setValue(value);
111         });
112 }
113
114 void slave_checkbox(QCheckBox *master, QCheckBox *slave)
115 {
116         QWidget::connect(master, &QCheckBox::stateChanged, [slave](int state){
117                 slave->blockSignals(true);
118                 slave->setCheckState(Qt::CheckState(state));
119                 slave->blockSignals(false);
120         });
121         QWidget::connect(slave, &QCheckBox::stateChanged, [master](int state){
122                 master->setCheckState(Qt::CheckState(state));
123         });
124 }
125
126 void slave_fader(NonLinearFader *master, NonLinearFader *slave)
127 {
128         QWidget::connect(master, &NonLinearFader::dbValueChanged, [slave](double value) {
129                 slave->blockSignals(true);
130                 slave->setDbValue(value);
131                 slave->blockSignals(false);
132         });
133         QWidget::connect(slave, &NonLinearFader::dbValueChanged, [master](double value){
134                 master->setDbValue(value);
135         });
136 }
137
138 constexpr unsigned DB_WITH_SIGN = 0x1;
139 constexpr unsigned DB_BARE = 0x2;
140
141 string format_db(double db, unsigned flags)
142 {
143         string text;
144         if (flags & DB_WITH_SIGN) {
145                 if (isfinite(db)) {
146                         char buf[256];
147                         snprintf(buf, sizeof(buf), "%+.1f", db);
148                         text = buf;
149                 } else if (db < 0.0) {
150                         text = "-∞";
151                 } else {
152                         // Should never happen, really.
153                         text = "+∞";
154                 }
155         } else {
156                 if (isfinite(db)) {
157                         char buf[256];
158                         snprintf(buf, sizeof(buf), "%.1f", db);
159                         text = buf;
160                 } else if (db < 0.0) {
161                         text = "-∞";
162                 } else {
163                         // Should never happen, really.
164                         text = "∞";
165                 }
166         }
167         if (!(flags & DB_BARE)) {
168                 text += " dB";
169         }
170         return text;
171 }
172
173 void set_peak_label(QLabel *peak_label, float peak_db)
174 {
175         peak_label->setText(QString::fromStdString(format_db(peak_db, DB_BARE)));
176
177         if (peak_db > peak_limit_dbfs) {
178                 peak_label->setStyleSheet("QLabel { background-color: red; color: white; }");
179         } else {
180                 peak_label->setStyleSheet("");
181         }
182 }
183
184 string get_bus_desc_label(const InputMapping::Bus &bus)
185 {
186         string suffix;
187         if (bus.device.type == InputSourceType::ALSA_INPUT) {
188                 ALSAPool::Device::State state = global_audio_mixer->get_alsa_card_state(bus.device.index);
189                 if (state == ALSAPool::Device::State::STARTING) {
190                         suffix = " (busy)";
191                 } else if (state == ALSAPool::Device::State::DEAD) {
192                         suffix = " (dead)";
193                 }
194         }
195
196         return bus.name + suffix;
197 }
198
199 }  // namespace
200
201 MainWindow::MainWindow()
202         : ui(new Ui::MainWindow), midi_mapper(this)
203 {
204         global_mainwindow = this;
205         ui->setupUi(this);
206
207         global_disk_space_estimator = new DiskSpaceEstimator(bind(&MainWindow::report_disk_space, this, _1, _2, _3));
208         disk_free_label = new QLabel(this);
209         disk_free_label->setStyleSheet("QLabel {padding-right: 5px;}");
210         ui->menuBar->setCornerWidget(disk_free_label);
211
212         QActionGroup *audio_mapping_group = new QActionGroup(this);
213         ui->simple_audio_mode->setActionGroup(audio_mapping_group);
214         ui->multichannel_audio_mode->setActionGroup(audio_mapping_group);
215
216         ui->me_live->set_output(Mixer::OUTPUT_LIVE);
217         ui->me_preview->set_output(Mixer::OUTPUT_PREVIEW);
218
219         // The menus.
220         connect(ui->cut_action, &QAction::triggered, this, &MainWindow::cut_triggered);
221         connect(ui->exit_action, &QAction::triggered, this, &MainWindow::exit_triggered);
222         connect(ui->manual_action, &QAction::triggered, this, &MainWindow::manual_triggered);
223         connect(ui->about_action, &QAction::triggered, this, &MainWindow::about_triggered);
224         connect(ui->open_analyzer_action, &QAction::triggered, this, &MainWindow::open_analyzer_triggered);
225         connect(ui->simple_audio_mode, &QAction::triggered, this, &MainWindow::simple_audio_mode_triggered);
226         connect(ui->multichannel_audio_mode, &QAction::triggered, this, &MainWindow::multichannel_audio_mode_triggered);
227         connect(ui->input_mapping_action, &QAction::triggered, this, &MainWindow::input_mapping_triggered);
228         connect(ui->midi_mapping_action, &QAction::triggered, this, &MainWindow::midi_mapping_triggered);
229         connect(ui->timecode_stream_action, &QAction::triggered, this, &MainWindow::timecode_stream_triggered);
230         connect(ui->timecode_stdout_action, &QAction::triggered, this, &MainWindow::timecode_stdout_triggered);
231
232         ui->timecode_stream_action->setChecked(global_flags.display_timecode_in_stream);
233         ui->timecode_stdout_action->setChecked(global_flags.display_timecode_on_stdout);
234
235         if (global_flags.x264_video_to_http && isinf(global_flags.x264_crf)) {
236                 connect(ui->x264_bitrate_action, &QAction::triggered, this, &MainWindow::x264_bitrate_triggered);
237         } else {
238                 ui->x264_bitrate_action->setEnabled(false);
239         }
240
241         connect(ui->video_menu, &QMenu::aboutToShow, [this]{
242                 fill_hdmi_sdi_output_device_menu(ui->hdmi_sdi_output_device_menu);
243                 fill_hdmi_sdi_output_resolution_menu(ui->hdmi_sdi_output_resolution_menu);
244         });
245
246         // Hook up the transition buttons. (Keyboard shortcuts are set in set_transition_names().)
247         // TODO: Make them dynamic.
248         connect(ui->transition_btn1, &QPushButton::clicked, bind(&MainWindow::transition_clicked, this, 0));
249         connect(ui->transition_btn2, &QPushButton::clicked, bind(&MainWindow::transition_clicked, this, 1));
250         connect(ui->transition_btn3, &QPushButton::clicked, bind(&MainWindow::transition_clicked, this, 2));
251
252         // Aiee...
253         transition_btn1 = ui->transition_btn1;
254         transition_btn2 = ui->transition_btn2;
255         transition_btn3 = ui->transition_btn3;
256         qRegisterMetaType<string>("std::string");
257         qRegisterMetaType<vector<string>>("std::vector<std::string>");
258         connect(ui->me_live, &GLWidget::transition_names_updated, this, &MainWindow::set_transition_names);
259         qRegisterMetaType<Mixer::Output>("Mixer::Output");
260
261         connect(ui->me_live, &GLWidget::name_updated, this, &MainWindow::update_channel_name);
262         connect(ui->me_preview, &GLWidget::name_updated, this, &MainWindow::update_channel_name);
263
264         // Hook up the prev/next buttons on the audio views.
265         connect(ui->compact_prev_page, &QAbstractButton::clicked, this, &MainWindow::prev_page);
266         connect(ui->compact_next_page, &QAbstractButton::clicked, this, &MainWindow::next_page);
267         connect(ui->full_prev_page, &QAbstractButton::clicked, this, &MainWindow::prev_page);
268         connect(ui->full_next_page, &QAbstractButton::clicked, this, &MainWindow::next_page);
269         connect(ui->video_grid_prev_page, &QAbstractButton::clicked, this, &MainWindow::prev_page);
270         connect(ui->video_grid_next_page, &QAbstractButton::clicked, this, &MainWindow::next_page);
271
272         // And bind the same to PgUp/PgDown.
273         connect(new QShortcut(QKeySequence::MoveToNextPage, this), &QShortcut::activated, this, &MainWindow::next_page);
274         connect(new QShortcut(QKeySequence::MoveToPreviousPage, this), &QShortcut::activated, this, &MainWindow::prev_page);
275
276         // When the audio view changes, move the previews.
277         connect(ui->audio_views, &QStackedWidget::currentChanged, bind(&MainWindow::audio_view_changed, this, _1));
278
279         if (global_flags.enable_quick_cut_keys) {
280                 ui->quick_cut_enable_action->setChecked(true);
281         }
282         connect(ui->quick_cut_enable_action, &QAction::changed, [this](){
283                 global_flags.enable_quick_cut_keys = ui->quick_cut_enable_action->isChecked();
284         });
285
286 #if HAVE_SRT
287         if (global_flags.srt_port >= 0) {
288                 char title[256];
289                 snprintf(title, sizeof(title), "Accept new SRT connections on port %d", global_flags.srt_port);
290                 ui->srt_enable_action->setChecked(true);
291                 ui->srt_enable_action->setText(title);
292                 connect(ui->srt_enable_action, &QAction::changed, [this](){
293                         global_flags.enable_srt = ui->srt_enable_action->isChecked();
294                 });
295         } else {
296                 ui->srt_enable_action->setChecked(false);
297                 ui->srt_enable_action->setEnabled(false);
298                 ui->srt_enable_action->setText("Accept new SRT connections");
299         }
300 #else
301         ui->srt_enable_action->setChecked(false);
302         ui->srt_enable_action->setEnabled(false);
303         ui->srt_enable_action->setText("Accept new SRT connections");
304 #endif
305
306         last_audio_level_callback = steady_clock::now() - seconds(1);
307
308         if (!global_flags.midi_mapping_filename.empty()) {
309                 MIDIMappingProto midi_mapping;
310                 if (!load_midi_mapping_from_file(global_flags.midi_mapping_filename, &midi_mapping)) {
311                         fprintf(stderr, "Couldn't load MIDI mapping '%s'; exiting.\n",
312                                 global_flags.midi_mapping_filename.c_str());
313                         ::abort();
314                 }
315                 midi_mapper.set_midi_mapping(midi_mapping);
316         }
317         midi_mapper.refresh_highlights();
318         midi_mapper.refresh_lights();
319         if (global_flags.fullscreen) {
320                 QMainWindow::showFullScreen();
321         }
322 }
323
324 void MainWindow::prev_page()
325 {
326         if (global_audio_mixer->get_mapping_mode() == AudioMixer::MappingMode::MULTICHANNEL) {
327                 ui->audio_views->setCurrentIndex((ui->audio_views->currentIndex() + 2) % 3);
328         } else {
329                 ui->audio_views->setCurrentIndex(2 - ui->audio_views->currentIndex());  // Switch between 0 and 2.
330         }
331 }
332
333 void MainWindow::next_page()
334 {
335         if (global_audio_mixer->get_mapping_mode() == AudioMixer::MappingMode::MULTICHANNEL) {
336                 ui->audio_views->setCurrentIndex((ui->audio_views->currentIndex() + 1) % 3);
337         } else {
338                 ui->audio_views->setCurrentIndex(2 - ui->audio_views->currentIndex());  // Switch between 0 and 2.
339         }
340 }
341
342 void MainWindow::resizeEvent(QResizeEvent* event)
343 {
344         QMainWindow::resizeEvent(event);
345
346         // Ask for a relayout, but only after the event loop is done doing relayout
347         // on everything else.
348         QMetaObject::invokeMethod(this, "relayout", Qt::QueuedConnection);
349 }
350
351 void MainWindow::mixer_created(Mixer *mixer)
352 {
353         // Make the previews.
354         unsigned num_previews = mixer->get_num_channels();
355
356         const char qwerty[] = "QWERTYUIOP";
357         for (unsigned i = 0; i < num_previews; ++i) {
358                 Mixer::Output output = Mixer::Output(Mixer::OUTPUT_INPUT0 + i);
359
360                 QWidget *preview = new QWidget(this);  // Will be connected to a layout immediately after the loop.
361                 Ui::Display *ui_display = new Ui::Display;
362                 ui_display->setupUi(preview);
363                 ui_display->label->setText(mixer->get_channel_name(output).c_str());
364                 ui_display->display->set_output(output);
365                 previews.push_back(ui_display);
366
367                 // Hook up the click.
368                 connect(ui_display->display, &GLWidget::clicked, bind(&MainWindow::channel_clicked, this, i));
369
370                 // Let the theme update the text whenever the resolution or color changed.
371                 connect(ui_display->display, &GLWidget::name_updated, this, &MainWindow::update_channel_name);
372                 connect(ui_display->display, &GLWidget::color_updated, this, &MainWindow::update_channel_color);
373
374                 // Hook up the keyboard key.
375                 QShortcut *shortcut = nullptr;
376                 if (i < 9) {
377                         shortcut = new QShortcut(QKeySequence(Qt::Key_1 + i), this);
378                 } else if (i == 9) {
379                         shortcut = new QShortcut(QKeySequence(Qt::Key_0), this);
380                 }
381                 if (shortcut != nullptr) {
382                         connect(shortcut, &QShortcut::activated, bind(&MainWindow::channel_clicked, this, i));
383                 }
384
385                 // Hook up the quick-cut key.
386                 if (i < strlen(qwerty)) {
387                         QShortcut *shortcut = new QShortcut(QKeySequence(qwerty[i]), this);
388                         connect(shortcut, &QShortcut::activated, bind(&MainWindow::quick_cut_activated, this, i));
389                 }
390
391                 // Hook up the white balance button (irrelevant if invisible).
392                 ui_display->wb_button->setVisible(mixer->get_supports_set_wb(output));
393                 connect(ui_display->wb_button, &QPushButton::clicked, bind(&MainWindow::wb_button_clicked, this, i));
394         }
395
396         // Connect the previews to the correct layout.
397         audio_view_changed(ui->audio_views->currentIndex());
398
399         global_audio_mixer->set_state_changed_callback(bind(&MainWindow::audio_state_changed, this));
400
401         slave_knob(ui->locut_cutoff_knob, ui->locut_cutoff_knob_2);
402         slave_knob(ui->limiter_threshold_knob, ui->limiter_threshold_knob_2);
403         slave_knob(ui->makeup_gain_knob, ui->makeup_gain_knob_2);
404         slave_checkbox(ui->makeup_gain_auto_checkbox, ui->makeup_gain_auto_checkbox_2);
405         slave_checkbox(ui->limiter_enabled, ui->limiter_enabled_2);
406
407         reset_audio_mapping_ui();
408
409         // TODO: Fetch all of the values these for completeness,
410         // not just the enable knobs implied by flags.
411         ui->limiter_enabled->setChecked(global_audio_mixer->get_limiter_enabled());
412         ui->makeup_gain_auto_checkbox->setChecked(global_audio_mixer->get_final_makeup_gain_auto());
413
414         // Controls used only for simple audio fetch their state from the first bus.
415         constexpr unsigned simple_bus_index = 0;
416         if (global_audio_mixer->get_mapping_mode() == AudioMixer::MappingMode::SIMPLE) {
417                 ui->locut_enabled->setChecked(global_audio_mixer->get_locut_enabled(simple_bus_index));
418                 ui->gainstaging_knob->setValue(global_audio_mixer->get_gain_staging_db(simple_bus_index));
419                 ui->gainstaging_auto_checkbox->setChecked(global_audio_mixer->get_gain_staging_auto(simple_bus_index));
420                 ui->compressor_enabled->setChecked(global_audio_mixer->get_compressor_enabled(simple_bus_index));
421                 ui->compressor_threshold_db_display->setText(
422                         QString::fromStdString(format_db(mixer->get_audio_mixer()->get_compressor_threshold_dbfs(simple_bus_index), DB_WITH_SIGN)));
423         }
424         connect(ui->locut_enabled, &QCheckBox::stateChanged, [this](int state){
425                 global_audio_mixer->set_locut_enabled(simple_bus_index, state == Qt::Checked);
426                 midi_mapper.refresh_lights();
427         });
428         connect(ui->gainstaging_knob, &QAbstractSlider::valueChanged,
429                 bind(&MainWindow::gain_staging_knob_changed, this, simple_bus_index, _1));
430         connect(ui->gainstaging_auto_checkbox, &QCheckBox::stateChanged, [this](int state){
431                 global_audio_mixer->set_gain_staging_auto(simple_bus_index, state == Qt::Checked);
432                 midi_mapper.refresh_lights();
433         });
434         connect(ui->compressor_threshold_knob, &QDial::valueChanged,
435                 bind(&MainWindow::compressor_threshold_knob_changed, this, simple_bus_index, _1));
436         connect(ui->compressor_enabled, &QCheckBox::stateChanged, [this](int state){
437                 global_audio_mixer->set_compressor_enabled(simple_bus_index, state == Qt::Checked);
438                 midi_mapper.refresh_lights();
439         });
440
441         // Global mastering controls.
442         QString limiter_threshold_label(
443                 QString::fromStdString(format_db(mixer->get_audio_mixer()->get_limiter_threshold_dbfs(), DB_WITH_SIGN)));
444         ui->limiter_threshold_db_display->setText(limiter_threshold_label);
445         ui->limiter_threshold_db_display_2->setText(limiter_threshold_label);
446
447         connect(ui->locut_cutoff_knob, &QDial::valueChanged, this, &MainWindow::cutoff_knob_changed);
448         cutoff_knob_changed(ui->locut_cutoff_knob->value());
449
450         connect(ui->makeup_gain_knob, &QAbstractSlider::valueChanged, this, &MainWindow::final_makeup_gain_knob_changed);
451         connect(ui->makeup_gain_auto_checkbox, &QCheckBox::stateChanged, [this](int state){
452                 global_audio_mixer->set_final_makeup_gain_auto(state == Qt::Checked);
453                 midi_mapper.refresh_lights();
454         });
455
456         connect(ui->limiter_threshold_knob, &QDial::valueChanged, this, &MainWindow::limiter_threshold_knob_changed);
457         connect(ui->limiter_enabled, &QCheckBox::stateChanged, [this](int state){
458                 global_audio_mixer->set_limiter_enabled(state == Qt::Checked);
459                 midi_mapper.refresh_lights();
460         });
461         connect(ui->reset_meters_button, &QPushButton::clicked, this, &MainWindow::reset_meters_button_clicked);
462         // Even though we have a reset button right next to it, the fact that
463         // the expanded audio view labels are clickable makes it natural to
464         // click this one as well.
465         connect(ui->peak_display, &ClickableLabel::clicked, this, &MainWindow::reset_meters_button_clicked);
466         mixer->get_audio_mixer()->set_audio_level_callback(bind(&MainWindow::audio_level_callback, this, _1, _2, _3, _4, _5, _6, _7, _8));
467
468         midi_mapper.refresh_highlights();
469         midi_mapper.refresh_lights();
470         midi_mapper.start_thread();
471
472         analyzer.reset(new Analyzer);
473
474         global_mixer->set_theme_menu_callback(bind(&MainWindow::setup_theme_menu, this));
475         setup_theme_menu();
476
477         struct sigaction act;
478         memset(&act, 0, sizeof(act));
479         act.sa_handler = schedule_cut_signal;
480         act.sa_flags = SA_RESTART;
481         sigaction(SIGHUP, &act, nullptr);
482
483         // Mostly for debugging. Don't override SIGINT, that's so evil if
484         // shutdown isn't instant.
485         memset(&act, 0, sizeof(act));
486         act.sa_handler = quit_signal;
487         act.sa_flags = SA_RESTART;
488         sigaction(SIGUSR1, &act, nullptr);
489 }
490
491 void MainWindow::reset_audio_mapping_ui()
492 {
493         bool simple = (global_audio_mixer->get_mapping_mode() == AudioMixer::MappingMode::SIMPLE);
494
495         ui->simple_audio_mode->setChecked(simple);
496         ui->multichannel_audio_mode->setChecked(!simple);
497         ui->input_mapping_action->setEnabled(!simple);
498         ui->midi_mapping_action->setEnabled(!simple);
499
500         ui->locut_enabled->setVisible(simple);
501         ui->gainstaging_label->setVisible(simple);
502         ui->gainstaging_knob->setVisible(simple);
503         ui->gainstaging_db_display->setVisible(simple);
504         ui->gainstaging_auto_checkbox->setVisible(simple);
505         ui->compressor_threshold_label->setVisible(simple);
506         ui->compressor_threshold_knob->setVisible(simple);
507         ui->compressor_threshold_db_display->setVisible(simple);
508         ui->compressor_enabled->setVisible(simple);
509
510         setup_audio_miniview();
511         setup_audio_expanded_view();
512
513         if (simple) {
514                 ui->compact_label->setText("Compact audio view (1/2)  ");
515                 ui->video_grid_label->setText("Video grid display (2/2)  ");
516                 if (ui->audio_views->currentIndex() == 1) {
517                         // Full audio view is not available in simple mode.
518                         ui->audio_views->setCurrentIndex(0);
519                 }
520         } else {
521                 ui->compact_label->setText("Compact audio view (1/3)  ");
522                 ui->full_label->setText("Full audio view (2/3)  ");
523                 ui->video_grid_label->setText("Video grid display (3/3)  ");
524         }
525
526         midi_mapper.refresh_highlights();
527         midi_mapper.refresh_lights();
528 }
529
530 void MainWindow::setup_audio_miniview()
531 {
532         // Remove any existing channels.
533         for (QLayoutItem *item; (item = ui->faders->takeAt(0)) != nullptr; ) {
534                 delete item->widget();
535                 delete item;
536         }
537         audio_miniviews.clear();
538
539         if (global_audio_mixer->get_mapping_mode() == AudioMixer::MappingMode::SIMPLE) {
540                 return;
541         }
542
543         // Set up brand new ones from the input mapping.
544         InputMapping mapping = global_audio_mixer->get_input_mapping();
545         audio_miniviews.resize(mapping.buses.size());
546         for (unsigned bus_index = 0; bus_index < mapping.buses.size(); ++bus_index) {
547                 QWidget *channel = new QWidget(this);
548                 Ui::AudioMiniView *ui_audio_miniview = new Ui::AudioMiniView;
549                 ui_audio_miniview->setupUi(channel);
550                 ui_audio_miniview->bus_desc_label->setFullText(
551                         QString::fromStdString(get_bus_desc_label(mapping.buses[bus_index])));
552                 audio_miniviews[bus_index] = ui_audio_miniview;
553
554                 // Set up the peak meter.
555                 VUMeter *peak_meter = ui_audio_miniview->peak_meter;
556                 peak_meter->set_min_level(-30.0f);
557                 peak_meter->set_max_level(0.0f);
558                 peak_meter->set_ref_level(0.0f);
559
560                 ui_audio_miniview->fader->setDbValue(global_audio_mixer->get_fader_volume(bus_index));
561
562                 ui->faders->addWidget(channel);
563
564                 connect(ui_audio_miniview->fader, &NonLinearFader::dbValueChanged,
565                         bind(&MainWindow::mini_fader_changed, this, bus_index, _1));
566                 connect(ui_audio_miniview->peak_display_label, &ClickableLabel::clicked,
567                         [bus_index]() {
568                                 global_audio_mixer->reset_peak(bus_index);
569                         });
570         }
571 }
572
573 void MainWindow::setup_audio_expanded_view()
574 {
575         // Remove any existing channels.
576         for (QLayoutItem *item; (item = ui->buses->takeAt(0)) != nullptr; ) {
577                 delete item->widget();
578                 delete item;
579         }
580         audio_expanded_views.clear();
581
582         if (global_audio_mixer->get_mapping_mode() == AudioMixer::MappingMode::SIMPLE) {
583                 return;
584         }
585
586         // Set up brand new ones from the input mapping.
587         InputMapping mapping = global_audio_mixer->get_input_mapping();
588         audio_expanded_views.resize(mapping.buses.size());
589         for (unsigned bus_index = 0; bus_index < mapping.buses.size(); ++bus_index) {
590                 QWidget *channel = new QWidget(this);
591                 Ui::AudioExpandedView *ui_audio_expanded_view = new Ui::AudioExpandedView;
592                 ui_audio_expanded_view->setupUi(channel);
593                 ui_audio_expanded_view->bus_desc_label->setFullText(
594                         QString::fromStdString(get_bus_desc_label(mapping.buses[bus_index])));
595                 audio_expanded_views[bus_index] = ui_audio_expanded_view;
596                 update_stereo_knob_and_label(bus_index, lrintf(100.0f * global_audio_mixer->get_stereo_width(bus_index)));
597                 update_eq_label(bus_index, EQ_BAND_TREBLE, global_audio_mixer->get_eq(bus_index, EQ_BAND_TREBLE));
598                 update_eq_label(bus_index, EQ_BAND_MID, global_audio_mixer->get_eq(bus_index, EQ_BAND_MID));
599                 update_eq_label(bus_index, EQ_BAND_BASS, global_audio_mixer->get_eq(bus_index, EQ_BAND_BASS));
600                 ui_audio_expanded_view->fader->setDbValue(global_audio_mixer->get_fader_volume(bus_index));
601                 ui_audio_expanded_view->mute_button->setChecked(global_audio_mixer->get_mute(bus_index));
602                 connect(ui_audio_expanded_view->mute_button, &QPushButton::toggled,
603                         bind(&MainWindow::mute_button_toggled, this, bus_index, _1));
604                 ui->buses->addWidget(channel);
605
606                 ui_audio_expanded_view->locut_enabled->setChecked(global_audio_mixer->get_locut_enabled(bus_index));
607                 connect(ui_audio_expanded_view->locut_enabled, &QCheckBox::stateChanged, [this, bus_index](int state){
608                         global_audio_mixer->set_locut_enabled(bus_index, state == Qt::Checked);
609                         midi_mapper.refresh_lights();
610                 });
611
612                 connect(ui_audio_expanded_view->stereo_width_knob, &QDial::valueChanged,
613                         bind(&MainWindow::stereo_width_knob_changed, this, bus_index, _1));
614
615                 connect(ui_audio_expanded_view->treble_knob, &QDial::valueChanged,
616                         bind(&MainWindow::eq_knob_changed, this, bus_index, EQ_BAND_TREBLE, _1));
617                 connect(ui_audio_expanded_view->mid_knob, &QDial::valueChanged,
618                         bind(&MainWindow::eq_knob_changed, this, bus_index, EQ_BAND_MID, _1));
619                 connect(ui_audio_expanded_view->bass_knob, &QDial::valueChanged,
620                         bind(&MainWindow::eq_knob_changed, this, bus_index, EQ_BAND_BASS, _1));
621
622                 ui_audio_expanded_view->gainstaging_knob->setValue(global_audio_mixer->get_gain_staging_db(bus_index));
623                 ui_audio_expanded_view->gainstaging_auto_checkbox->setChecked(global_audio_mixer->get_gain_staging_auto(bus_index));
624                 ui_audio_expanded_view->compressor_enabled->setChecked(global_audio_mixer->get_compressor_enabled(bus_index));
625
626                 connect(ui_audio_expanded_view->gainstaging_knob, &QAbstractSlider::valueChanged, bind(&MainWindow::gain_staging_knob_changed, this, bus_index, _1));
627                 connect(ui_audio_expanded_view->gainstaging_auto_checkbox, &QCheckBox::stateChanged, [this, bus_index](int state){
628                         global_audio_mixer->set_gain_staging_auto(bus_index, state == Qt::Checked);
629                         midi_mapper.refresh_lights();
630                 });
631
632                 connect(ui_audio_expanded_view->compressor_threshold_knob, &QDial::valueChanged, bind(&MainWindow::compressor_threshold_knob_changed, this, bus_index, _1));
633                 connect(ui_audio_expanded_view->compressor_enabled, &QCheckBox::stateChanged, [this, bus_index](int state){
634                         global_audio_mixer->set_compressor_enabled(bus_index, state == Qt::Checked);
635                         midi_mapper.refresh_lights();
636                 });
637
638                 slave_fader(audio_miniviews[bus_index]->fader, ui_audio_expanded_view->fader);
639
640                 // Set up the peak meter.
641                 VUMeter *peak_meter = ui_audio_expanded_view->peak_meter;
642                 peak_meter->set_min_level(-30.0f);
643                 peak_meter->set_max_level(0.0f);
644                 peak_meter->set_ref_level(0.0f);
645
646                 connect(ui_audio_expanded_view->peak_display_label, &ClickableLabel::clicked,
647                         [this, bus_index]() {
648                                 global_audio_mixer->reset_peak(bus_index);
649                                 midi_mapper.refresh_lights();
650                         });
651         }
652
653         update_cutoff_labels(global_audio_mixer->get_locut_cutoff());
654 }
655
656 void MainWindow::mixer_shutting_down()
657 {
658         ui->me_live->shutdown();
659         ui->me_preview->shutdown();
660
661         for (Ui::Display *display : previews) {
662                 display->display->shutdown();
663         }
664
665         analyzer->mixer_shutting_down();
666 }
667
668 void MainWindow::cut_triggered()
669 {
670         global_mixer->schedule_cut();
671 }
672
673 void MainWindow::x264_bitrate_triggered()
674 {
675         bool ok;
676         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);
677         if (ok && new_bitrate >= 100 && new_bitrate <= 100000) {
678                 global_flags.x264_bitrate = new_bitrate;
679                 global_mixer->change_x264_bitrate(new_bitrate);
680         }
681 }
682
683 void MainWindow::exit_triggered()
684 {
685         close();
686 }
687
688 void MainWindow::manual_triggered()
689 {
690         if (!QDesktopServices::openUrl(QUrl("https://nageru.sesse.net/doc/"))) {
691                 QMessageBox msgbox;
692                 msgbox.setText("Could not launch manual in web browser.\nPlease see https://nageru.sesse.net/doc/ manually.");
693                 msgbox.exec();
694         }
695 }
696
697 void MainWindow::about_triggered()
698 {
699         AboutDialog("Nageru", "Realtime video mixer").exec();
700 }
701
702 void MainWindow::open_analyzer_triggered()
703 {
704         analyzer->show();
705 }
706
707 void MainWindow::simple_audio_mode_triggered()
708 {
709         if (global_audio_mixer->get_mapping_mode() == AudioMixer::MappingMode::SIMPLE) {
710                 return;
711         }
712         unsigned card_index = global_audio_mixer->get_simple_input();
713         if (card_index == numeric_limits<unsigned>::max()) {
714                 QMessageBox::StandardButton reply =
715                         QMessageBox::question(this,
716                                 "Mapping too complex",
717                                 "The current audio mapping is too complicated to be representable in simple mode, "
718                                         "and will be discarded if you proceed. Really go to simple audio mode?",
719                                 QMessageBox::Yes | QMessageBox::No);
720                 if (reply == QMessageBox::No) {
721                         ui->simple_audio_mode->setChecked(false);
722                         ui->multichannel_audio_mode->setChecked(true);
723                         return;
724                 }
725                 card_index = 0;
726         }
727         global_audio_mixer->set_simple_input(/*card_index=*/card_index);
728         reset_audio_mapping_ui();
729 }
730
731 void MainWindow::multichannel_audio_mode_triggered()
732 {
733         if (global_audio_mixer->get_mapping_mode() == AudioMixer::MappingMode::MULTICHANNEL) {
734                 return;
735         }
736
737         // Take the generated input mapping from the simple input,
738         // and set it as a normal multichannel mapping, which causes
739         // the mode to go to multichannel.
740         global_audio_mixer->set_input_mapping(global_audio_mixer->get_input_mapping());
741         reset_audio_mapping_ui();
742 }
743
744 void MainWindow::input_mapping_triggered()
745 {
746         if (InputMappingDialog().exec() == QDialog::Accepted) {
747                 setup_audio_miniview();
748                 setup_audio_expanded_view();
749         }
750         midi_mapper.refresh_highlights();
751         midi_mapper.refresh_lights();
752 }
753
754 void MainWindow::midi_mapping_triggered()
755 {
756         MIDIMappingDialog(&midi_mapper).exec();
757 }
758
759 void MainWindow::timecode_stream_triggered()
760 {
761         global_mixer->set_display_timecode_in_stream(ui->timecode_stream_action->isChecked());
762 }
763
764 void MainWindow::timecode_stdout_triggered()
765 {
766         global_mixer->set_display_timecode_on_stdout(ui->timecode_stdout_action->isChecked());
767 }
768
769 void MainWindow::gain_staging_knob_changed(unsigned bus_index, int value)
770 {
771         if (bus_index == 0) {
772                 ui->gainstaging_auto_checkbox->setCheckState(Qt::Unchecked);
773         }
774         if (bus_index < audio_expanded_views.size()) {
775                 audio_expanded_views[bus_index]->gainstaging_auto_checkbox->setCheckState(Qt::Unchecked);
776         }
777
778         float gain_db = value * 0.1f;
779         global_audio_mixer->set_gain_staging_db(bus_index, gain_db);
780
781         // The label will be updated by the audio level callback.
782 }
783
784 void MainWindow::final_makeup_gain_knob_changed(int value)
785 {
786         ui->makeup_gain_auto_checkbox->setCheckState(Qt::Unchecked);
787
788         float gain_db = value * 0.1f;
789         global_audio_mixer->set_final_makeup_gain_db(gain_db);
790
791         // The label will be updated by the audio level callback.
792 }
793
794 void MainWindow::cutoff_knob_changed(int value)
795 {
796         float octaves = value * 0.1f;
797         float cutoff_hz = 20.0 * pow(2.0, octaves);
798         global_audio_mixer->set_locut_cutoff(cutoff_hz);
799         update_cutoff_labels(cutoff_hz);
800 }
801
802 void MainWindow::update_cutoff_labels(float cutoff_hz)
803 {
804         char buf[256];
805         snprintf(buf, sizeof(buf), "%ld Hz", lrintf(cutoff_hz));
806         ui->locut_cutoff_display->setText(buf);
807         ui->locut_cutoff_display_2->setText(buf);
808
809         for (unsigned bus_index = 0; bus_index < audio_expanded_views.size(); ++bus_index) {
810                 audio_expanded_views[bus_index]->locut_enabled->setText(
811                         QString("Lo-cut: ") + buf);
812         }
813 }
814
815 void MainWindow::report_disk_space(off_t free_bytes, double estimated_seconds_left, double file_length_seconds)
816 {
817         char time_str[256];
818         if (estimated_seconds_left < 60.0) {
819                 strcpy(time_str, "<font color=\"red\">Less than a minute</font>");
820         } else if (estimated_seconds_left < 1800.0) {  // Less than half an hour: Xm Ys (red).
821                 int s = lrintf(estimated_seconds_left);
822                 int m = s / 60;
823                 s %= 60;
824                 snprintf(time_str, sizeof(time_str), "<font color=\"red\">%dm %ds</font>", m, s);
825         } else if (estimated_seconds_left < 3600.0) {  // Less than an hour: Xm.
826                 int m = lrintf(estimated_seconds_left / 60.0);
827                 snprintf(time_str, sizeof(time_str), "%dm", m);
828         } else if (estimated_seconds_left < 36000.0) {  // Less than ten hours: Xh Ym.
829                 int m = lrintf(estimated_seconds_left / 60.0);
830                 int h = m / 60;
831                 m %= 60;
832                 snprintf(time_str, sizeof(time_str), "%dh %dm", h, m);
833         } else {  // More than ten hours: Xh.
834                 int h = lrintf(estimated_seconds_left / 3600.0);
835                 snprintf(time_str, sizeof(time_str), "%dh", h);
836         }
837         char buf[256];
838         snprintf(buf, sizeof(buf), "Disk free: %'.0f MB (approx. %s)", free_bytes / 1048576.0, time_str);
839
840         // NOTE: The default formatter does not use file_length_seconds for anything,
841         // but the theme might want to do so.
842         std::string label = global_mixer->format_status_line(buf, file_length_seconds);
843
844         post_to_main_thread([this, label]{
845                 disk_free_label->setText(QString::fromStdString(label));
846                 ui->menuBar->setCornerWidget(disk_free_label);  // Need to set this again for the sizing to get right.
847         });
848 }
849
850 void MainWindow::stereo_width_knob_changed(unsigned bus_index, int value)
851 {
852         float stereo_width = value * 0.01f;
853         global_audio_mixer->set_stereo_width(bus_index, stereo_width);
854
855         update_stereo_label(bus_index, value);
856 }
857
858 void MainWindow::eq_knob_changed(unsigned bus_index, EQBand band, int value)
859 {
860         float gain_db = value * 0.1f;
861         global_audio_mixer->set_eq(bus_index, band, gain_db);
862
863         update_eq_label(bus_index, band, gain_db);
864 }
865
866 void MainWindow::update_stereo_knob_and_label(unsigned bus_index, int stereo_width_percent)
867 {
868         Ui::AudioExpandedView *view = audio_expanded_views[bus_index];
869
870         if (global_audio_mixer->is_mono(bus_index)) {
871                 view->stereo_width_knob->setEnabled(false);
872                 view->stereo_width_label->setEnabled(false);
873         } else {
874                 view->stereo_width_knob->setEnabled(true);
875                 view->stereo_width_label->setEnabled(true);
876         }
877         view->stereo_width_knob->setValue(stereo_width_percent);
878         update_stereo_label(bus_index, stereo_width_percent);
879 }
880
881 void MainWindow::update_stereo_label(unsigned bus_index, int stereo_width_percent)
882 {
883         Ui::AudioExpandedView *view = audio_expanded_views[bus_index];
884
885         if (global_audio_mixer->is_mono(bus_index)) {
886                 view->stereo_width_label->setText("Mono");
887         } else {
888                 char buf[256];
889                 snprintf(buf, sizeof(buf), "Stereo: %d%%", stereo_width_percent);
890                 view->stereo_width_label->setText(buf);
891         }
892 }
893
894 void MainWindow::update_eq_label(unsigned bus_index, EQBand band, float gain_db)
895 {
896         Ui::AudioExpandedView *view = audio_expanded_views[bus_index];
897         string db_string = format_db(gain_db, DB_WITH_SIGN);
898         switch (band) {
899         case EQ_BAND_TREBLE:
900                 view->treble_label->setText(QString::fromStdString("Treble: " + db_string));
901                 break;
902         case EQ_BAND_MID:
903                 view->mid_label->setText(QString::fromStdString("Mid: " + db_string));
904                 break;
905         case EQ_BAND_BASS:
906                 view->bass_label->setText(QString::fromStdString("Bass: " + db_string));
907                 break;
908         default:
909                 assert(false);
910         }
911 }
912
913 void MainWindow::setup_theme_menu()
914 {
915         Theme::MenuEntry *root_menu = global_mixer->get_theme_menu();
916
917         // Remove the old menu, if any.
918         if (theme_menu != nullptr) {
919                 ui->menuBar->removeAction(theme_menu->menuAction());
920                 theme_menu = nullptr;
921         }
922
923         if (root_menu != nullptr) {
924                 assert(root_menu->is_submenu);
925                 if (!root_menu->submenu.empty()) {
926                         theme_menu = new QMenu("&Theme");
927                         fill_menu_from_theme_menu(root_menu->submenu, theme_menu);
928                         ui->menuBar->insertMenu(ui->menu_Help->menuAction(), theme_menu);
929                 }
930         }
931 }
932
933 void MainWindow::fill_menu_from_theme_menu(const vector<unique_ptr<Theme::MenuEntry>> &entries, QMenu *menu)
934 {
935         for (const unique_ptr<Theme::MenuEntry> &entry : entries) {
936                 if (entry->is_submenu) {
937                         QMenu *submenu = new QMenu(QString::fromStdString(entry->text));
938                         fill_menu_from_theme_menu(entry->submenu, submenu);
939                         menu->addMenu(submenu);
940                         continue;
941                 }
942
943                 QAction *action = menu->addAction(QString::fromStdString(entry->text));
944                 if (entry->entry.flags == Theme::MenuEntry::CHECKABLE) {
945                         action->setCheckable(true);
946                 } else if (entry->entry.flags == Theme::MenuEntry::CHECKED) {
947                         action->setCheckable(true);
948                         action->setChecked(true);
949                 }
950                 connect(action, &QAction::triggered, [lua_ref = entry->entry.lua_ref] {
951                         global_mixer->theme_menu_entry_clicked(lua_ref);
952                 });
953         }
954 }
955
956 void MainWindow::limiter_threshold_knob_changed(int value)
957 {
958         float threshold_dbfs = value * 0.1f;
959         global_audio_mixer->set_limiter_threshold_dbfs(threshold_dbfs);
960         ui->limiter_threshold_db_display->setText(
961                 QString::fromStdString(format_db(threshold_dbfs, DB_WITH_SIGN)));
962         ui->limiter_threshold_db_display_2->setText(
963                 QString::fromStdString(format_db(threshold_dbfs, DB_WITH_SIGN)));
964 }
965
966 void MainWindow::compressor_threshold_knob_changed(unsigned bus_index, int value)
967 {
968         float threshold_dbfs = value * 0.1f;
969         global_audio_mixer->set_compressor_threshold_dbfs(bus_index, threshold_dbfs);
970
971         QString label(QString::fromStdString(format_db(threshold_dbfs, DB_WITH_SIGN)));
972         if (bus_index == 0) {
973                 ui->compressor_threshold_db_display->setText(label);
974         }
975         if (bus_index < audio_expanded_views.size()) {
976                 audio_expanded_views[bus_index]->compressor_threshold_db_display->setText(label);
977         }
978 }
979
980 void MainWindow::mini_fader_changed(int bus, double volume_db)
981 {
982         QString label(QString::fromStdString(format_db(volume_db, DB_WITH_SIGN)));
983         audio_miniviews[bus]->fader_label->setText(label);
984         audio_expanded_views[bus]->fader_label->setText(label);
985
986         global_audio_mixer->set_fader_volume(bus, volume_db);
987 }
988
989 void MainWindow::mute_button_toggled(int bus, bool checked)
990 {
991         global_audio_mixer->set_mute(bus, checked);
992         midi_mapper.refresh_lights();
993 }
994
995 void MainWindow::reset_meters_button_clicked()
996 {
997         global_audio_mixer->reset_meters();
998         ui->peak_display->setText(QString::fromStdString(format_db(-HUGE_VAL, DB_WITH_SIGN | DB_BARE)));
999         ui->peak_display->setStyleSheet("");
1000 }
1001
1002 void MainWindow::audio_level_callback(float level_lufs, float peak_db, vector<AudioMixer::BusLevel> bus_levels,
1003                                       float global_level_lufs,
1004                                       float range_low_lufs, float range_high_lufs,
1005                                       float final_makeup_gain_db,
1006                                       float correlation)
1007 {
1008         steady_clock::time_point now = steady_clock::now();
1009
1010         // The meters are somewhat inefficient to update. Only update them
1011         // every 100 ms or so (we get updates every 5–20 ms). Note that this
1012         // means that the digital peak meters are ever so slightly too low
1013         // (each update won't be a faithful representation of the highest peak
1014         // since the previous update, since there are frames we won't draw),
1015         // but the _peak_ of the peak meters will be correct (it's tracked in
1016         // AudioMixer, not here), and that's much more important.
1017         double last_update_age = duration<double>(now - last_audio_level_callback).count();
1018         if (last_update_age < 0.100) {
1019                 return;
1020         }
1021         last_audio_level_callback = now;
1022
1023         post_to_main_thread([=]() {
1024                 ui->vu_meter->set_level(level_lufs);
1025                 for (unsigned bus_index = 0; bus_index < bus_levels.size(); ++bus_index) {
1026                         if (bus_index < audio_miniviews.size()) {
1027                                 const AudioMixer::BusLevel &level = bus_levels[bus_index];
1028                                 Ui::AudioMiniView *miniview = audio_miniviews[bus_index];
1029                                 miniview->peak_meter->set_level(
1030                                         level.current_level_dbfs[0], level.current_level_dbfs[1]);
1031                                 miniview->peak_meter->set_peak(
1032                                         level.peak_level_dbfs[0], level.peak_level_dbfs[1]);
1033                                 set_peak_label(miniview->peak_display_label, level.historic_peak_dbfs);
1034
1035                                 Ui::AudioExpandedView *view = audio_expanded_views[bus_index];
1036                                 view->peak_meter->set_level(
1037                                         level.current_level_dbfs[0], level.current_level_dbfs[1]);
1038                                 view->peak_meter->set_peak(
1039                                         level.peak_level_dbfs[0], level.peak_level_dbfs[1]);
1040                                 view->reduction_meter->set_reduction_db(level.compressor_attenuation_db);
1041                                 view->gainstaging_knob->blockSignals(true);
1042                                 view->gainstaging_knob->setValue(lrintf(level.gain_staging_db * 10.0f));
1043                                 view->gainstaging_knob->blockSignals(false);
1044                                 view->gainstaging_db_display->setText(
1045                                         QString("Gain: ") +
1046                                         QString::fromStdString(format_db(level.gain_staging_db, DB_WITH_SIGN)));
1047                                 set_peak_label(view->peak_display_label, level.historic_peak_dbfs);
1048
1049                                 midi_mapper.set_has_peaked(bus_index, level.historic_peak_dbfs >= -0.1f);
1050                         }
1051                 }
1052                 ui->lra_meter->set_levels(global_level_lufs, range_low_lufs, range_high_lufs);
1053                 ui->correlation_meter->set_correlation(correlation);
1054
1055                 ui->peak_display->setText(QString::fromStdString(format_db(peak_db, DB_BARE)));
1056                 set_peak_label(ui->peak_display, peak_db);
1057
1058                 // NOTE: Will be invisible when using multitrack audio.
1059                 if (!bus_levels.empty()) {
1060                         ui->gainstaging_knob->blockSignals(true);
1061                         ui->gainstaging_knob->setValue(lrintf(bus_levels[0].gain_staging_db * 10.0f));
1062                         ui->gainstaging_knob->blockSignals(false);
1063                         ui->gainstaging_db_display->setText(
1064                                 QString::fromStdString(format_db(bus_levels[0].gain_staging_db, DB_WITH_SIGN)));
1065                 }
1066
1067                 ui->makeup_gain_knob->blockSignals(true);
1068                 ui->makeup_gain_knob->setValue(lrintf(final_makeup_gain_db * 10.0f));
1069                 ui->makeup_gain_knob->blockSignals(false);
1070                 ui->makeup_gain_db_display->setText(
1071                         QString::fromStdString(format_db(final_makeup_gain_db, DB_WITH_SIGN)));
1072                 ui->makeup_gain_db_display_2->setText(
1073                         QString::fromStdString(format_db(final_makeup_gain_db, DB_WITH_SIGN)));
1074
1075                 // Peak labels could have changed.
1076                 midi_mapper.refresh_lights();
1077         });
1078 }
1079
1080 void MainWindow::relayout()
1081 {
1082         int height = ui->vertical_layout->geometry().height();
1083         if (height <= 0) {
1084                 // Seemingly this can happen and must be ignored.
1085                 return;
1086         }
1087
1088         double remaining_height = height;
1089
1090         // Allocate the height; the most important part is to keep the main displays
1091         // at the right aspect if at all possible.
1092         double me_width = ui->me_preview->width();
1093         double me_height = me_width * double(global_flags.height) / double(global_flags.width) + ui->label_preview->height() + ui->preview_vertical_layout->spacing();
1094
1095         // TODO: Scale the widths when we need to do this.
1096         if (me_height / double(height) > 0.8) {
1097                 me_height = height * 0.8;
1098         }
1099         remaining_height -= me_height + ui->vertical_layout->spacing();
1100
1101         // Space between the M/E displays and the audio strip.
1102         remaining_height -= ui->vertical_layout->spacing();
1103
1104         // The label above the audio strip.
1105         double compact_label_height = ui->compact_label->minimumHeight() +
1106                 ui->compact_audio_layout->spacing();
1107         remaining_height -= compact_label_height;
1108
1109         // The previews will be constrained by the remaining height, and the width.
1110         double preview_label_height = previews[0]->label->minimumSize().height() +
1111                 previews[0]->main_vertical_layout->spacing();
1112         int preview_total_width = ui->preview_displays->geometry().width() - (previews.size() - 1) * ui->preview_displays->spacing();
1113         double preview_height = min(remaining_height - preview_label_height, (preview_total_width / double(previews.size())) * double(global_flags.height) / double(global_flags.width));
1114         remaining_height -= preview_height + preview_label_height + ui->vertical_layout->spacing();
1115
1116         ui->vertical_layout->setStretch(0, lrintf(me_height));
1117         ui->vertical_layout->setStretch(1,
1118                 lrintf(compact_label_height) +
1119                 lrintf(remaining_height) +
1120                 lrintf(preview_height + preview_label_height));  // Audio strip and previews together.
1121
1122         ui->compact_audio_layout->setStretch(0, lrintf(compact_label_height));
1123         ui->compact_audio_layout->setStretch(1, lrintf(remaining_height));  // Audio strip.
1124         ui->compact_audio_layout->setStretch(2, lrintf(preview_height + preview_label_height));
1125
1126         if (current_audio_view == 0) {  // Compact audio view.
1127                 // Set the widths for the previews.
1128                 double preview_width = preview_height * double(global_flags.width) / double(global_flags.height);
1129                 for (unsigned i = 0; i < previews.size(); ++i) {
1130                         ui->preview_displays->setStretch(i, lrintf(preview_width));
1131                 }
1132
1133                 // The preview horizontal spacer.
1134                 double remaining_preview_width = preview_total_width - previews.size() * preview_width;
1135                 ui->preview_displays->setStretch(previews.size(), lrintf(remaining_preview_width));
1136         } else if (current_audio_view == 2) {  // Video grid view.
1137                 // QGridLayout doesn't do it for us, since we need to be able to remove rows
1138                 // or columns as the grid changes, and it won't do that. Thus, position everything
1139                 // by hand.
1140                 constexpr int spacing = 6;
1141                 int grid_width = ui->preview_displays_grid->geometry().width();
1142                 int grid_height = ui->preview_displays_grid->geometry().height();
1143                 int best_preview_width = 0;
1144                 unsigned best_num_rows = 1, best_num_cols = 1;
1145                 for (unsigned num_rows = 1; num_rows <= previews.size(); ++num_rows) {
1146                         int num_cols = (previews.size() + num_rows - 1) / num_rows;
1147
1148                         int max_preview_height = (grid_height - spacing * (num_rows - 1)) / num_rows - preview_label_height;
1149                         int max_preview_width = (grid_width - spacing * (num_cols - 1)) / num_cols;
1150                         int preview_width = std::min<int>(max_preview_width, max_preview_height * double(global_flags.width) / double(global_flags.height));
1151
1152                         if (preview_width > best_preview_width) {
1153                                 best_preview_width = preview_width;
1154                                 best_num_rows = num_rows;
1155                                 best_num_cols = num_cols;
1156                         }
1157                 }
1158
1159                 double cell_height = lrintf(best_preview_width * double(global_flags.height) / double(global_flags.width)) + preview_label_height;
1160                 remaining_height = grid_height - best_num_rows * cell_height - (best_num_rows - 1) * spacing;
1161                 int cell_width = best_preview_width;
1162                 int remaining_width = grid_width - best_num_cols * cell_width - (best_num_cols - 1) * spacing;
1163
1164                 for (unsigned i = 0; i < previews.size(); ++i) {
1165                         int col_idx = i % best_num_cols;
1166                         int row_idx = i / best_num_cols;
1167
1168                         double top = remaining_height * 0.5f + row_idx * (cell_height + spacing);
1169                         double bottom = top + cell_height;
1170                         double left = remaining_width * 0.5f + col_idx * (cell_width + spacing);
1171                         double right = left + cell_width;
1172
1173                         QRect rect;
1174                         rect.setTop(lrintf(top));
1175                         rect.setBottom(lrintf(bottom));
1176                         rect.setLeft(lrintf(left));
1177                         rect.setRight(lrintf(right));
1178
1179                         QWidget *display = static_cast<QWidget *>(previews[i]->frame->parent());
1180                         display->setGeometry(rect);
1181                         display->show();
1182                 }
1183         }
1184 }
1185
1186 void MainWindow::set_locut(float value)
1187 {
1188         set_relative_value(ui->locut_cutoff_knob, value);
1189 }
1190
1191 void MainWindow::set_limiter_threshold(float value)
1192 {
1193         set_relative_value(ui->limiter_threshold_knob, value);
1194 }
1195
1196 void MainWindow::set_makeup_gain(float value)
1197 {
1198         set_relative_value(ui->makeup_gain_knob, value);
1199 }
1200
1201 void MainWindow::set_stereo_width(unsigned bus_idx, float value)
1202 {
1203         set_relative_value_if_exists(bus_idx, &Ui::AudioExpandedView::stereo_width_knob, value);
1204 }
1205
1206 void MainWindow::set_treble(unsigned bus_idx, float value)
1207 {
1208         set_relative_value_if_exists(bus_idx, &Ui::AudioExpandedView::treble_knob, value);
1209 }
1210
1211 void MainWindow::set_eq_absolute(unsigned bus_idx, EQBand eq_band, float value_db)
1212 {
1213         if (eq_band == EQ_BAND_TREBLE) {
1214                 set_db_value_if_exists(bus_idx, &Ui::AudioExpandedView::treble_knob, value_db);
1215         } else if (eq_band == EQ_BAND_MID) {
1216                 set_db_value_if_exists(bus_idx, &Ui::AudioExpandedView::mid_knob, value_db);
1217         } else if (eq_band == EQ_BAND_BASS) {
1218                 set_db_value_if_exists(bus_idx, &Ui::AudioExpandedView::bass_knob, value_db);
1219         } else {
1220                 assert(false);
1221         }
1222 }
1223
1224 void MainWindow::set_mid(unsigned bus_idx, float value)
1225 {
1226         set_relative_value_if_exists(bus_idx, &Ui::AudioExpandedView::mid_knob, value);
1227 }
1228
1229 void MainWindow::set_bass(unsigned bus_idx, float value)
1230 {
1231         set_relative_value_if_exists(bus_idx, &Ui::AudioExpandedView::bass_knob, value);
1232 }
1233
1234 void MainWindow::set_gain(unsigned bus_idx, float value)
1235 {
1236         set_relative_value_if_exists(bus_idx, &Ui::AudioExpandedView::gainstaging_knob, value);
1237 }
1238
1239 void MainWindow::set_compressor_threshold(unsigned bus_idx, float value)
1240 {
1241         set_relative_value_if_exists(bus_idx, &Ui::AudioExpandedView::compressor_threshold_knob, value);
1242 }
1243
1244 void MainWindow::set_fader(unsigned bus_idx, float value)
1245 {
1246         set_relative_value_if_exists(bus_idx, &Ui::AudioExpandedView::fader, value);
1247 }
1248
1249 void MainWindow::set_fader_absolute(unsigned bus_idx, float value_db)
1250 {
1251         if (global_audio_mixer != nullptr &&
1252             global_audio_mixer->get_mapping_mode() == AudioMixer::MappingMode::MULTICHANNEL &&
1253             bus_idx < audio_expanded_views.size()) {
1254                 audio_expanded_views[bus_idx]->fader->setDbValue(value_db);
1255         }
1256 }
1257
1258 void MainWindow::toggle_mute(unsigned bus_idx)
1259 {
1260         click_button_if_exists(bus_idx, &Ui::AudioExpandedView::mute_button);
1261 }
1262
1263 void MainWindow::toggle_locut(unsigned bus_idx)
1264 {
1265         click_button_if_exists(bus_idx, &Ui::AudioExpandedView::locut_enabled);
1266 }
1267
1268 void MainWindow::toggle_auto_gain_staging(unsigned bus_idx)
1269 {
1270         click_button_if_exists(bus_idx, &Ui::AudioExpandedView::gainstaging_auto_checkbox);
1271 }
1272
1273 void MainWindow::toggle_compressor(unsigned bus_idx)
1274 {
1275         click_button_if_exists(bus_idx, &Ui::AudioExpandedView::compressor_enabled);
1276 }
1277
1278 void MainWindow::clear_peak(unsigned bus_idx)
1279 {
1280         post_to_main_thread([=]{
1281                 if (global_audio_mixer->get_mapping_mode() == AudioMixer::MappingMode::MULTICHANNEL) {
1282                         global_audio_mixer->reset_peak(bus_idx);
1283                         midi_mapper.set_has_peaked(bus_idx, false);
1284                         midi_mapper.refresh_lights();
1285                 }
1286         });
1287 }
1288
1289 void MainWindow::clear_all_highlights()
1290 {
1291         post_to_main_thread([this]{
1292                 highlight_locut(false);
1293                 highlight_limiter_threshold(false);
1294                 highlight_makeup_gain(false);
1295                 highlight_toggle_limiter(false);
1296                 highlight_toggle_auto_makeup_gain(false);
1297                 for (unsigned bus_idx = 0; bus_idx < audio_expanded_views.size(); ++bus_idx) {
1298                         highlight_treble(bus_idx, false);
1299                         highlight_mid(bus_idx, false);
1300                         highlight_bass(bus_idx, false);
1301                         highlight_gain(bus_idx, false);
1302                         highlight_compressor_threshold(bus_idx, false);
1303                         highlight_fader(bus_idx, false);
1304                         highlight_mute(bus_idx, false);
1305                         highlight_toggle_locut(bus_idx, false);
1306                         highlight_toggle_auto_gain_staging(bus_idx, false);
1307                         highlight_toggle_compressor(bus_idx, false);
1308                 }
1309         });
1310 }
1311
1312 void MainWindow::toggle_limiter()
1313 {
1314         if (global_audio_mixer->get_mapping_mode() == AudioMixer::MappingMode::MULTICHANNEL) {
1315                 ui->limiter_enabled->click();
1316         }
1317 }
1318
1319 void MainWindow::toggle_auto_makeup_gain()
1320 {
1321         if (global_audio_mixer->get_mapping_mode() == AudioMixer::MappingMode::MULTICHANNEL) {
1322                 ui->makeup_gain_auto_checkbox->click();
1323         }
1324 }
1325
1326 void MainWindow::switch_video_channel(int channel_number)
1327 {
1328         global_mixer->channel_clicked(channel_number);
1329 }
1330
1331 void MainWindow::apply_transition(int transition_number)
1332 {
1333         global_mixer->transition_clicked(transition_number);
1334 }
1335
1336 void MainWindow::prev_audio_view()
1337 {
1338         post_to_main_thread([this]{
1339                 prev_page();
1340         });
1341 }
1342
1343 void MainWindow::next_audio_view()
1344 {
1345         post_to_main_thread([this]{
1346                 next_page();
1347         });
1348 }
1349
1350 void MainWindow::begin_new_segment()
1351 {
1352         global_mixer->schedule_cut();
1353 }
1354
1355 void MainWindow::exit()
1356 {
1357         post_to_main_thread([this]{
1358                 close();
1359         });
1360 }
1361
1362 void MainWindow::highlight_locut(bool highlight)
1363 {
1364         post_to_main_thread([this, highlight]{
1365                 highlight_control(ui->locut_cutoff_knob, highlight);
1366                 highlight_control(ui->locut_cutoff_knob_2, highlight);
1367         });
1368 }
1369
1370 void MainWindow::highlight_limiter_threshold(bool highlight)
1371 {
1372         post_to_main_thread([this, highlight]{
1373                 highlight_control(ui->limiter_threshold_knob, highlight);
1374                 highlight_control(ui->limiter_threshold_knob_2, highlight);
1375         });
1376 }
1377
1378 void MainWindow::highlight_makeup_gain(bool highlight)
1379 {
1380         post_to_main_thread([this, highlight]{
1381                 highlight_control(ui->makeup_gain_knob, highlight);
1382                 highlight_control(ui->makeup_gain_knob_2, highlight);
1383         });
1384 }
1385
1386 void MainWindow::highlight_stereo_width(unsigned bus_idx, bool highlight)
1387 {
1388         highlight_control_if_exists(bus_idx, &Ui::AudioExpandedView::stereo_width_knob, highlight);
1389 }
1390
1391 void MainWindow::highlight_treble(unsigned bus_idx, bool highlight)
1392 {
1393         highlight_control_if_exists(bus_idx, &Ui::AudioExpandedView::treble_knob, highlight);
1394 }
1395
1396 void MainWindow::highlight_mid(unsigned bus_idx, bool highlight)
1397 {
1398         highlight_control_if_exists(bus_idx, &Ui::AudioExpandedView::mid_knob, highlight);
1399 }
1400
1401 void MainWindow::highlight_bass(unsigned bus_idx, bool highlight)
1402 {
1403         highlight_control_if_exists(bus_idx, &Ui::AudioExpandedView::bass_knob, highlight);
1404 }
1405
1406 void MainWindow::highlight_gain(unsigned bus_idx, bool highlight)
1407 {
1408         highlight_control_if_exists(bus_idx, &Ui::AudioExpandedView::gainstaging_knob, highlight);
1409 }
1410
1411 void MainWindow::highlight_compressor_threshold(unsigned bus_idx, bool highlight)
1412 {
1413         highlight_control_if_exists(bus_idx, &Ui::AudioExpandedView::compressor_threshold_knob, highlight);
1414 }
1415
1416 void MainWindow::highlight_fader(unsigned bus_idx, bool highlight)
1417 {
1418         highlight_control_if_exists(bus_idx, &Ui::AudioExpandedView::fader, highlight);
1419 }
1420
1421 void MainWindow::highlight_mute(unsigned bus_idx, bool highlight)
1422 {
1423         highlight_control_if_exists(bus_idx, &Ui::AudioExpandedView::mute_button, highlight, /*is_mute_btton=*/true);
1424 }
1425
1426 void MainWindow::highlight_toggle_locut(unsigned bus_idx, bool highlight)
1427 {
1428         highlight_control_if_exists(bus_idx, &Ui::AudioExpandedView::locut_enabled, highlight);
1429 }
1430
1431 void MainWindow::highlight_toggle_auto_gain_staging(unsigned bus_idx, bool highlight)
1432 {
1433         highlight_control_if_exists(bus_idx, &Ui::AudioExpandedView::gainstaging_auto_checkbox, highlight);
1434 }
1435
1436 void MainWindow::highlight_toggle_compressor(unsigned bus_idx, bool highlight)
1437 {
1438         highlight_control_if_exists(bus_idx, &Ui::AudioExpandedView::compressor_enabled, highlight);
1439 }
1440
1441 void MainWindow::highlight_toggle_limiter(bool highlight)
1442 {
1443         post_to_main_thread([this, highlight]{
1444                 highlight_control(ui->limiter_enabled, highlight);
1445                 highlight_control(ui->limiter_enabled_2, highlight);
1446         });
1447 }
1448
1449 void MainWindow::highlight_toggle_auto_makeup_gain(bool highlight)
1450 {
1451         post_to_main_thread([this, highlight]{
1452                 highlight_control(ui->makeup_gain_auto_checkbox, highlight);
1453                 highlight_control(ui->makeup_gain_auto_checkbox_2, highlight);
1454         });
1455 }
1456
1457 template<class T>
1458 void MainWindow::set_relative_value(T *control, float value)
1459 {
1460         post_to_main_thread([control, value]{
1461                 control->setValue(lrintf(control->minimum() + value * (control->maximum() - control->minimum())));
1462         });
1463 }
1464
1465 template<class T>
1466 void MainWindow::set_relative_value_if_exists(unsigned bus_idx, T *(Ui_AudioExpandedView::*control), float value)
1467 {
1468         if (global_audio_mixer != nullptr &&
1469             global_audio_mixer->get_mapping_mode() == AudioMixer::MappingMode::MULTICHANNEL &&
1470             bus_idx < audio_expanded_views.size()) {
1471                 set_relative_value(audio_expanded_views[bus_idx]->*control, value);
1472         }
1473 }
1474
1475 void MainWindow::set_db_value_if_exists(unsigned bus_idx, QDial *(Ui_AudioExpandedView::*control), float value_db)
1476 {
1477         post_to_main_thread([this, bus_idx, control, value_db]{
1478                 if (global_audio_mixer != nullptr &&
1479                     global_audio_mixer->get_mapping_mode() == AudioMixer::MappingMode::MULTICHANNEL &&
1480                     bus_idx < audio_expanded_views.size()) {
1481                         int value = lrintf(value_db * 10.0f);
1482                         (audio_expanded_views[bus_idx]->*control)->setValue(value);
1483                 }
1484         });
1485 }
1486
1487 template<class T>
1488 void MainWindow::click_button_if_exists(unsigned bus_idx, T *(Ui_AudioExpandedView::*control))
1489 {
1490         post_to_main_thread([this, bus_idx, control]{
1491                 if (global_audio_mixer != nullptr &&
1492                     global_audio_mixer->get_mapping_mode() == AudioMixer::MappingMode::MULTICHANNEL &&
1493                     bus_idx < audio_expanded_views.size()) {
1494                         (audio_expanded_views[bus_idx]->*control)->click();
1495                 }
1496         });
1497 }
1498
1499 template<class T>
1500 void MainWindow::highlight_control(T *control, bool highlight)
1501 {
1502         if (control == nullptr) {
1503                 return;
1504         }
1505         if (global_audio_mixer == nullptr ||
1506             global_audio_mixer->get_mapping_mode() != AudioMixer::MappingMode::MULTICHANNEL) {
1507                 highlight = false;
1508         }
1509         if (highlight) {
1510                 control->setStyleSheet("background: rgb(0,255,0,80)");
1511         } else {
1512                 control->setStyleSheet("");
1513         }
1514 }
1515
1516 template<class T>
1517 void MainWindow::highlight_mute_control(T *control, bool highlight)
1518 {
1519         if (control == nullptr) {
1520                 return;
1521         }
1522         if (global_audio_mixer == nullptr ||
1523             global_audio_mixer->get_mapping_mode() != AudioMixer::MappingMode::MULTICHANNEL) {
1524                 highlight = false;
1525         }
1526         if (highlight) {
1527                 control->setStyleSheet("QPushButton { background: rgb(0,255,0,80); } QPushButton:checked { background: rgba(255,80,0,140); }");
1528         } else {
1529                 control->setStyleSheet("QPushButton:checked { background: rgba(255,0,0,80); }");
1530         }
1531 }
1532
1533 template<class T>
1534 void MainWindow::highlight_control_if_exists(unsigned bus_idx, T *(Ui_AudioExpandedView::*control), bool highlight, bool is_mute_button)
1535 {
1536         post_to_main_thread([this, bus_idx, control, highlight, is_mute_button]{
1537                 if (bus_idx < audio_expanded_views.size()) {
1538                         if (is_mute_button) {
1539                                 highlight_mute_control(audio_expanded_views[bus_idx]->*control, highlight);
1540                         } else {
1541                                 highlight_control(audio_expanded_views[bus_idx]->*control, highlight);
1542                         }
1543                 }
1544         });
1545 }
1546
1547 void MainWindow::set_transition_names(vector<string> transition_names)
1548 {
1549         if (transition_names.size() < 1 || transition_names[0].empty()) {
1550                 transition_btn1->setText(QString(""));
1551         } else {
1552                 transition_btn1->setText(QString::fromStdString(transition_names[0] + " (J)"));
1553                 ui->transition_btn1->setShortcut(QKeySequence("J"));
1554         }
1555         if (transition_names.size() < 2 || transition_names[1].empty()) {
1556                 transition_btn2->setText(QString(""));
1557         } else {
1558                 transition_btn2->setText(QString::fromStdString(transition_names[1] + " (K)"));
1559                 ui->transition_btn2->setShortcut(QKeySequence("K"));
1560         }
1561         if (transition_names.size() < 3 || transition_names[2].empty()) {
1562                 transition_btn3->setText(QString(""));
1563         } else {
1564                 transition_btn3->setText(QString::fromStdString(transition_names[2] + " (L)"));
1565                 ui->transition_btn3->setShortcut(QKeySequence("L"));
1566         }
1567 }
1568
1569 void MainWindow::update_channel_name(Mixer::Output output, const string &name)
1570 {
1571         if (output == Mixer::OUTPUT_LIVE) {
1572                 ui->label_live->setText(name.c_str());
1573         } else if (output == Mixer::OUTPUT_PREVIEW) {
1574                 ui->label_preview->setText(name.c_str());
1575         } else if (output >= Mixer::OUTPUT_INPUT0) {
1576                 unsigned channel = output - Mixer::OUTPUT_INPUT0;
1577                 previews[channel]->label->setText(name.c_str());
1578         }
1579
1580         analyzer->update_channel_name(output, name);
1581 }
1582
1583 void MainWindow::update_channel_color(Mixer::Output output, const string &color)
1584 {
1585         if (output >= Mixer::OUTPUT_INPUT0) {
1586                 unsigned channel = output - Mixer::OUTPUT_INPUT0;
1587                 previews[channel]->frame->setStyleSheet(QString::fromStdString("background-color:" + color));
1588         }
1589 }
1590
1591 void MainWindow::transition_clicked(int transition_number)
1592 {
1593         global_mixer->transition_clicked(transition_number);
1594 }
1595
1596 void MainWindow::channel_clicked(int channel_number)
1597 {
1598         if (current_wb_pick_display == channel_number) {
1599                 // The picking was already done from eventFilter(), since we don't get
1600                 // the mouse pointer here.
1601         } else {
1602                 global_mixer->channel_clicked(channel_number);
1603         }
1604 }
1605
1606 void MainWindow::quick_cut_activated(int channel_number)
1607 {
1608         if (!global_flags.enable_quick_cut_keys) {
1609                 return;
1610         }
1611         global_mixer->channel_clicked(channel_number);
1612         global_mixer->transition_clicked(0);
1613 }
1614
1615 void MainWindow::wb_button_clicked(int channel_number)
1616 {
1617         current_wb_pick_display = channel_number;
1618         QApplication::setOverrideCursor(Qt::CrossCursor);
1619 }
1620
1621 void MainWindow::audio_view_changed(int audio_view)
1622 {
1623         if (audio_view == current_audio_view) {
1624                 return;
1625         }
1626
1627         if (audio_view == 0) {
1628                 // Compact audio view. (1, full audio view, has no video previews.)
1629                 for (unsigned i = 0; i < previews.size(); ++i) {
1630                         QWidget *display = static_cast<QWidget *>(previews[i]->frame->parent());
1631                         ui->preview_displays->insertWidget(i, display, 1);
1632                 }
1633         } else if (audio_view == 2) {
1634                 // Video grid display.
1635                 for (unsigned i = 0; i < previews.size(); ++i) {
1636                         QWidget *display = static_cast<QWidget *>(previews[i]->frame->parent());
1637                         display->setParent(ui->preview_displays_grid);
1638                         display->show();
1639                 }
1640         }
1641
1642         current_audio_view = audio_view;
1643
1644         // Ask for a relayout, but only after the event loop is done doing relayout
1645         // on everything else.
1646         QMetaObject::invokeMethod(this, "relayout", Qt::QueuedConnection);
1647 }
1648
1649 bool MainWindow::eventFilter(QObject *watched, QEvent *event)
1650 {
1651         if (current_wb_pick_display != -1 &&
1652             event->type() == QEvent::MouseButtonRelease &&
1653             watched->isWidgetType()) {
1654                 QApplication::restoreOverrideCursor();
1655                 if (watched == previews[current_wb_pick_display]->display) {
1656                         const QMouseEvent *mouse_event = (QMouseEvent *)event;
1657                         previews[current_wb_pick_display]->display->grab_white_balance(
1658                                 current_wb_pick_display,
1659                                 mouse_event->x(), mouse_event->y());
1660                 } else {
1661                         // The user clicked on something else, give up.
1662                         // (The click goes through, which might not be ideal, but, yes.)
1663                         current_wb_pick_display = -1;
1664                 }
1665         }
1666         return false;
1667 }
1668
1669 void MainWindow::closeEvent(QCloseEvent *event)
1670 {
1671         if (global_mixer->get_num_connected_clients() > 0) {
1672                 QMessageBox::StandardButton reply =
1673                         QMessageBox::question(this, "Nageru", "There are clients connected. Do you really want to quit?",
1674                                 QMessageBox::Yes | QMessageBox::No);
1675                 if (reply != QMessageBox::Yes) {
1676                         event->ignore();
1677                         return;
1678                 }
1679         }
1680
1681         analyzer->hide();
1682         global_mixer->quit();
1683         mixer_shutting_down();
1684         event->accept();
1685 }
1686
1687 void MainWindow::audio_state_changed()
1688 {
1689         post_to_main_thread([this]{
1690                 if (global_audio_mixer->get_mapping_mode() == AudioMixer::MappingMode::SIMPLE) {
1691                         return;
1692                 }
1693                 InputMapping mapping = global_audio_mixer->get_input_mapping();
1694                 for (unsigned bus_index = 0; bus_index < mapping.buses.size(); ++bus_index) {
1695                         string label = get_bus_desc_label(mapping.buses[bus_index]);
1696                         audio_miniviews[bus_index]->bus_desc_label->setFullText(
1697                                 QString::fromStdString(label));
1698                         audio_expanded_views[bus_index]->bus_desc_label->setFullText(
1699                                 QString::fromStdString(label));
1700                 }
1701         });
1702 }