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