]> git.sesse.net Git - nageru/blob - mainwindow.cpp
Allow using control 0.
[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                 // Set up the compression attenuation meter.
534                 VUMeter *reduction_meter = ui_audio_expanded_view->reduction_meter;
535                 reduction_meter->set_min_level(0.0f);
536                 reduction_meter->set_max_level(10.0f);
537                 reduction_meter->set_ref_level(0.0f);
538                 reduction_meter->set_flip(true);
539         }
540
541         update_cutoff_labels(global_audio_mixer->get_locut_cutoff());
542 }
543
544 void MainWindow::mixer_shutting_down()
545 {
546         ui->me_live->clean_context();
547         ui->me_preview->clean_context();
548         for (Ui::Display *display : previews) {
549                 display->display->clean_context();
550         }
551 }
552
553 void MainWindow::cut_triggered()
554 {
555         global_mixer->schedule_cut();
556 }
557
558 void MainWindow::x264_bitrate_triggered()
559 {
560         bool ok;
561         int new_bitrate = QInputDialog::getInt(this, "Change x264 bitrate", "Choose new bitrate for x264 HTTP output (from 100–100,000 kbit/sec):", global_flags.x264_bitrate, /*min=*/100, /*max=*/100000, /*step=*/100, &ok);
562         if (ok && new_bitrate >= 100 && new_bitrate <= 100000) {
563                 global_flags.x264_bitrate = new_bitrate;
564                 global_mixer->change_x264_bitrate(new_bitrate);
565         }
566 }
567
568 void MainWindow::exit_triggered()
569 {
570         close();
571 }
572
573 void MainWindow::about_triggered()
574 {
575         AboutDialog().exec();
576 }
577
578 void MainWindow::simple_audio_mode_triggered()
579 {
580         if (global_audio_mixer->get_mapping_mode() == AudioMixer::MappingMode::SIMPLE) {
581                 return;
582         }
583         unsigned card_index = global_audio_mixer->get_simple_input();
584         if (card_index == numeric_limits<unsigned>::max()) {
585                 QMessageBox::StandardButton reply =
586                         QMessageBox::question(this,
587                                 "Mapping too complex",
588                                 "The current audio mapping is too complicated to be representable in simple mode, "
589                                         "and will be discarded if you proceed. Really go to simple audio mode?",
590                                 QMessageBox::Yes | QMessageBox::No);
591                 if (reply == QMessageBox::No) {
592                         ui->simple_audio_mode->setChecked(false);
593                         ui->multichannel_audio_mode->setChecked(true);
594                         return;
595                 }
596                 card_index = 0;
597         }
598         global_audio_mixer->set_simple_input(/*card_index=*/card_index);
599         reset_audio_mapping_ui();
600 }
601
602 void MainWindow::multichannel_audio_mode_triggered()
603 {
604         if (global_audio_mixer->get_mapping_mode() == AudioMixer::MappingMode::MULTICHANNEL) {
605                 return;
606         }
607
608         // Take the generated input mapping from the simple input,
609         // and set it as a normal multichannel mapping, which causes
610         // the mode to go to multichannel.
611         global_audio_mixer->set_input_mapping(global_audio_mixer->get_input_mapping());
612         reset_audio_mapping_ui();
613 }
614
615 void MainWindow::input_mapping_triggered()
616 {
617         if (InputMappingDialog().exec() == QDialog::Accepted) {
618                 setup_audio_miniview();
619                 setup_audio_expanded_view();
620         }
621         midi_mapper.refresh_highlights();
622         midi_mapper.refresh_lights();
623 }
624
625 void MainWindow::midi_mapping_triggered()
626 {
627         MIDIMappingDialog(&midi_mapper).exec();
628 }
629
630 void MainWindow::gain_staging_knob_changed(unsigned bus_index, int value)
631 {
632         if (bus_index == 0) {
633                 ui->gainstaging_auto_checkbox->setCheckState(Qt::Unchecked);
634         }
635         if (bus_index < audio_expanded_views.size()) {
636                 audio_expanded_views[bus_index]->gainstaging_auto_checkbox->setCheckState(Qt::Unchecked);
637         }
638
639         float gain_db = value * 0.1f;
640         global_audio_mixer->set_gain_staging_db(bus_index, gain_db);
641
642         // The label will be updated by the audio level callback.
643 }
644
645 void MainWindow::final_makeup_gain_knob_changed(int value)
646 {
647         ui->makeup_gain_auto_checkbox->setCheckState(Qt::Unchecked);
648
649         float gain_db = value * 0.1f;
650         global_audio_mixer->set_final_makeup_gain_db(gain_db);
651
652         // The label will be updated by the audio level callback.
653 }
654
655 void MainWindow::cutoff_knob_changed(int value)
656 {
657         float octaves = value * 0.1f;
658         float cutoff_hz = 20.0 * pow(2.0, octaves);
659         global_audio_mixer->set_locut_cutoff(cutoff_hz);
660         update_cutoff_labels(cutoff_hz);
661 }
662
663 void MainWindow::update_cutoff_labels(float cutoff_hz)
664 {
665         char buf[256];
666         snprintf(buf, sizeof(buf), "%ld Hz", lrintf(cutoff_hz));
667         ui->locut_cutoff_display->setText(buf);
668         ui->locut_cutoff_display_2->setText(buf);
669
670         for (unsigned bus_index = 0; bus_index < audio_expanded_views.size(); ++bus_index) {
671                 audio_expanded_views[bus_index]->locut_enabled->setText(
672                         QString("Lo-cut: ") + buf);
673         }
674 }
675
676 void MainWindow::report_disk_space(off_t free_bytes, double estimated_seconds_left)
677 {
678         char time_str[256];
679         if (estimated_seconds_left < 60.0) {
680                 strcpy(time_str, "<font color=\"red\">Less than a minute</font>");
681         } else if (estimated_seconds_left < 1800.0) {  // Less than half an hour: Xm Ys (red).
682                 int s = lrintf(estimated_seconds_left);
683                 int m = s / 60;
684                 s %= 60;
685                 snprintf(time_str, sizeof(time_str), "<font color=\"red\">%dm %ds</font>", m, s);
686         } else if (estimated_seconds_left < 3600.0) {  // Less than an hour: Xm.
687                 int m = lrintf(estimated_seconds_left / 60.0);
688                 snprintf(time_str, sizeof(time_str), "%dm", m);
689         } else if (estimated_seconds_left < 36000.0) {  // Less than ten hours: Xh Ym.
690                 int m = lrintf(estimated_seconds_left / 60.0);
691                 int h = m / 60;
692                 m %= 60;
693                 snprintf(time_str, sizeof(time_str), "%dh %dm", h, m);
694         } else {  // More than ten hours: Xh.
695                 int h = lrintf(estimated_seconds_left / 3600.0);
696                 snprintf(time_str, sizeof(time_str), "%dh", h);
697         }
698         char buf[256];
699         snprintf(buf, sizeof(buf), "Disk free: %'.0f MB (approx. %s)", free_bytes / 1048576.0, time_str);
700
701         std::string label = buf;
702
703         post_to_main_thread([this, label]{
704                 disk_free_label->setText(QString::fromStdString(label));
705                 ui->menuBar->setCornerWidget(disk_free_label);  // Need to set this again for the sizing to get right.
706         });
707 }
708
709 void MainWindow::eq_knob_changed(unsigned bus_index, EQBand band, int value)
710 {
711         float gain_db = value * 0.1f;
712         global_audio_mixer->set_eq(bus_index, band, gain_db);
713
714         update_eq_label(bus_index, band, gain_db);
715 }
716
717 void MainWindow::update_eq_label(unsigned bus_index, EQBand band, float gain_db)
718 {
719         Ui::AudioExpandedView *view = audio_expanded_views[bus_index];
720         string db_string = format_db(gain_db, DB_WITH_SIGN);
721         switch (band) {
722         case EQ_BAND_TREBLE:
723                 view->treble_label->setText(QString::fromStdString("Treble: " + db_string));
724                 break;
725         case EQ_BAND_MID:
726                 view->mid_label->setText(QString::fromStdString("Mid: " + db_string));
727                 break;
728         case EQ_BAND_BASS:
729                 view->bass_label->setText(QString::fromStdString("Bass: " + db_string));
730                 break;
731         default:
732                 assert(false);
733         }
734 }
735
736 void MainWindow::limiter_threshold_knob_changed(int value)
737 {
738         float threshold_dbfs = value * 0.1f;
739         global_audio_mixer->set_limiter_threshold_dbfs(threshold_dbfs);
740         ui->limiter_threshold_db_display->setText(
741                 QString::fromStdString(format_db(threshold_dbfs, DB_WITH_SIGN)));
742         ui->limiter_threshold_db_display_2->setText(
743                 QString::fromStdString(format_db(threshold_dbfs, DB_WITH_SIGN)));
744 }
745
746 void MainWindow::compressor_threshold_knob_changed(unsigned bus_index, int value)
747 {
748         float threshold_dbfs = value * 0.1f;
749         global_audio_mixer->set_compressor_threshold_dbfs(bus_index, threshold_dbfs);
750
751         QString label(QString::fromStdString(format_db(threshold_dbfs, DB_WITH_SIGN)));
752         if (bus_index == 0) {
753                 ui->compressor_threshold_db_display->setText(label);
754         }
755         if (bus_index < audio_expanded_views.size()) {
756                 audio_expanded_views[bus_index]->compressor_threshold_db_display->setText(label);
757         }
758 }
759
760 void MainWindow::mini_fader_changed(int bus, double volume_db)
761 {
762         QString label(QString::fromStdString(format_db(volume_db, DB_WITH_SIGN)));
763         audio_miniviews[bus]->fader_label->setText(label);
764         audio_expanded_views[bus]->fader_label->setText(label);
765
766         global_audio_mixer->set_fader_volume(bus, volume_db);
767 }
768
769 void MainWindow::mute_button_toggled(int bus, bool checked)
770 {
771         global_audio_mixer->set_mute(bus, checked);
772         midi_mapper.refresh_lights();
773 }
774
775 void MainWindow::reset_meters_button_clicked()
776 {
777         global_audio_mixer->reset_meters();
778         ui->peak_display->setText(QString::fromStdString(format_db(-HUGE_VAL, DB_WITH_SIGN | DB_BARE)));
779         ui->peak_display->setStyleSheet("");
780 }
781
782 void MainWindow::audio_level_callback(float level_lufs, float peak_db, vector<AudioMixer::BusLevel> bus_levels,
783                                       float global_level_lufs,
784                                       float range_low_lufs, float range_high_lufs,
785                                       float final_makeup_gain_db,
786                                       float correlation)
787 {
788         steady_clock::time_point now = steady_clock::now();
789
790         // The meters are somewhat inefficient to update. Only update them
791         // every 100 ms or so (we get updates every 5–20 ms). Note that this
792         // means that the digital peak meters are ever so slightly too low
793         // (each update won't be a faithful representation of the highest peak
794         // since the previous update, since there are frames we won't draw),
795         // but the _peak_ of the peak meters will be correct (it's tracked in
796         // AudioMixer, not here), and that's much more important.
797         double last_update_age = duration<double>(now - last_audio_level_callback).count();
798         if (last_update_age < 0.100) {
799                 return;
800         }
801         last_audio_level_callback = now;
802
803         post_to_main_thread([=]() {
804                 ui->vu_meter->set_level(level_lufs);
805                 for (unsigned bus_index = 0; bus_index < bus_levels.size(); ++bus_index) {
806                         if (bus_index < audio_miniviews.size()) {
807                                 const AudioMixer::BusLevel &level = bus_levels[bus_index];
808                                 Ui::AudioMiniView *miniview = audio_miniviews[bus_index];
809                                 miniview->peak_meter->set_level(
810                                         level.current_level_dbfs[0], level.current_level_dbfs[1]);
811                                 miniview->peak_meter->set_peak(
812                                         level.peak_level_dbfs[0], level.peak_level_dbfs[1]);
813                                 set_peak_label(miniview->peak_display_label, level.historic_peak_dbfs);
814
815                                 Ui::AudioExpandedView *view = audio_expanded_views[bus_index];
816                                 view->peak_meter->set_level(
817                                         level.current_level_dbfs[0], level.current_level_dbfs[1]);
818                                 view->peak_meter->set_peak(
819                                         level.peak_level_dbfs[0], level.peak_level_dbfs[1]);
820                                 view->reduction_meter->set_level(level.compressor_attenuation_db);
821                                 view->gainstaging_knob->blockSignals(true);
822                                 view->gainstaging_knob->setValue(lrintf(level.gain_staging_db * 10.0f));
823                                 view->gainstaging_knob->blockSignals(false);
824                                 view->gainstaging_db_display->setText(
825                                         QString("Gain: ") +
826                                         QString::fromStdString(format_db(level.gain_staging_db, DB_WITH_SIGN)));
827                                 set_peak_label(view->peak_display_label, level.historic_peak_dbfs);
828
829                                 midi_mapper.set_has_peaked(bus_index, level.historic_peak_dbfs >= -0.1f);
830                         }
831                 }
832                 ui->lra_meter->set_levels(global_level_lufs, range_low_lufs, range_high_lufs);
833                 ui->correlation_meter->set_correlation(correlation);
834
835                 ui->peak_display->setText(QString::fromStdString(format_db(peak_db, DB_BARE)));
836                 set_peak_label(ui->peak_display, peak_db);
837
838                 // NOTE: Will be invisible when using multitrack audio.
839                 ui->gainstaging_knob->blockSignals(true);
840                 ui->gainstaging_knob->setValue(lrintf(bus_levels[0].gain_staging_db * 10.0f));
841                 ui->gainstaging_knob->blockSignals(false);
842                 ui->gainstaging_db_display->setText(
843                         QString::fromStdString(format_db(bus_levels[0].gain_staging_db, DB_WITH_SIGN)));
844
845                 ui->makeup_gain_knob->blockSignals(true);
846                 ui->makeup_gain_knob->setValue(lrintf(final_makeup_gain_db * 10.0f));
847                 ui->makeup_gain_knob->blockSignals(false);
848                 ui->makeup_gain_db_display->setText(
849                         QString::fromStdString(format_db(final_makeup_gain_db, DB_WITH_SIGN)));
850                 ui->makeup_gain_db_display_2->setText(
851                         QString::fromStdString(format_db(final_makeup_gain_db, DB_WITH_SIGN)));
852
853                 // Peak labels could have changed.
854                 midi_mapper.refresh_lights();
855         });
856 }
857
858 void MainWindow::relayout()
859 {
860         int height = ui->vertical_layout->geometry().height();
861
862         double remaining_height = height;
863
864         // Allocate the height; the most important part is to keep the main displays
865         // at 16:9 if at all possible.
866         double me_width = ui->me_preview->width();
867         double me_height = me_width * 9.0 / 16.0 + ui->label_preview->height() + ui->preview_vertical_layout->spacing();
868
869         // TODO: Scale the widths when we need to do this.
870         if (me_height / double(height) > 0.8) {
871                 me_height = height * 0.8;
872         }
873         remaining_height -= me_height + ui->vertical_layout->spacing();
874
875         // Space between the M/E displays and the audio strip.
876         remaining_height -= ui->vertical_layout->spacing();
877
878         // The label above the audio strip.
879         double compact_label_height = ui->compact_label->minimumHeight() +
880                 ui->compact_audio_layout->spacing();
881         remaining_height -= compact_label_height;
882
883         // The previews will be constrained by the remaining height, and the width.
884         double preview_label_height = previews[0]->title_bar->geometry().height() +
885                 previews[0]->main_vertical_layout->spacing();
886         int preview_total_width = ui->preview_displays->geometry().width() - (previews.size() - 1) * ui->preview_displays->spacing();
887         double preview_height = min(remaining_height - preview_label_height, (preview_total_width / double(previews.size())) * 9.0 / 16.0);
888         remaining_height -= preview_height + preview_label_height + ui->vertical_layout->spacing();
889
890         ui->vertical_layout->setStretch(0, lrintf(me_height));
891         ui->vertical_layout->setStretch(1,
892                 lrintf(compact_label_height) +
893                 lrintf(remaining_height) +
894                 lrintf(preview_height + preview_label_height));  // Audio strip and previews together.
895
896         ui->compact_audio_layout->setStretch(0, lrintf(compact_label_height));
897         ui->compact_audio_layout->setStretch(1, lrintf(remaining_height));  // Audio strip.
898         ui->compact_audio_layout->setStretch(2, lrintf(preview_height + preview_label_height));
899
900         // Set the widths for the previews.
901         double preview_width = preview_height * 16.0 / 9.0;
902         for (unsigned i = 0; i < previews.size(); ++i) {
903                 ui->preview_displays->setStretch(i, lrintf(preview_width));
904         }
905
906         // The preview horizontal spacer.
907         double remaining_preview_width = preview_total_width - previews.size() * preview_width;
908         ui->preview_displays->setStretch(previews.size(), lrintf(remaining_preview_width));
909 }
910
911 void MainWindow::set_locut(float value)
912 {
913         set_relative_value(ui->locut_cutoff_knob, value);
914 }
915
916 void MainWindow::set_limiter_threshold(float value)
917 {
918         set_relative_value(ui->limiter_threshold_knob, value);
919 }
920
921 void MainWindow::set_makeup_gain(float value)
922 {
923         set_relative_value(ui->makeup_gain_knob, value);
924 }
925
926 void MainWindow::set_treble(unsigned bus_idx, float value)
927 {
928         set_relative_value_if_exists(bus_idx, &Ui::AudioExpandedView::treble_knob, value);
929 }
930
931 void MainWindow::set_mid(unsigned bus_idx, float value)
932 {
933         set_relative_value_if_exists(bus_idx, &Ui::AudioExpandedView::mid_knob, value);
934 }
935
936 void MainWindow::set_bass(unsigned bus_idx, float value)
937 {
938         set_relative_value_if_exists(bus_idx, &Ui::AudioExpandedView::bass_knob, value);
939 }
940
941 void MainWindow::set_gain(unsigned bus_idx, float value)
942 {
943         set_relative_value_if_exists(bus_idx, &Ui::AudioExpandedView::gainstaging_knob, value);
944 }
945
946 void MainWindow::set_compressor_threshold(unsigned bus_idx, float value)
947 {
948         set_relative_value_if_exists(bus_idx, &Ui::AudioExpandedView::compressor_threshold_knob, value);
949 }
950
951 void MainWindow::set_fader(unsigned bus_idx, float value)
952 {
953         set_relative_value_if_exists(bus_idx, &Ui::AudioExpandedView::fader, value);
954 }
955
956 void MainWindow::toggle_mute(unsigned bus_idx)
957 {
958         click_button_if_exists(bus_idx, &Ui::AudioExpandedView::mute_button);
959 }
960
961 void MainWindow::toggle_locut(unsigned bus_idx)
962 {
963         click_button_if_exists(bus_idx, &Ui::AudioExpandedView::locut_enabled);
964 }
965
966 void MainWindow::toggle_auto_gain_staging(unsigned bus_idx)
967 {
968         click_button_if_exists(bus_idx, &Ui::AudioExpandedView::gainstaging_auto_checkbox);
969 }
970
971 void MainWindow::toggle_compressor(unsigned bus_idx)
972 {
973         click_button_if_exists(bus_idx, &Ui::AudioExpandedView::compressor_enabled);
974 }
975
976 void MainWindow::clear_peak(unsigned bus_idx)
977 {
978         post_to_main_thread([=]{
979                 if (global_audio_mixer->get_mapping_mode() == AudioMixer::MappingMode::MULTICHANNEL) {
980                         global_audio_mixer->reset_peak(bus_idx);
981                         midi_mapper.set_has_peaked(bus_idx, false);
982                         midi_mapper.refresh_lights();
983                 }
984         });
985 }
986
987 void MainWindow::clear_all_highlights()
988 {
989         post_to_main_thread([this]{
990                 highlight_locut(false);
991                 highlight_limiter_threshold(false);
992                 highlight_makeup_gain(false);
993                 highlight_toggle_limiter(false);
994                 highlight_toggle_auto_makeup_gain(false);
995                 for (unsigned bus_idx = 0; bus_idx < audio_expanded_views.size(); ++bus_idx) {
996                         highlight_treble(bus_idx, false);
997                         highlight_mid(bus_idx, false);
998                         highlight_bass(bus_idx, false);
999                         highlight_gain(bus_idx, false);
1000                         highlight_compressor_threshold(bus_idx, false);
1001                         highlight_fader(bus_idx, false);
1002                         highlight_mute(bus_idx, false);
1003                         highlight_toggle_locut(bus_idx, false);
1004                         highlight_toggle_auto_gain_staging(bus_idx, false);
1005                         highlight_toggle_compressor(bus_idx, false);
1006                 }
1007         });
1008 }
1009
1010 void MainWindow::toggle_limiter()
1011 {
1012         if (global_audio_mixer->get_mapping_mode() == AudioMixer::MappingMode::MULTICHANNEL) {
1013                 ui->limiter_enabled->click();
1014         }
1015 }
1016
1017 void MainWindow::toggle_auto_makeup_gain()
1018 {
1019         if (global_audio_mixer->get_mapping_mode() == AudioMixer::MappingMode::MULTICHANNEL) {
1020                 ui->makeup_gain_auto_checkbox->click();
1021         }
1022 }
1023
1024 void MainWindow::highlight_locut(bool highlight)
1025 {
1026         post_to_main_thread([this, highlight]{
1027                 highlight_control(ui->locut_cutoff_knob, highlight);
1028                 highlight_control(ui->locut_cutoff_knob_2, highlight);
1029         });
1030 }
1031
1032 void MainWindow::highlight_limiter_threshold(bool highlight)
1033 {
1034         post_to_main_thread([this, highlight]{
1035                 highlight_control(ui->limiter_threshold_knob, highlight);
1036                 highlight_control(ui->limiter_threshold_knob_2, highlight);
1037         });
1038 }
1039
1040 void MainWindow::highlight_makeup_gain(bool highlight)
1041 {
1042         post_to_main_thread([this, highlight]{
1043                 highlight_control(ui->makeup_gain_knob, highlight);
1044                 highlight_control(ui->makeup_gain_knob_2, highlight);
1045         });
1046 }
1047
1048 void MainWindow::highlight_treble(unsigned bus_idx, bool highlight)
1049 {
1050         highlight_control_if_exists(bus_idx, &Ui::AudioExpandedView::treble_knob, highlight);
1051 }
1052
1053 void MainWindow::highlight_mid(unsigned bus_idx, bool highlight)
1054 {
1055         highlight_control_if_exists(bus_idx, &Ui::AudioExpandedView::mid_knob, highlight);
1056 }
1057
1058 void MainWindow::highlight_bass(unsigned bus_idx, bool highlight)
1059 {
1060         highlight_control_if_exists(bus_idx, &Ui::AudioExpandedView::bass_knob, highlight);
1061 }
1062
1063 void MainWindow::highlight_gain(unsigned bus_idx, bool highlight)
1064 {
1065         highlight_control_if_exists(bus_idx, &Ui::AudioExpandedView::gainstaging_knob, highlight);
1066 }
1067
1068 void MainWindow::highlight_compressor_threshold(unsigned bus_idx, bool highlight)
1069 {
1070         highlight_control_if_exists(bus_idx, &Ui::AudioExpandedView::compressor_threshold_knob, highlight);
1071 }
1072
1073 void MainWindow::highlight_fader(unsigned bus_idx, bool highlight)
1074 {
1075         highlight_control_if_exists(bus_idx, &Ui::AudioExpandedView::fader, highlight);
1076 }
1077
1078 void MainWindow::highlight_mute(unsigned bus_idx, bool highlight)
1079 {
1080         highlight_control_if_exists(bus_idx, &Ui::AudioExpandedView::mute_button, highlight, /*is_mute_btton=*/true);
1081 }
1082
1083 void MainWindow::highlight_toggle_locut(unsigned bus_idx, bool highlight)
1084 {
1085         highlight_control_if_exists(bus_idx, &Ui::AudioExpandedView::locut_enabled, highlight);
1086 }
1087
1088 void MainWindow::highlight_toggle_auto_gain_staging(unsigned bus_idx, bool highlight)
1089 {
1090         highlight_control_if_exists(bus_idx, &Ui::AudioExpandedView::gainstaging_auto_checkbox, highlight);
1091 }
1092
1093 void MainWindow::highlight_toggle_compressor(unsigned bus_idx, bool highlight)
1094 {
1095         highlight_control_if_exists(bus_idx, &Ui::AudioExpandedView::compressor_enabled, highlight);
1096 }
1097
1098 void MainWindow::highlight_toggle_limiter(bool highlight)
1099 {
1100         post_to_main_thread([this, highlight]{
1101                 highlight_control(ui->limiter_enabled, highlight);
1102                 highlight_control(ui->limiter_enabled_2, highlight);
1103         });
1104 }
1105
1106 void MainWindow::highlight_toggle_auto_makeup_gain(bool highlight)
1107 {
1108         post_to_main_thread([this, highlight]{
1109                 highlight_control(ui->makeup_gain_auto_checkbox, highlight);
1110                 highlight_control(ui->makeup_gain_auto_checkbox_2, highlight);
1111         });
1112 }
1113
1114 template<class T>
1115 void MainWindow::set_relative_value(T *control, float value)
1116 {
1117         post_to_main_thread([control, value]{
1118                 control->setValue(lrintf(control->minimum() + value * (control->maximum() - control->minimum())));
1119         });
1120 }
1121
1122 template<class T>
1123 void MainWindow::set_relative_value_if_exists(unsigned bus_idx, T *(Ui_AudioExpandedView::*control), float value)
1124 {
1125         if (global_audio_mixer != nullptr &&
1126             global_audio_mixer->get_mapping_mode() == AudioMixer::MappingMode::MULTICHANNEL &&
1127             bus_idx < audio_expanded_views.size()) {
1128                 set_relative_value(audio_expanded_views[bus_idx]->*control, value);
1129         }
1130 }
1131
1132 template<class T>
1133 void MainWindow::click_button_if_exists(unsigned bus_idx, T *(Ui_AudioExpandedView::*control))
1134 {
1135         post_to_main_thread([this, bus_idx, control]{
1136                 if (global_audio_mixer != nullptr &&
1137                     global_audio_mixer->get_mapping_mode() == AudioMixer::MappingMode::MULTICHANNEL &&
1138                     bus_idx < audio_expanded_views.size()) {
1139                         (audio_expanded_views[bus_idx]->*control)->click();
1140                 }
1141         });
1142 }
1143
1144 template<class T>
1145 void MainWindow::highlight_control(T *control, bool highlight)
1146 {
1147         if (control == nullptr) {
1148                 return;
1149         }
1150         if (global_audio_mixer == nullptr ||
1151             global_audio_mixer->get_mapping_mode() != AudioMixer::MappingMode::MULTICHANNEL) {
1152                 highlight = false;
1153         }
1154         if (highlight) {
1155                 control->setStyleSheet("background: rgb(0,255,0,80)");
1156         } else {
1157                 control->setStyleSheet("");
1158         }
1159 }
1160
1161 template<class T>
1162 void MainWindow::highlight_mute_control(T *control, bool highlight)
1163 {
1164         if (control == nullptr) {
1165                 return;
1166         }
1167         if (global_audio_mixer == nullptr ||
1168             global_audio_mixer->get_mapping_mode() != AudioMixer::MappingMode::MULTICHANNEL) {
1169                 highlight = false;
1170         }
1171         if (highlight) {
1172                 control->setStyleSheet("QPushButton { background: rgb(0,255,0,80); } QPushButton:checked { background: rgba(255,80,0,140); }");
1173         } else {
1174                 control->setStyleSheet("QPushButton:checked { background: rgba(255,0,0,80); }");
1175         }
1176 }
1177
1178 template<class T>
1179 void MainWindow::highlight_control_if_exists(unsigned bus_idx, T *(Ui_AudioExpandedView::*control), bool highlight, bool is_mute_button)
1180 {
1181         post_to_main_thread([this, bus_idx, control, highlight, is_mute_button]{
1182                 if (bus_idx < audio_expanded_views.size()) {
1183                         if (is_mute_button) {
1184                                 highlight_mute_control(audio_expanded_views[bus_idx]->*control, highlight);
1185                         } else {
1186                                 highlight_control(audio_expanded_views[bus_idx]->*control, highlight);
1187                         }
1188                 }
1189         });
1190 }
1191
1192 void MainWindow::set_transition_names(vector<string> transition_names)
1193 {
1194         if (transition_names.size() < 1 || transition_names[0].empty()) {
1195                 transition_btn1->setText(QString(""));
1196         } else {
1197                 transition_btn1->setText(QString::fromStdString(transition_names[0] + " (J)"));
1198                 ui->transition_btn1->setShortcut(QKeySequence("J"));
1199         }
1200         if (transition_names.size() < 2 || transition_names[1].empty()) {
1201                 transition_btn2->setText(QString(""));
1202         } else {
1203                 transition_btn2->setText(QString::fromStdString(transition_names[1] + " (K)"));
1204                 ui->transition_btn2->setShortcut(QKeySequence("K"));
1205         }
1206         if (transition_names.size() < 3 || transition_names[2].empty()) {
1207                 transition_btn3->setText(QString(""));
1208         } else {
1209                 transition_btn3->setText(QString::fromStdString(transition_names[2] + " (L)"));
1210                 ui->transition_btn3->setShortcut(QKeySequence("L"));
1211         }
1212 }
1213
1214 void MainWindow::update_channel_name(Mixer::Output output, const string &name)
1215 {
1216         if (output >= Mixer::OUTPUT_INPUT0) {
1217                 unsigned channel = output - Mixer::OUTPUT_INPUT0;
1218                 previews[channel]->label->setText(name.c_str());
1219         }
1220 }
1221
1222 void MainWindow::update_channel_color(Mixer::Output output, const string &color)
1223 {
1224         if (output >= Mixer::OUTPUT_INPUT0) {
1225                 unsigned channel = output - Mixer::OUTPUT_INPUT0;
1226                 previews[channel]->frame->setStyleSheet(QString::fromStdString("background-color:" + color));
1227         }
1228 }
1229
1230 void MainWindow::transition_clicked(int transition_number)
1231 {
1232         global_mixer->transition_clicked(transition_number);
1233 }
1234
1235 void MainWindow::channel_clicked(int channel_number)
1236 {
1237         if (current_wb_pick_display == channel_number) {
1238                 // The picking was already done from eventFilter(), since we don't get
1239                 // the mouse pointer here.
1240         } else {
1241                 global_mixer->channel_clicked(channel_number);
1242         }
1243 }
1244
1245 void MainWindow::wb_button_clicked(int channel_number)
1246 {
1247         current_wb_pick_display = channel_number;
1248         QApplication::setOverrideCursor(Qt::CrossCursor);
1249 }
1250
1251 bool MainWindow::eventFilter(QObject *watched, QEvent *event)
1252 {
1253         if (current_wb_pick_display != -1 &&
1254             event->type() == QEvent::MouseButtonRelease &&
1255             watched->isWidgetType()) {
1256                 QApplication::restoreOverrideCursor();
1257                 if (watched == previews[current_wb_pick_display]->display) {
1258                         const QMouseEvent *mouse_event = (QMouseEvent *)event;
1259                         set_white_balance(current_wb_pick_display, mouse_event->x(), mouse_event->y());
1260                 } else {
1261                         // The user clicked on something else, give up.
1262                         // (The click goes through, which might not be ideal, but, yes.)
1263                         current_wb_pick_display = -1;
1264                 }
1265         }
1266         return false;
1267 }
1268
1269 namespace {
1270
1271 double srgb_to_linear(double x)
1272 {
1273         if (x < 0.04045) {
1274                 return x / 12.92;
1275         } else {
1276                 return pow((x + 0.055) / 1.055, 2.4);
1277         }
1278 }
1279
1280 }  // namespace
1281
1282 void MainWindow::set_white_balance(int channel_number, int x, int y)
1283 {
1284         // Set the white balance to neutral for the grab. It's probably going to
1285         // flicker a bit, but hopefully this display is not live anyway.
1286         global_mixer->set_wb(Mixer::OUTPUT_INPUT0 + channel_number, 0.5, 0.5, 0.5);
1287         previews[channel_number]->display->updateGL();
1288         QRgb reference_color = previews[channel_number]->display->grabFrameBuffer().pixel(x, y);
1289
1290         double r = srgb_to_linear(qRed(reference_color) / 255.0);
1291         double g = srgb_to_linear(qGreen(reference_color) / 255.0);
1292         double b = srgb_to_linear(qBlue(reference_color) / 255.0);
1293         global_mixer->set_wb(Mixer::OUTPUT_INPUT0 + channel_number, r, g, b);
1294         previews[channel_number]->display->updateGL();
1295 }
1296
1297 void MainWindow::audio_state_changed()
1298 {
1299         post_to_main_thread([this]{
1300                 InputMapping mapping = global_audio_mixer->get_input_mapping();
1301                 for (unsigned bus_index = 0; bus_index < mapping.buses.size(); ++bus_index) {
1302                         const InputMapping::Bus &bus = mapping.buses[bus_index];
1303                         string suffix;
1304                         if (bus.device.type == InputSourceType::ALSA_INPUT) {
1305                                 ALSAPool::Device::State state = global_audio_mixer->get_alsa_card_state(bus.device.index);
1306                                 if (state == ALSAPool::Device::State::STARTING) {
1307                                         suffix = " (busy)";
1308                                 } else if (state == ALSAPool::Device::State::DEAD) {
1309                                         suffix = " (dead)";
1310                                 }
1311                         }
1312
1313                         audio_miniviews[bus_index]->bus_desc_label->setFullText(
1314                                 QString::fromStdString(bus.name + suffix));
1315                         audio_expanded_views[bus_index]->bus_desc_label->setFullText(
1316                                 QString::fromStdString(bus.name + suffix));
1317                 }
1318         });
1319 }