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