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