]> git.sesse.net Git - nageru/blob - mainwindow.cpp
Make the UI show free disk space, and a rough estimation of for how much longer we...
[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 "lrameter.h"
26 #include "mixer.h"
27 #include "post_to_main_thread.h"
28 #include "ui_display.h"
29 #include "ui_mainwindow.h"
30 #include "vumeter.h"
31
32 class QResizeEvent;
33
34 using namespace std;
35 using namespace std::chrono;
36 using namespace std::placeholders;
37
38 Q_DECLARE_METATYPE(std::string);
39 Q_DECLARE_METATYPE(std::vector<std::string>);
40
41 MainWindow *global_mainwindow = nullptr;
42
43 namespace {
44
45 void schedule_cut_signal(int ignored)
46 {
47         global_mixer->schedule_cut();
48 }
49
50 void quit_signal(int ignored)
51 {
52         global_mainwindow->close();
53 }
54
55 constexpr unsigned DB_NO_FLAGS = 0x0;
56 constexpr unsigned DB_WITH_SIGN = 0x1;
57 constexpr unsigned DB_BARE = 0x2;
58
59 string format_db(double db, unsigned flags)
60 {
61         string text;
62         if (flags & DB_WITH_SIGN) {
63                 if (isfinite(db)) {
64                         char buf[256];
65                         snprintf(buf, sizeof(buf), "%+.1f", db);
66                         text = buf;
67                 } else if (db < 0.0) {
68                         text = "-∞";
69                 } else {
70                         // Should never happen, really.
71                         text = "+∞";
72                 }
73         } else {
74                 if (isfinite(db)) {
75                         char buf[256];
76                         snprintf(buf, sizeof(buf), "%.1f", db);
77                         text = buf;
78                 } else if (db < 0.0) {
79                         text = "-∞";
80                 } else {
81                         // Should never happen, really.
82                         text = "∞";
83                 }
84         }
85         if (!(flags & DB_BARE)) {
86                 text += " dB";
87         }
88         return text;
89 }
90
91 }  // namespace
92
93 MainWindow::MainWindow()
94         : ui(new Ui::MainWindow)
95 {
96         global_mainwindow = this;
97         ui->setupUi(this);
98
99         global_disk_space_estimator = new DiskSpaceEstimator(bind(&MainWindow::report_disk_space, this, _1, _2));
100         disk_free_label = new QLabel(this);
101         disk_free_label->setStyleSheet("QLabel {padding-right: 5px;}");
102         ui->menuBar->setCornerWidget(disk_free_label);
103
104         ui->me_live->set_output(Mixer::OUTPUT_LIVE);
105         ui->me_preview->set_output(Mixer::OUTPUT_PREVIEW);
106
107         // The menus.
108         connect(ui->cut_action, &QAction::triggered, this, &MainWindow::cut_triggered);
109         connect(ui->exit_action, &QAction::triggered, this, &MainWindow::exit_triggered);
110         connect(ui->about_action, &QAction::triggered, this, &MainWindow::about_triggered);
111
112         if (global_flags.x264_video_to_http) {
113                 connect(ui->x264_bitrate_action, &QAction::triggered, this, &MainWindow::x264_bitrate_triggered);
114         } else {
115                 ui->x264_bitrate_action->setEnabled(false);
116         }
117
118         // Hook up the transition buttons. (Keyboard shortcuts are set in set_transition_names().)
119         // TODO: Make them dynamic.
120         connect(ui->transition_btn1, &QPushButton::clicked, bind(&MainWindow::transition_clicked, this, 0));
121         connect(ui->transition_btn2, &QPushButton::clicked, bind(&MainWindow::transition_clicked, this, 1));
122         connect(ui->transition_btn3, &QPushButton::clicked, bind(&MainWindow::transition_clicked, this, 2));
123
124         // Aiee...
125         transition_btn1 = ui->transition_btn1;
126         transition_btn2 = ui->transition_btn2;
127         transition_btn3 = ui->transition_btn3;
128         qRegisterMetaType<string>("std::string");
129         qRegisterMetaType<vector<string>>("std::vector<std::string>");
130         connect(ui->me_live, &GLWidget::transition_names_updated, this, &MainWindow::set_transition_names);
131         qRegisterMetaType<Mixer::Output>("Mixer::Output");
132
133         last_audio_level_callback = steady_clock::now() - seconds(1);
134 }
135
136 void MainWindow::resizeEvent(QResizeEvent* event)
137 {
138         QMainWindow::resizeEvent(event);
139
140         // Ask for a relayout, but only after the event loop is done doing relayout
141         // on everything else.
142         QMetaObject::invokeMethod(this, "relayout", Qt::QueuedConnection);
143 }
144
145 void MainWindow::mixer_created(Mixer *mixer)
146 {
147         // Make the previews.
148         unsigned num_previews = mixer->get_num_channels();
149
150         for (unsigned i = 0; i < num_previews; ++i) {
151                 Mixer::Output output = Mixer::Output(Mixer::OUTPUT_INPUT0 + i);
152
153                 QWidget *preview = new QWidget(this);
154                 Ui::Display *ui_display = new Ui::Display;
155                 ui_display->setupUi(preview);
156                 ui_display->label->setText(mixer->get_channel_name(output).c_str());
157                 ui_display->display->set_output(output);
158                 ui->preview_displays->insertWidget(previews.size(), preview, 1);
159                 previews.push_back(ui_display);
160
161                 // Hook up the click.
162                 connect(ui_display->display, &GLWidget::clicked, bind(&MainWindow::channel_clicked, this, i));
163
164                 // Let the theme update the text whenever the resolution or color changed.
165                 connect(ui_display->display, &GLWidget::name_updated, this, &MainWindow::update_channel_name);
166                 connect(ui_display->display, &GLWidget::color_updated, this, &MainWindow::update_channel_color);
167
168                 // Hook up the keyboard key.
169                 QShortcut *shortcut = new QShortcut(QKeySequence(Qt::Key_1 + i), this);
170                 connect(shortcut, &QShortcut::activated, bind(&MainWindow::channel_clicked, this, i));
171
172                 // Hook up the white balance button (irrelevant if invisible).
173                 ui_display->wb_button->setVisible(mixer->get_supports_set_wb(output));
174                 connect(ui_display->wb_button, &QPushButton::clicked, bind(&MainWindow::wb_button_clicked, this, i));
175         }
176
177         // TODO: Fetch all of the values these for completeness,
178         // not just the enable knobs implied by flags.
179         ui->locut_enabled->setChecked(global_mixer->get_locut_enabled());
180         ui->gainstaging_knob->setValue(global_mixer->get_gain_staging_db());
181         ui->gainstaging_auto_checkbox->setChecked(global_mixer->get_gain_staging_auto());
182         ui->compressor_enabled->setChecked(global_mixer->get_compressor_enabled());
183         ui->limiter_enabled->setChecked(global_mixer->get_limiter_enabled());
184         ui->makeup_gain_auto_checkbox->setChecked(global_mixer->get_final_makeup_gain_auto());
185
186         ui->limiter_threshold_db_display->setText(
187                 QString::fromStdString(format_db(mixer->get_limiter_threshold_dbfs(), DB_WITH_SIGN)));
188         ui->compressor_threshold_db_display->setText(
189                 QString::fromStdString(format_db(mixer->get_compressor_threshold_dbfs(), DB_WITH_SIGN)));
190
191         connect(ui->locut_cutoff_knob, &QDial::valueChanged, this, &MainWindow::cutoff_knob_changed);
192         cutoff_knob_changed(ui->locut_cutoff_knob->value());
193         connect(ui->locut_enabled, &QCheckBox::stateChanged, [this](int state){
194                 global_mixer->set_locut_enabled(state == Qt::Checked);
195         });
196
197         connect(ui->gainstaging_knob, &QAbstractSlider::valueChanged, this, &MainWindow::gain_staging_knob_changed);
198         connect(ui->gainstaging_auto_checkbox, &QCheckBox::stateChanged, [this](int state){
199                 global_mixer->set_gain_staging_auto(state == Qt::Checked);
200         });
201         connect(ui->makeup_gain_knob, &QAbstractSlider::valueChanged, this, &MainWindow::final_makeup_gain_knob_changed);
202         connect(ui->makeup_gain_auto_checkbox, &QCheckBox::stateChanged, [this](int state){
203                 global_mixer->set_final_makeup_gain_auto(state == Qt::Checked);
204         });
205
206         connect(ui->limiter_threshold_knob, &QDial::valueChanged, this, &MainWindow::limiter_threshold_knob_changed);
207         connect(ui->compressor_threshold_knob, &QDial::valueChanged, this, &MainWindow::compressor_threshold_knob_changed);
208         connect(ui->limiter_enabled, &QCheckBox::stateChanged, [this](int state){
209                 global_mixer->set_limiter_enabled(state == Qt::Checked);
210         });
211         connect(ui->compressor_enabled, &QCheckBox::stateChanged, [this](int state){
212                 global_mixer->set_compressor_enabled(state == Qt::Checked);
213         });
214         connect(ui->reset_meters_button, &QPushButton::clicked, this, &MainWindow::reset_meters_button_clicked);
215         mixer->set_audio_level_callback(bind(&MainWindow::audio_level_callback, this, _1, _2, _3, _4, _5, _6, _7, _8));
216
217         struct sigaction act;
218         memset(&act, 0, sizeof(act));
219         act.sa_handler = schedule_cut_signal;
220         act.sa_flags = SA_RESTART;
221         sigaction(SIGHUP, &act, nullptr);
222
223         // Mostly for debugging. Don't override SIGINT, that's so evil if
224         // shutdown isn't instant.
225         memset(&act, 0, sizeof(act));
226         act.sa_handler = quit_signal;
227         act.sa_flags = SA_RESTART;
228         sigaction(SIGUSR1, &act, nullptr);
229 }
230
231 void MainWindow::mixer_shutting_down()
232 {
233         ui->me_live->clean_context();
234         ui->me_preview->clean_context();
235         for (Ui::Display *display : previews) {
236                 display->display->clean_context();
237         }
238 }
239
240 void MainWindow::cut_triggered()
241 {
242         global_mixer->schedule_cut();
243 }
244
245 void MainWindow::x264_bitrate_triggered()
246 {
247         bool ok;
248         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);
249         if (ok && new_bitrate >= 100 && new_bitrate <= 100000) {
250                 global_flags.x264_bitrate = new_bitrate;
251                 global_mixer->change_x264_bitrate(new_bitrate);
252         }
253 }
254
255 void MainWindow::exit_triggered()
256 {
257         close();
258 }
259
260 void MainWindow::about_triggered()
261 {
262         AboutDialog().exec();
263 }
264
265 void MainWindow::gain_staging_knob_changed(int value)
266 {
267         ui->gainstaging_auto_checkbox->setCheckState(Qt::Unchecked);
268
269         float gain_db = value * 0.1f;
270         global_mixer->set_gain_staging_db(gain_db);
271
272         // The label will be updated by the audio level callback.
273 }
274
275 void MainWindow::final_makeup_gain_knob_changed(int value)
276 {
277         ui->makeup_gain_auto_checkbox->setCheckState(Qt::Unchecked);
278
279         float gain_db = value * 0.1f;
280         global_mixer->set_final_makeup_gain_db(gain_db);
281
282         // The label will be updated by the audio level callback.
283 }
284
285 void MainWindow::cutoff_knob_changed(int value)
286 {
287         float octaves = value * 0.1f;
288         float cutoff_hz = 20.0 * pow(2.0, octaves);
289         global_mixer->set_locut_cutoff(cutoff_hz);
290
291         char buf[256];
292         snprintf(buf, sizeof(buf), "%ld Hz", lrintf(cutoff_hz));
293         ui->locut_cutoff_display->setText(buf);
294 }
295
296 void MainWindow::report_disk_space(off_t free_bytes, double estimated_seconds_left)
297 {
298         char time_str[256];
299         if (estimated_seconds_left < 60.0) {
300                 strcpy(time_str, "<font color=\"red\">Less than a minute</font>");
301         } else if (estimated_seconds_left < 1800.0) {  // Less than half an hour: Xm Ys (red).
302                 int s = lrintf(estimated_seconds_left);
303                 int m = s / 60;
304                 s %= 60;
305                 snprintf(time_str, sizeof(time_str), "<font color=\"red\">%dm %ds</font>", m, s);
306         } else if (estimated_seconds_left < 3600.0) {  // Less than an hour: Xm.
307                 int m = lrintf(estimated_seconds_left / 60.0);
308                 snprintf(time_str, sizeof(time_str), "%dm", m);
309         } else if (estimated_seconds_left < 36000.0) {  // Less than ten hours: Xh Ym.
310                 int m = lrintf(estimated_seconds_left / 60.0);
311                 int h = m / 60;
312                 m %= 60;
313                 snprintf(time_str, sizeof(time_str), "%dh %dm", h, m);
314         } else {  // More than ten hours: Xh.
315                 int h = lrintf(estimated_seconds_left / 3600.0);
316                 snprintf(time_str, sizeof(time_str), "%dh", h);
317         }
318         char buf[256];
319         snprintf(buf, sizeof(buf), "Disk free: %'.0f MB (approx. %s)", free_bytes / 1048576.0, time_str);
320
321         std::string label = buf;
322
323         post_to_main_thread([this, label]{
324                 disk_free_label->setText(QString::fromStdString(label));
325                 ui->menuBar->setCornerWidget(disk_free_label);  // Need to set this again for the sizing to get right.
326         });
327 }
328
329 void MainWindow::limiter_threshold_knob_changed(int value)
330 {
331         float threshold_dbfs = value * 0.1f;
332         global_mixer->set_limiter_threshold_dbfs(threshold_dbfs);
333         ui->limiter_threshold_db_display->setText(
334                 QString::fromStdString(format_db(threshold_dbfs, DB_WITH_SIGN)));
335 }
336
337 void MainWindow::compressor_threshold_knob_changed(int value)
338 {
339         float threshold_dbfs = value * 0.1f;
340         global_mixer->set_compressor_threshold_dbfs(threshold_dbfs);
341         ui->compressor_threshold_db_display->setText(
342                 QString::fromStdString(format_db(threshold_dbfs, DB_WITH_SIGN)));
343 }
344
345 void MainWindow::reset_meters_button_clicked()
346 {
347         global_mixer->reset_meters();
348         ui->peak_display->setText(QString::fromStdString(format_db(-HUGE_VAL, DB_WITH_SIGN | DB_BARE)));
349         ui->peak_display->setStyleSheet("");
350 }
351
352 void MainWindow::audio_level_callback(float level_lufs, float peak_db, float global_level_lufs,
353                                       float range_low_lufs, float range_high_lufs,
354                                       float gain_staging_db, float final_makeup_gain_db,
355                                       float correlation)
356 {
357         steady_clock::time_point now = steady_clock::now();
358
359         // The meters are somewhat inefficient to update. Only update them
360         // every 100 ms or so (we get updates every 5–20 ms).
361         double last_update_age = duration<double>(now - last_audio_level_callback).count();
362         if (last_update_age < 0.100) {
363                 return;
364         }
365         last_audio_level_callback = now;
366
367         post_to_main_thread([=]() {
368                 ui->vu_meter->set_level(level_lufs);
369                 ui->lra_meter->set_levels(global_level_lufs, range_low_lufs, range_high_lufs);
370                 ui->correlation_meter->set_correlation(correlation);
371
372                 ui->peak_display->setText(QString::fromStdString(format_db(peak_db, DB_BARE)));
373                 if (peak_db > -0.1f) {  // -0.1 dBFS is EBU peak limit.
374                         ui->peak_display->setStyleSheet("QLabel { background-color: red; color: white; }");
375                 } else {
376                         ui->peak_display->setStyleSheet("");
377                 }
378
379                 ui->gainstaging_knob->blockSignals(true);
380                 ui->gainstaging_knob->setValue(lrintf(gain_staging_db * 10.0f));
381                 ui->gainstaging_knob->blockSignals(false);
382                 ui->gainstaging_db_display->setText(
383                         QString::fromStdString(format_db(gain_staging_db, DB_WITH_SIGN)));
384
385                 ui->makeup_gain_knob->blockSignals(true);
386                 ui->makeup_gain_knob->setValue(lrintf(final_makeup_gain_db * 10.0f));
387                 ui->makeup_gain_knob->blockSignals(false);
388                 ui->makeup_gain_db_display->setText(
389                         QString::fromStdString(format_db(final_makeup_gain_db, DB_WITH_SIGN)));
390         });
391 }
392
393 void MainWindow::relayout()
394 {
395         int height = ui->vertical_layout->geometry().height();
396
397         double remaining_height = height;
398
399         // Allocate the height; the most important part is to keep the main displays
400         // at 16:9 if at all possible.
401         double me_width = ui->me_preview->width();
402         double me_height = me_width * 9.0 / 16.0 + ui->label_preview->height() + ui->preview_vertical_layout->spacing();
403
404         // TODO: Scale the widths when we need to do this.
405         if (me_height / double(height) > 0.8) {
406                 me_height = height * 0.8;
407         }
408         remaining_height -= me_height + ui->vertical_layout->spacing();
409
410         double audiostrip_height = ui->audiostrip->geometry().height();
411         remaining_height -= audiostrip_height + ui->vertical_layout->spacing();
412
413         // The previews will be constrained by the remaining height, and the width.
414         double preview_label_height = previews[0]->title_bar->geometry().height() +
415                 previews[0]->main_vertical_layout->spacing();
416         int preview_total_width = ui->preview_displays->geometry().width() - (previews.size() - 1) * ui->preview_displays->spacing();
417         double preview_height = min(remaining_height - preview_label_height, (preview_total_width / double(previews.size())) * 9.0 / 16.0);
418         remaining_height -= preview_height + preview_label_height + ui->vertical_layout->spacing();
419
420         ui->vertical_layout->setStretch(0, lrintf(me_height));
421         ui->vertical_layout->setStretch(1, 0);  // Don't stretch the audiostrip.
422         ui->vertical_layout->setStretch(2, max<int>(1, remaining_height));  // Spacer.
423         ui->vertical_layout->setStretch(3, lrintf(preview_height + preview_label_height));
424
425         // Set the widths for the previews.
426         double preview_width = preview_height * 16.0 / 9.0;
427         for (unsigned i = 0; i < previews.size(); ++i) {
428                 ui->preview_displays->setStretch(i, lrintf(preview_width));
429         }
430
431         // The preview horizontal spacer.
432         double remaining_preview_width = preview_total_width - previews.size() * preview_width;
433         ui->preview_displays->setStretch(previews.size(), lrintf(remaining_preview_width));
434 }
435
436 void MainWindow::set_transition_names(vector<string> transition_names)
437 {
438         if (transition_names.size() < 1 || transition_names[0].empty()) {
439                 transition_btn1->setText(QString(""));
440         } else {
441                 transition_btn1->setText(QString::fromStdString(transition_names[0] + " (J)"));
442                 ui->transition_btn1->setShortcut(QKeySequence("J"));
443         }
444         if (transition_names.size() < 2 || transition_names[1].empty()) {
445                 transition_btn2->setText(QString(""));
446         } else {
447                 transition_btn2->setText(QString::fromStdString(transition_names[1] + " (K)"));
448                 ui->transition_btn2->setShortcut(QKeySequence("K"));
449         }
450         if (transition_names.size() < 3 || transition_names[2].empty()) {
451                 transition_btn3->setText(QString(""));
452         } else {
453                 transition_btn3->setText(QString::fromStdString(transition_names[2] + " (L)"));
454                 ui->transition_btn3->setShortcut(QKeySequence("L"));
455         }
456 }
457
458 void MainWindow::update_channel_name(Mixer::Output output, const string &name)
459 {
460         if (output >= Mixer::OUTPUT_INPUT0) {
461                 unsigned channel = output - Mixer::OUTPUT_INPUT0;
462                 previews[channel]->label->setText(name.c_str());
463         }
464 }
465
466 void MainWindow::update_channel_color(Mixer::Output output, const string &color)
467 {
468         if (output >= Mixer::OUTPUT_INPUT0) {
469                 unsigned channel = output - Mixer::OUTPUT_INPUT0;
470                 previews[channel]->frame->setStyleSheet(QString::fromStdString("background-color:" + color));
471         }
472 }
473
474 void MainWindow::transition_clicked(int transition_number)
475 {
476         global_mixer->transition_clicked(transition_number);
477 }
478
479 void MainWindow::channel_clicked(int channel_number)
480 {
481         if (current_wb_pick_display == channel_number) {
482                 // The picking was already done from eventFilter(), since we don't get
483                 // the mouse pointer here.
484         } else {
485                 global_mixer->channel_clicked(channel_number);
486         }
487 }
488
489 void MainWindow::wb_button_clicked(int channel_number)
490 {
491         current_wb_pick_display = channel_number;
492         QApplication::setOverrideCursor(Qt::CrossCursor);
493 }
494
495 bool MainWindow::eventFilter(QObject *watched, QEvent *event)
496 {
497         if (current_wb_pick_display != -1 &&
498             event->type() == QEvent::MouseButtonRelease &&
499             watched->isWidgetType()) {
500                 QApplication::restoreOverrideCursor();
501                 if (watched == previews[current_wb_pick_display]->display) {
502                         const QMouseEvent *mouse_event = (QMouseEvent *)event;
503                         set_white_balance(current_wb_pick_display, mouse_event->x(), mouse_event->y());
504                 } else {
505                         // The user clicked on something else, give up.
506                         // (The click goes through, which might not be ideal, but, yes.)
507                         current_wb_pick_display = -1;
508                 }
509         }
510         return false;
511 }
512
513 namespace {
514
515 double srgb_to_linear(double x)
516 {
517         if (x < 0.04045) {
518                 return x / 12.92;
519         } else {
520                 return pow((x + 0.055) / 1.055, 2.4);
521         }
522 }
523
524 }  // namespace
525
526 void MainWindow::set_white_balance(int channel_number, int x, int y)
527 {
528         // Set the white balance to neutral for the grab. It's probably going to
529         // flicker a bit, but hopefully this display is not live anyway.
530         global_mixer->set_wb(Mixer::OUTPUT_INPUT0 + channel_number, 0.5, 0.5, 0.5);
531         previews[channel_number]->display->updateGL();
532         QRgb reference_color = previews[channel_number]->display->grabFrameBuffer().pixel(x, y);
533
534         double r = srgb_to_linear(qRed(reference_color) / 255.0);
535         double g = srgb_to_linear(qGreen(reference_color) / 255.0);
536         double b = srgb_to_linear(qBlue(reference_color) / 255.0);
537         global_mixer->set_wb(Mixer::OUTPUT_INPUT0 + channel_number, r, g, b);
538         previews[channel_number]->display->updateGL();
539 }