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