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