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