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