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