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