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