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