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