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