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