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