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