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