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