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