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