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