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