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