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