]> git.sesse.net Git - nageru/blob - futatabi/mainwindow.cpp
Add a MIDI mapping editor for Futatabi.
[nageru] / futatabi / mainwindow.cpp
1 #include "mainwindow.h"
2
3 #include "clip_list.h"
4 #include "export.h"
5 #include "flags.h"
6 #include "frame_on_disk.h"
7 #include "player.h"
8 #include "futatabi_midi_mapping.pb.h"
9 #include "midi_mapping_dialog.h"
10 #include "shared/aboutdialog.h"
11 #include "shared/disk_space_estimator.h"
12 #include "shared/post_to_main_thread.h"
13 #include "shared/timebase.h"
14 #include "ui_mainwindow.h"
15
16 #include <QDesktopServices>
17 #include <QFileDialog>
18 #include <QMessageBox>
19 #include <QMouseEvent>
20 #include <QNetworkReply>
21 #include <QShortcut>
22 #include <QTimer>
23 #include <QWheelEvent>
24 #include <future>
25 #include <sqlite3.h>
26 #include <string>
27 #include <vector>
28
29 using namespace std;
30 using namespace std::placeholders;
31
32 MainWindow *global_mainwindow = nullptr;
33 static ClipList *cliplist_clips;
34 static PlayList *playlist_clips;
35
36 extern int64_t current_pts;
37
38 namespace {
39
40 void set_pts_in(int64_t pts, int64_t current_pts, ClipProxy &clip)
41 {
42         pts = std::max<int64_t>(pts, 0);
43         if (clip->pts_out == -1) {
44                 pts = std::min(pts, current_pts);
45         } else {
46                 pts = std::min(pts, clip->pts_out);
47         }
48         clip->pts_in = pts;
49 }
50
51 }  // namespace
52
53 MainWindow::MainWindow()
54         : ui(new Ui::MainWindow),
55           db(global_flags.working_directory + "/futatabi.db"),
56           midi_mapper(this)
57 {
58         global_mainwindow = this;
59         ui->setupUi(this);
60
61         // Load settings from database.
62         SettingsProto settings = db.get_settings();
63         if (!global_flags.interpolation_quality_set) {
64                 if (settings.interpolation_quality() != 0) {
65                         global_flags.interpolation_quality = settings.interpolation_quality() - 1;
66                 }
67         }
68         if (!global_flags.cue_point_padding_set) {
69                 global_flags.cue_point_padding_seconds = settings.cue_point_padding_seconds();  // Default 0 is fine.
70         }
71         if (global_flags.interpolation_quality == 0) {
72                 // Allocate something just for simplicity; we won't be using it
73                 // unless the user changes runtime, in which case 1 is fine.
74                 flow_initialized_interpolation_quality = 1;
75         } else {
76                 flow_initialized_interpolation_quality = global_flags.interpolation_quality;
77         }
78         save_settings();
79
80         // The menus.
81         connect(ui->midi_mapping_action, &QAction::triggered, this, &MainWindow::midi_mapping_triggered);
82         connect(ui->exit_action, &QAction::triggered, this, &MainWindow::exit_triggered);
83         connect(ui->export_cliplist_clip_multitrack_action, &QAction::triggered, this, &MainWindow::export_cliplist_clip_multitrack_triggered);
84         connect(ui->export_playlist_clip_interpolated_action, &QAction::triggered, this, &MainWindow::export_playlist_clip_interpolated_triggered);
85         connect(ui->manual_action, &QAction::triggered, this, &MainWindow::manual_triggered);
86         connect(ui->about_action, &QAction::triggered, this, &MainWindow::about_triggered);
87         connect(ui->undo_action, &QAction::triggered, this, &MainWindow::undo_triggered);
88         connect(ui->redo_action, &QAction::triggered, this, &MainWindow::redo_triggered);
89         ui->undo_action->setEnabled(false);
90         ui->redo_action->setEnabled(false);
91
92         // The quality group.
93         QActionGroup *quality_group = new QActionGroup(ui->interpolation_menu);
94         quality_group->addAction(ui->quality_0_action);
95         quality_group->addAction(ui->quality_1_action);
96         quality_group->addAction(ui->quality_2_action);
97         quality_group->addAction(ui->quality_3_action);
98         quality_group->addAction(ui->quality_4_action);
99         if (global_flags.interpolation_quality == 0) {
100                 ui->quality_0_action->setChecked(true);
101         } else if (global_flags.interpolation_quality == 1) {
102                 ui->quality_1_action->setChecked(true);
103         } else if (global_flags.interpolation_quality == 2) {
104                 ui->quality_2_action->setChecked(true);
105         } else if (global_flags.interpolation_quality == 3) {
106                 ui->quality_3_action->setChecked(true);
107         } else if (global_flags.interpolation_quality == 4) {
108                 ui->quality_4_action->setChecked(true);
109         } else {
110                 assert(false);
111         }
112         connect(ui->quality_0_action, &QAction::toggled, bind(&MainWindow::quality_toggled, this, 0, _1));
113         connect(ui->quality_1_action, &QAction::toggled, bind(&MainWindow::quality_toggled, this, 1, _1));
114         connect(ui->quality_2_action, &QAction::toggled, bind(&MainWindow::quality_toggled, this, 2, _1));
115         connect(ui->quality_3_action, &QAction::toggled, bind(&MainWindow::quality_toggled, this, 3, _1));
116         connect(ui->quality_4_action, &QAction::toggled, bind(&MainWindow::quality_toggled, this, 4, _1));
117
118         // The cue point padding group.
119         QActionGroup *padding_group = new QActionGroup(ui->interpolation_menu);
120         padding_group->addAction(ui->padding_0_action);
121         padding_group->addAction(ui->padding_1_action);
122         padding_group->addAction(ui->padding_2_action);
123         padding_group->addAction(ui->padding_5_action);
124         if (global_flags.cue_point_padding_seconds <= 1e-3) {
125                 ui->padding_0_action->setChecked(true);
126         } else if (fabs(global_flags.cue_point_padding_seconds - 1.0) < 1e-3) {
127                 ui->padding_1_action->setChecked(true);
128         } else if (fabs(global_flags.cue_point_padding_seconds - 2.0) < 1e-3) {
129                 ui->padding_2_action->setChecked(true);
130         } else if (fabs(global_flags.cue_point_padding_seconds - 5.0) < 1e-3) {
131                 ui->padding_5_action->setChecked(true);
132         } else {
133                 // Nothing to check, which is fine.
134         }
135         connect(ui->padding_0_action, &QAction::toggled, bind(&MainWindow::padding_toggled, this, 0.0, _1));
136         connect(ui->padding_1_action, &QAction::toggled, bind(&MainWindow::padding_toggled, this, 1.0, _1));
137         connect(ui->padding_2_action, &QAction::toggled, bind(&MainWindow::padding_toggled, this, 2.0, _1));
138         connect(ui->padding_5_action, &QAction::toggled, bind(&MainWindow::padding_toggled, this, 5.0, _1));
139
140         global_disk_space_estimator = new DiskSpaceEstimator(bind(&MainWindow::report_disk_space, this, _1, _2));
141         disk_free_label = new QLabel(this);
142         disk_free_label->setStyleSheet("QLabel {padding-right: 5px;}");
143         ui->menuBar->setCornerWidget(disk_free_label);
144
145         StateProto state = db.get_state();
146         undo_stack.push_back(state);  // The undo stack always has the current state on top.
147
148         cliplist_clips = new ClipList(state.clip_list());
149         ui->clip_list->setModel(cliplist_clips);
150         connect(cliplist_clips, &ClipList::any_content_changed, this, &MainWindow::content_changed);
151
152         playlist_clips = new PlayList(state.play_list());
153         ui->playlist->setModel(playlist_clips);
154         connect(playlist_clips, &PlayList::any_content_changed, this, &MainWindow::content_changed);
155
156         // For un-highlighting when we lose focus.
157         ui->clip_list->installEventFilter(this);
158
159         // For scrubbing in the pts columns.
160         ui->clip_list->viewport()->installEventFilter(this);
161         ui->playlist->viewport()->installEventFilter(this);
162
163         QShortcut *cue_in = new QShortcut(QKeySequence(Qt::Key_A), this);
164         connect(cue_in, &QShortcut::activated, ui->cue_in_btn, &QPushButton::click);
165         connect(ui->cue_in_btn, &QPushButton::clicked, this, &MainWindow::cue_in_clicked);
166
167         QShortcut *cue_out = new QShortcut(QKeySequence(Qt::Key_S), this);
168         connect(cue_out, &QShortcut::activated, ui->cue_out_btn, &QPushButton::click);
169         connect(ui->cue_out_btn, &QPushButton::clicked, this, &MainWindow::cue_out_clicked);
170
171         QShortcut *queue = new QShortcut(QKeySequence(Qt::Key_Q), this);
172         connect(queue, &QShortcut::activated, ui->queue_btn, &QPushButton::click);
173         connect(ui->queue_btn, &QPushButton::clicked, this, &MainWindow::queue_clicked);
174
175         QShortcut *preview = new QShortcut(QKeySequence(Qt::Key_W), this);
176         connect(preview, &QShortcut::activated, ui->preview_btn, &QPushButton::click);
177         connect(ui->preview_btn, &QPushButton::clicked, this, &MainWindow::preview_clicked);
178
179         QShortcut *play = new QShortcut(QKeySequence(Qt::Key_Space), this);
180         connect(play, &QShortcut::activated, ui->play_btn, &QPushButton::click);
181         connect(ui->play_btn, &QPushButton::clicked, this, &MainWindow::play_clicked);
182
183         connect(ui->stop_btn, &QPushButton::clicked, this, &MainWindow::stop_clicked);
184         ui->stop_btn->setEnabled(false);
185
186         connect(ui->speed_slider, &QAbstractSlider::valueChanged, this, &MainWindow::speed_slider_changed);
187         connect(ui->speed_lock_btn, &QPushButton::clicked, this, &MainWindow::speed_lock_clicked);
188
189         connect(ui->playlist_duplicate_btn, &QPushButton::clicked, this, &MainWindow::playlist_duplicate);
190
191         connect(ui->playlist_remove_btn, &QPushButton::clicked, this, &MainWindow::playlist_remove);
192         QShortcut *delete_key = new QShortcut(QKeySequence(Qt::Key_Delete), ui->playlist);
193         connect(delete_key, &QShortcut::activated, [this] {
194                 if (ui->playlist->hasFocus()) {
195                         playlist_remove();
196                 }
197         });
198
199         // TODO: support drag-and-drop.
200         connect(ui->playlist_move_up_btn, &QPushButton::clicked, [this] { playlist_move(-1); });
201         connect(ui->playlist_move_down_btn, &QPushButton::clicked, [this] { playlist_move(1); });
202
203         connect(ui->playlist->selectionModel(), &QItemSelectionModel::selectionChanged,
204                 this, &MainWindow::playlist_selection_changed);
205         playlist_selection_changed();  // First time set-up.
206
207         preview_player.reset(new Player(ui->preview_display, Player::NO_STREAM_OUTPUT));
208         preview_player->set_done_callback([this] {
209                 post_to_main_thread([this] {
210                         preview_player_done();
211                 });
212         });
213
214         live_player.reset(new Player(ui->live_display, Player::HTTPD_STREAM_OUTPUT));
215         live_player->set_done_callback([this] {
216                 post_to_main_thread([this] {
217                         live_player_done();
218                 });
219         });
220         live_player->set_progress_callback([this](const map<uint64_t, double> &progress, double time_remaining) {
221                 post_to_main_thread([this, progress, time_remaining] {
222                         live_player_clip_progress(progress, time_remaining);
223                 });
224         });
225         set_output_status("paused");
226         enable_or_disable_queue_button();
227
228         defer_timeout = new QTimer(this);
229         defer_timeout->setSingleShot(true);
230         connect(defer_timeout, &QTimer::timeout, this, &MainWindow::defer_timer_expired);
231         ui->undo_action->setEnabled(true);
232
233         lock_blink_timeout = new QTimer(this);
234         lock_blink_timeout->setSingleShot(true);
235         connect(lock_blink_timeout, &QTimer::timeout, this, &MainWindow::lock_blink_timer_expired);
236
237         connect(ui->clip_list->selectionModel(), &QItemSelectionModel::currentChanged,
238                 this, &MainWindow::clip_list_selection_changed);
239         enable_or_disable_queue_button();
240
241         // Find out how many cameras we have in the existing frames;
242         // if none, we start with two cameras.
243         num_cameras = 2;
244         {
245                 lock_guard<mutex> lock(frame_mu);
246                 for (size_t stream_idx = 2; stream_idx < MAX_STREAMS; ++stream_idx) {
247                         if (!frames[stream_idx].empty()) {
248                                 num_cameras = stream_idx + 1;
249                         }
250                 }
251         }
252         change_num_cameras();
253
254         if (!global_flags.tally_url.empty()) {
255                 start_tally();
256         }
257
258         if (!global_flags.midi_mapping_filename.empty()) {
259                 MIDIMappingProto midi_mapping;
260                 if (!load_midi_mapping_from_file(global_flags.midi_mapping_filename, &midi_mapping)) {
261                         fprintf(stderr, "Couldn't load MIDI mapping '%s'; exiting.\n",
262                                 global_flags.midi_mapping_filename.c_str());
263                         exit(1);
264                 }
265                 midi_mapper.set_midi_mapping(midi_mapping);
266         }
267         midi_mapper.refresh_lights();
268         midi_mapper.start_thread();
269 }
270
271 void MainWindow::change_num_cameras()
272 {
273         assert(num_cameras >= displays.size());  // We only add, never remove.
274
275         // Make new display rows.
276         unsigned display_rows = (num_cameras + 1) / 2;
277         ui->video_displays->setStretch(1, display_rows);
278         for (unsigned i = displays.size(); i < num_cameras; ++i) {
279                 QFrame *frame = new QFrame(this);
280                 frame->setAutoFillBackground(true);
281
282                 QLayout *layout = new QGridLayout(frame);
283                 frame->setLayout(layout);
284                 layout->setContentsMargins(3, 3, 3, 3);
285
286                 JPEGFrameView *display = new JPEGFrameView(frame);
287                 display->setAutoFillBackground(true);
288                 layout->addWidget(display);
289
290                 ui->input_displays->addWidget(frame, i / 2, i % 2);
291                 display->set_overlay(to_string(i + 1));
292
293                 QPushButton *preview_btn = new QPushButton(this);
294                 preview_btn->setMaximumSize(20, 17);
295                 preview_btn->setText(QString::fromStdString(to_string(i + 1)));
296                 ui->preview_layout->addWidget(preview_btn);
297
298                 displays.emplace_back(FrameAndDisplay{ frame, display, preview_btn });
299
300                 connect(display, &JPEGFrameView::clicked, preview_btn, &QPushButton::click);
301                 QShortcut *shortcut = new QShortcut(QKeySequence(Qt::Key_1 + i), this);
302                 connect(shortcut, &QShortcut::activated, preview_btn, &QPushButton::click);
303
304                 connect(preview_btn, &QPushButton::clicked, [this, i] { preview_angle_clicked(i); });
305         }
306
307         cliplist_clips->change_num_cameras(num_cameras);
308         playlist_clips->change_num_cameras(num_cameras);
309
310         QMetaObject::invokeMethod(this, "relayout", Qt::QueuedConnection);
311 }
312
313 MainWindow::~MainWindow()
314 {
315         // Empty so that we can forward-declare Player in the .h file.
316 }
317
318 void MainWindow::cue_in_clicked()
319 {
320         if (!cliplist_clips->empty() && cliplist_clips->back()->pts_out < 0) {
321                 cliplist_clips->mutable_back()->pts_in = current_pts;
322         } else {
323                 Clip clip;
324                 clip.pts_in = max<int64_t>(current_pts - lrint(global_flags.cue_point_padding_seconds * TIMEBASE), 0);
325                 cliplist_clips->add_clip(clip);
326                 playlist_selection_changed();
327         }
328
329         // Select the item so that we can jog it.
330         ui->clip_list->setFocus();
331         QModelIndex index = cliplist_clips->index(cliplist_clips->size() - 1, int(ClipList::Column::IN));
332         ui->clip_list->selectionModel()->setCurrentIndex(index, QItemSelectionModel::ClearAndSelect);
333         ui->clip_list->scrollToBottom();
334         enable_or_disable_queue_button();
335 }
336
337 void MainWindow::cue_out_clicked()
338 {
339         if (cliplist_clips->empty()) {
340                 return;
341         }
342
343         cliplist_clips->mutable_back()->pts_out = current_pts + lrint(global_flags.cue_point_padding_seconds * TIMEBASE);
344
345         // Select the item so that we can jog it.
346         ui->clip_list->setFocus();
347         QModelIndex index = cliplist_clips->index(cliplist_clips->size() - 1, int(ClipList::Column::OUT));
348         ui->clip_list->selectionModel()->setCurrentIndex(index, QItemSelectionModel::ClearAndSelect);
349         ui->clip_list->scrollToBottom();
350         enable_or_disable_queue_button();
351 }
352
353 void MainWindow::queue_clicked()
354 {
355         // See also enable_or_disable_queue_button().
356
357         if (cliplist_clips->empty()) {
358                 return;
359         }
360
361         QItemSelectionModel *selected = ui->clip_list->selectionModel();
362         if (!selected->hasSelection()) {
363                 Clip clip = *cliplist_clips->back();
364                 clip.stream_idx = 0;
365                 if (clip.pts_out != -1) {
366                         playlist_clips->add_clip(clip);
367                         playlist_selection_changed();
368                         ui->playlist->scrollToBottom();
369                 }
370                 return;
371         }
372
373         QModelIndex index = selected->currentIndex();
374         Clip clip = *cliplist_clips->clip(index.row());
375         if (cliplist_clips->is_camera_column(index.column())) {
376                 clip.stream_idx = index.column() - int(ClipList::Column::CAMERA_1);
377         } else {
378                 clip.stream_idx = ui->preview_display->get_stream_idx();
379         }
380
381         if (clip.pts_out != -1) {
382                 playlist_clips->add_clip(clip);
383                 playlist_selection_changed();
384                 ui->playlist->scrollToBottom();
385                 if (!ui->playlist->selectionModel()->hasSelection()) {
386                         // TODO: Figure out why this doesn't always seem to actually select the row.
387                         QModelIndex bottom = playlist_clips->index(playlist_clips->size() - 1, 0);
388                         ui->playlist->setCurrentIndex(bottom);
389                 }
390         }
391 }
392
393 void MainWindow::preview_clicked()
394 {
395         // See also enable_or_disable_preview_button().
396
397         if (ui->playlist->hasFocus()) {
398                 // Allow the playlist as preview iff it has focus and something is selected.
399                 QItemSelectionModel *selected = ui->playlist->selectionModel();
400                 if (selected->hasSelection()) {
401                         QModelIndex index = selected->currentIndex();
402                         const Clip &clip = *playlist_clips->clip(index.row());
403                         preview_player->play(clip);
404                         preview_playing = true;
405                         enable_or_disable_preview_button();
406                         return;
407                 }
408         }
409
410         if (cliplist_clips->empty())
411                 return;
412
413         QItemSelectionModel *selected = ui->clip_list->selectionModel();
414         if (!selected->hasSelection()) {
415                 preview_player->play(*cliplist_clips->back());
416                 preview_playing = true;
417                 enable_or_disable_preview_button();
418                 return;
419         }
420
421         QModelIndex index = selected->currentIndex();
422         Clip clip = *cliplist_clips->clip(index.row());
423         if (cliplist_clips->is_camera_column(index.column())) {
424                 clip.stream_idx = index.column() - int(ClipList::Column::CAMERA_1);
425         } else {
426                 clip.stream_idx = ui->preview_display->get_stream_idx();
427         }
428         preview_player->play(clip);
429         preview_playing = true;
430         enable_or_disable_preview_button();
431 }
432
433 void MainWindow::preview_angle_clicked(unsigned stream_idx)
434 {
435         preview_player->override_angle(stream_idx);
436
437         // Change the selection if we were previewing a clip from the clip list.
438         // (The only other thing we could be showing is a pts scrub, and if so,
439         // that would be selected.)
440         QItemSelectionModel *selected = ui->clip_list->selectionModel();
441         if (selected->hasSelection()) {
442                 QModelIndex cell = selected->selectedIndexes()[0];
443                 int column = int(ClipList::Column::CAMERA_1) + stream_idx;
444                 selected->setCurrentIndex(cell.sibling(cell.row(), column), QItemSelectionModel::ClearAndSelect);
445         }
446 }
447
448 void MainWindow::playlist_duplicate()
449 {
450         QItemSelectionModel *selected = ui->playlist->selectionModel();
451         if (!selected->hasSelection()) {
452                 // Should have been grayed out, but OK.
453                 return;
454         }
455         QModelIndexList rows = selected->selectedRows();
456         int first = rows.front().row(), last = rows.back().row();
457         playlist_clips->duplicate_clips(first, last);
458         playlist_selection_changed();
459 }
460
461 void MainWindow::playlist_remove()
462 {
463         QItemSelectionModel *selected = ui->playlist->selectionModel();
464         if (!selected->hasSelection()) {
465                 // Should have been grayed out, but OK.
466                 return;
467         }
468         QModelIndexList rows = selected->selectedRows();
469         int first = rows.front().row(), last = rows.back().row();
470         playlist_clips->erase_clips(first, last);
471
472         // TODO: select the next one in the list?
473
474         playlist_selection_changed();
475 }
476
477 void MainWindow::playlist_move(int delta)
478 {
479         QItemSelectionModel *selected = ui->playlist->selectionModel();
480         if (!selected->hasSelection()) {
481                 // Should have been grayed out, but OK.
482                 return;
483         }
484
485         QModelIndexList rows = selected->selectedRows();
486         int first = rows.front().row(), last = rows.back().row();
487         if ((delta == -1 && first == 0) ||
488             (delta == 1 && size_t(last) == playlist_clips->size() - 1)) {
489                 // Should have been grayed out, but OK.
490                 return;
491         }
492
493         playlist_clips->move_clips(first, last, delta);
494         playlist_selection_changed();
495 }
496
497 void MainWindow::jog_internal(JogDestination jog_destination, int row, int column, int stream_idx, int pts_delta)
498 {
499         constexpr int camera_pts_per_pixel = 1500;  // One click of most mice (15 degrees), multiplied by the default wheel_sensitivity.
500
501         int in_column, out_column, camera_column;
502         if (jog_destination == JOG_CLIP_LIST) {
503                 in_column = int(ClipList::Column::IN);
504                 out_column = int(ClipList::Column::OUT);
505                 camera_column = -1;
506         } else if (jog_destination == JOG_PLAYLIST) {
507                 in_column = int(PlayList::Column::IN);
508                 out_column = int(PlayList::Column::OUT);
509                 camera_column = int(PlayList::Column::CAMERA);
510         } else {
511                 assert(false);
512         }
513
514         currently_deferring_model_changes = true;
515         {
516                 current_change_id = (jog_destination == JOG_CLIP_LIST) ? "cliplist:" : "playlist:";
517                 ClipProxy clip = (jog_destination == JOG_CLIP_LIST) ? cliplist_clips->mutable_clip(row) : playlist_clips->mutable_clip(row);
518                 if (jog_destination == JOG_PLAYLIST) {
519                         stream_idx = clip->stream_idx;
520                 }
521
522                 if (column == in_column) {
523                         current_change_id += "in:" + to_string(row);
524                         int64_t pts = clip->pts_in + pts_delta;
525                         set_pts_in(pts, current_pts, clip);
526                         preview_single_frame(pts, stream_idx, FIRST_AT_OR_AFTER);
527                 } else if (column == out_column) {
528                         current_change_id += "out:" + to_string(row);
529                         int64_t pts = clip->pts_out + pts_delta;
530                         pts = std::max(pts, clip->pts_in);
531                         pts = std::min(pts, current_pts);
532                         clip->pts_out = pts;
533                         preview_single_frame(pts, stream_idx, LAST_BEFORE);
534                 } else if (column == camera_column) {
535                         current_change_id += "camera:" + to_string(row);
536                         int angle_degrees = pts_delta;
537                         if (last_mousewheel_camera_row == row) {
538                                 angle_degrees += leftover_angle_degrees;
539                         }
540
541                         int stream_idx = clip->stream_idx + angle_degrees / camera_pts_per_pixel;
542                         stream_idx = std::max(stream_idx, 0);
543                         stream_idx = std::min<int>(stream_idx, num_cameras - 1);
544                         clip->stream_idx = stream_idx;
545
546                         last_mousewheel_camera_row = row;
547                         leftover_angle_degrees = angle_degrees % camera_pts_per_pixel;
548
549                         // Don't update the live view, that's rarely what the operator wants.
550                 }
551         }
552         currently_deferring_model_changes = false;
553 }
554
555 void MainWindow::defer_timer_expired()
556 {
557         state_changed(deferred_state);
558 }
559
560 void MainWindow::content_changed()
561 {
562         // If we are playing, update the part of the playlist that's not playing yet.
563         vector<ClipWithID> clips;
564         for (unsigned row = 0; row < playlist_clips->size(); ++row) {
565                 clips.emplace_back(*playlist_clips->clip_with_id(row));
566         }
567         live_player->splice_play(clips);
568
569         // Serialize the state.
570         if (defer_timeout->isActive() &&
571             (!currently_deferring_model_changes || deferred_change_id != current_change_id)) {
572                 // There's some deferred event waiting, but this event is unrelated.
573                 // So it's time to short-circuit that timer and do the work it wanted to do.
574                 defer_timeout->stop();
575                 state_changed(deferred_state);
576         }
577         StateProto state;
578         *state.mutable_clip_list() = cliplist_clips->serialize();
579         *state.mutable_play_list() = playlist_clips->serialize();
580         if (currently_deferring_model_changes) {
581                 deferred_change_id = current_change_id;
582                 deferred_state = std::move(state);
583                 defer_timeout->start(200);
584                 return;
585         }
586         state_changed(state);
587 }
588
589 void MainWindow::state_changed(const StateProto &state)
590 {
591         db.store_state(state);
592
593         redo_stack.clear();
594         ui->redo_action->setEnabled(false);
595
596         undo_stack.push_back(state);
597         ui->undo_action->setEnabled(undo_stack.size() > 1);
598
599         // Make sure it doesn't grow without bounds.
600         while (undo_stack.size() >= 100) {
601                 undo_stack.pop_front();
602         }
603 }
604
605 void MainWindow::save_settings()
606 {
607         SettingsProto settings;
608         settings.set_interpolation_quality(global_flags.interpolation_quality + 1);
609         settings.set_cue_point_padding_seconds(global_flags.cue_point_padding_seconds);
610         db.store_settings(settings);
611 }
612
613 void MainWindow::lock_blink_timer_expired()
614 {
615         midi_mapper.set_locked(MIDIMapper::LightState(ui->speed_lock_btn->isChecked()));  // Presumably On, or the timer should have been canceled.
616 }
617
618 void MainWindow::play_clicked()
619 {
620         QItemSelectionModel *selected = ui->playlist->selectionModel();
621         if (!selected->hasSelection()) {
622                 return;
623         }
624         unsigned start_row = selected->selectedRows(0)[0].row();
625
626         vector<ClipWithID> clips;
627         for (unsigned row = start_row; row < playlist_clips->size(); ++row) {
628                 clips.emplace_back(*playlist_clips->clip_with_id(row));
629         }
630         live_player->play(clips);
631         playlist_clips->set_progress({ { start_row, 0.0f } });
632         ui->playlist->selectionModel()->clear();
633         ui->stop_btn->setEnabled(true);
634         playlist_selection_changed();
635 }
636
637 void MainWindow::stop_clicked()
638 {
639         Clip fake_clip;
640         fake_clip.pts_in = 0;
641         fake_clip.pts_out = 0;
642         playlist_clips->set_progress({});
643         live_player->play(fake_clip);
644         ui->stop_btn->setEnabled(false);
645         playlist_selection_changed();
646 }
647
648 void MainWindow::speed_slider_changed(int percent)
649 {
650         float speed = percent / 100.0f;
651         ui->speed_lock_btn->setText(QString::fromStdString(" " + to_string(percent) + "%"));
652         live_player->set_master_speed(speed);
653         midi_mapper.set_speed_light(speed);
654 }
655
656 void MainWindow::speed_lock_clicked()
657 {
658         // TODO: Make for a less abrupt transition if we're not already at 100%.
659         ui->speed_slider->setValue(100);  // Also actually sets the master speed and updates the label.
660         ui->speed_slider->setEnabled(!ui->speed_lock_btn->isChecked());
661         midi_mapper.set_locked(MIDIMapper::LightState(ui->speed_lock_btn->isChecked()));
662         lock_blink_timeout->stop();
663 }
664
665 void MainWindow::preview_player_done()
666 {
667         preview_playing = false;
668         enable_or_disable_preview_button();
669 }
670
671 void MainWindow::live_player_done()
672 {
673         playlist_clips->set_progress({});
674         ui->stop_btn->setEnabled(false);
675         playlist_selection_changed();
676 }
677
678 void MainWindow::live_player_clip_progress(const map<uint64_t, double> &progress, double time_remaining)
679 {
680         playlist_clips->set_progress(progress);
681         set_output_status(format_duration(time_remaining) + " left");
682 }
683
684 void MainWindow::resizeEvent(QResizeEvent *event)
685 {
686         QMainWindow::resizeEvent(event);
687
688         // Ask for a relayout, but only after the event loop is done doing relayout
689         // on everything else.
690         QMetaObject::invokeMethod(this, "relayout", Qt::QueuedConnection);
691 }
692
693 void MainWindow::relayout()
694 {
695         ui->live_display->setMinimumWidth(ui->live_display->height() * 16 / 9);
696         ui->preview_display->setMinimumWidth(ui->preview_display->height() * 16 / 9);
697 }
698
699 bool MainWindow::eventFilter(QObject *watched, QEvent *event)
700 {
701         constexpr int dead_zone_pixels = 3;  // To avoid that simple clicks get misinterpreted.
702         int scrub_sensitivity = 100;  // pts units per pixel.
703         int wheel_sensitivity = 100;  // pts units per degree.
704
705         if (event->type() == QEvent::FocusIn || event->type() == QEvent::FocusOut) {
706                 enable_or_disable_preview_button();
707                 hidden_jog_column = -1;
708         }
709
710         unsigned stream_idx = ui->preview_display->get_stream_idx();
711
712         if (watched == ui->clip_list) {
713                 if (event->type() == QEvent::FocusOut) {
714                         highlight_camera_input(-1);
715                 }
716                 return false;
717         }
718
719         if (event->type() != QEvent::Wheel) {
720                 last_mousewheel_camera_row = -1;
721         }
722
723         if (event->type() == QEvent::MouseButtonPress) {
724                 QMouseEvent *mouse = (QMouseEvent *)event;
725
726                 QTableView *destination;
727                 ScrubType type;
728
729                 if (watched == ui->clip_list->viewport()) {
730                         destination = ui->clip_list;
731                         type = SCRUBBING_CLIP_LIST;
732                 } else if (watched == ui->playlist->viewport()) {
733                         destination = ui->playlist;
734                         type = SCRUBBING_PLAYLIST;
735                 } else {
736                         return false;
737                 }
738                 int column = destination->columnAt(mouse->x());
739                 int row = destination->rowAt(mouse->y());
740                 if (column == -1 || row == -1)
741                         return false;
742
743                 if (type == SCRUBBING_CLIP_LIST) {
744                         if (ClipList::Column(column) == ClipList::Column::IN) {
745                                 scrub_pts_origin = cliplist_clips->clip(row)->pts_in;
746                                 preview_single_frame(scrub_pts_origin, stream_idx, FIRST_AT_OR_AFTER);
747                         } else if (ClipList::Column(column) == ClipList::Column::OUT) {
748                                 scrub_pts_origin = cliplist_clips->clip(row)->pts_out;
749                                 preview_single_frame(scrub_pts_origin, stream_idx, LAST_BEFORE);
750                         } else {
751                                 return false;
752                         }
753                 } else {
754                         if (PlayList::Column(column) == PlayList::Column::IN) {
755                                 scrub_pts_origin = playlist_clips->clip(row)->pts_in;
756                                 preview_single_frame(scrub_pts_origin, stream_idx, FIRST_AT_OR_AFTER);
757                         } else if (PlayList::Column(column) == PlayList::Column::OUT) {
758                                 scrub_pts_origin = playlist_clips->clip(row)->pts_out;
759                                 preview_single_frame(scrub_pts_origin, stream_idx, LAST_BEFORE);
760                         } else {
761                                 return false;
762                         }
763                 }
764
765                 scrubbing = true;
766                 scrub_row = row;
767                 scrub_column = column;
768                 scrub_x_origin = mouse->x();
769                 scrub_type = type;
770         } else if (event->type() == QEvent::MouseMove) {
771                 QMouseEvent *mouse = (QMouseEvent *)event;
772                 if (mouse->modifiers() & Qt::KeyboardModifier::ShiftModifier) {
773                         scrub_sensitivity *= 10;
774                         wheel_sensitivity *= 10;
775                 }
776                 if (mouse->modifiers() & Qt::KeyboardModifier::AltModifier) {  // Note: Shift + Alt cancel each other out.
777                         scrub_sensitivity /= 10;
778                         wheel_sensitivity /= 10;
779                 }
780                 if (scrubbing) {
781                         int offset = mouse->x() - scrub_x_origin;
782                         int adjusted_offset;
783                         if (offset >= dead_zone_pixels) {
784                                 adjusted_offset = offset - dead_zone_pixels;
785                         } else if (offset < -dead_zone_pixels) {
786                                 adjusted_offset = offset + dead_zone_pixels;
787                         } else {
788                                 adjusted_offset = 0;
789                         }
790
791                         int64_t pts = scrub_pts_origin + adjusted_offset * scrub_sensitivity;
792                         currently_deferring_model_changes = true;
793                         if (scrub_type == SCRUBBING_CLIP_LIST) {
794                                 ClipProxy clip = cliplist_clips->mutable_clip(scrub_row);
795                                 if (scrub_column == int(ClipList::Column::IN)) {
796                                         current_change_id = "cliplist:in:" + to_string(scrub_row);
797                                         set_pts_in(pts, current_pts, clip);
798                                         preview_single_frame(pts, stream_idx, FIRST_AT_OR_AFTER);
799                                 } else {
800                                         current_change_id = "cliplist:out" + to_string(scrub_row);
801                                         pts = std::max(pts, clip->pts_in);
802                                         pts = std::min(pts, current_pts);
803                                         clip->pts_out = pts;
804                                         preview_single_frame(pts, stream_idx, LAST_BEFORE);
805                                 }
806                         } else {
807                                 ClipProxy clip = playlist_clips->mutable_clip(scrub_row);
808                                 if (scrub_column == int(PlayList::Column::IN)) {
809                                         current_change_id = "playlist:in:" + to_string(scrub_row);
810                                         set_pts_in(pts, current_pts, clip);
811                                         preview_single_frame(pts, clip->stream_idx, FIRST_AT_OR_AFTER);
812                                 } else {
813                                         current_change_id = "playlist:out:" + to_string(scrub_row);
814                                         pts = std::max(pts, clip->pts_in);
815                                         pts = std::min(pts, current_pts);
816                                         clip->pts_out = pts;
817                                         preview_single_frame(pts, clip->stream_idx, LAST_BEFORE);
818                                 }
819                         }
820                         currently_deferring_model_changes = false;
821
822                         return true;  // Don't use this mouse movement for selecting things.
823                 }
824         } else if (event->type() == QEvent::Wheel) {
825                 QWheelEvent *wheel = (QWheelEvent *)event;
826                 int angle_delta = wheel->angleDelta().y();
827                 if (wheel->modifiers() & Qt::KeyboardModifier::ShiftModifier) {
828                         scrub_sensitivity *= 10;
829                         wheel_sensitivity *= 10;
830                 }
831                 if (wheel->modifiers() & Qt::KeyboardModifier::AltModifier) {  // Note: Shift + Alt cancel each other out.
832                         scrub_sensitivity /= 10;
833                         wheel_sensitivity /= 10;
834                         angle_delta = wheel->angleDelta().x();  // Qt ickiness.
835                 }
836
837                 QTableView *destination;
838                 JogDestination jog_destination;
839                 if (watched == ui->clip_list->viewport()) {
840                         destination = ui->clip_list;
841                         jog_destination = JOG_CLIP_LIST;
842                         last_mousewheel_camera_row = -1;
843                 } else if (watched == ui->playlist->viewport()) {
844                         destination = ui->playlist;
845                         jog_destination = JOG_PLAYLIST;
846                         if (destination->columnAt(wheel->x()) != int(PlayList::Column::CAMERA)) {
847                                 last_mousewheel_camera_row = -1;
848                         }
849                 } else {
850                         last_mousewheel_camera_row = -1;
851                         return false;
852                 }
853
854                 int column = destination->columnAt(wheel->x());
855                 int row = destination->rowAt(wheel->y());
856                 if (column == -1 || row == -1)
857                         return false;
858
859                 // Only adjust pts with the wheel if the given row is selected.
860                 if (!destination->hasFocus() ||
861                     row != destination->selectionModel()->currentIndex().row()) {
862                         return false;
863                 }
864
865                 jog_internal(jog_destination, row, column, stream_idx, angle_delta * wheel_sensitivity);
866                 return true;  // Don't scroll.
867         } else if (event->type() == QEvent::MouseButtonRelease) {
868                 scrubbing = false;
869         }
870         return false;
871 }
872
873 void MainWindow::preview_single_frame(int64_t pts, unsigned stream_idx, MainWindow::Rounding rounding)
874 {
875         if (rounding == LAST_BEFORE) {
876                 lock_guard<mutex> lock(frame_mu);
877                 if (frames[stream_idx].empty())
878                         return;
879                 auto it = find_last_frame_before(frames[stream_idx], pts);
880                 if (it != frames[stream_idx].end()) {
881                         pts = it->pts;
882                 }
883         } else {
884                 assert(rounding == FIRST_AT_OR_AFTER);
885                 lock_guard<mutex> lock(frame_mu);
886                 if (frames[stream_idx].empty())
887                         return;
888                 auto it = find_first_frame_at_or_after(frames[stream_idx], pts);
889                 if (it != frames[stream_idx].end()) {
890                         pts = it->pts;
891                 }
892         }
893
894         Clip fake_clip;
895         fake_clip.pts_in = pts;
896         fake_clip.pts_out = pts + 1;
897         fake_clip.stream_idx = stream_idx;
898         preview_player->play(fake_clip);
899 }
900
901 void MainWindow::playlist_selection_changed()
902 {
903         enable_or_disable_preview_button();
904
905         QItemSelectionModel *selected = ui->playlist->selectionModel();
906         bool any_selected = selected->hasSelection();
907         ui->playlist_duplicate_btn->setEnabled(any_selected);
908         ui->playlist_remove_btn->setEnabled(any_selected);
909         ui->playlist_move_up_btn->setEnabled(
910                 any_selected && selected->selectedRows().front().row() > 0);
911         ui->playlist_move_down_btn->setEnabled(
912                 any_selected && selected->selectedRows().back().row() < int(playlist_clips->size()) - 1);
913
914         ui->play_btn->setEnabled(any_selected);
915         if (ui->stop_btn->isEnabled()) {  // Playing.
916                 midi_mapper.set_play_enabled(MIDIMapper::On);
917         } else if (any_selected) {
918                 midi_mapper.set_play_enabled(MIDIMapper::Blinking);
919         } else {
920                 midi_mapper.set_play_enabled(MIDIMapper::Off);
921         }
922
923         if (!any_selected) {
924                 set_output_status("paused");
925         } else {
926                 vector<ClipWithID> clips;
927                 for (size_t row = selected->selectedRows().front().row(); row < playlist_clips->size(); ++row) {
928                         clips.emplace_back(*playlist_clips->clip_with_id(row));
929                 }
930                 double remaining = compute_total_time(clips);
931                 set_output_status(format_duration(remaining) + " ready");
932         }
933 }
934
935 void MainWindow::clip_list_selection_changed(const QModelIndex &current, const QModelIndex &previous)
936 {
937         int camera_selected = -1;
938         if (cliplist_clips->is_camera_column(current.column())) {
939                 camera_selected = current.column() - int(ClipList::Column::CAMERA_1);
940
941                 // See the comment on hidden_jog_column.
942                 if (current.row() != previous.row()) {
943                         hidden_jog_column = -1;
944                 } else if (hidden_jog_column == -1) {
945                         hidden_jog_column = previous.column();
946                 }
947         } else {
948                 hidden_jog_column = -1;
949         }
950         highlight_camera_input(camera_selected);
951         enable_or_disable_queue_button();
952 }
953
954 void MainWindow::report_disk_space(off_t free_bytes, double estimated_seconds_left)
955 {
956         char time_str[256];
957         if (estimated_seconds_left < 60.0) {
958                 strcpy(time_str, "<font color=\"red\">Less than a minute</font>");
959         } else if (estimated_seconds_left < 1800.0) {  // Less than half an hour: Xm Ys (red).
960                 int s = lrintf(estimated_seconds_left);
961                 int m = s / 60;
962                 s %= 60;
963                 snprintf(time_str, sizeof(time_str), "<font color=\"red\">%dm %ds</font>", m, s);
964         } else if (estimated_seconds_left < 3600.0) {  // Less than an hour: Xm.
965                 int m = lrintf(estimated_seconds_left / 60.0);
966                 snprintf(time_str, sizeof(time_str), "%dm", m);
967         } else if (estimated_seconds_left < 36000.0) {  // Less than ten hours: Xh Ym.
968                 int m = lrintf(estimated_seconds_left / 60.0);
969                 int h = m / 60;
970                 m %= 60;
971                 snprintf(time_str, sizeof(time_str), "%dh %dm", h, m);
972         } else {  // More than ten hours: Xh.
973                 int h = lrintf(estimated_seconds_left / 3600.0);
974                 snprintf(time_str, sizeof(time_str), "%dh", h);
975         }
976         char buf[256];
977         snprintf(buf, sizeof(buf), "Disk free: %'.0f MB (approx. %s)", free_bytes / 1048576.0, time_str);
978
979         std::string label = buf;
980
981         post_to_main_thread([this, label] {
982                 disk_free_label->setText(QString::fromStdString(label));
983                 ui->menuBar->setCornerWidget(disk_free_label);  // Need to set this again for the sizing to get right.
984         });
985 }
986
987 void MainWindow::midi_mapping_triggered()
988 {
989         MIDIMappingDialog(&midi_mapper).exec();
990 }
991
992 void MainWindow::exit_triggered()
993 {
994         close();
995 }
996
997 void MainWindow::export_cliplist_clip_multitrack_triggered()
998 {
999         QItemSelectionModel *selected = ui->clip_list->selectionModel();
1000         if (!selected->hasSelection()) {
1001                 QMessageBox msgbox;
1002                 msgbox.setText("No clip selected in the clip list. Select one and try exporting again.");
1003                 msgbox.exec();
1004                 return;
1005         }
1006
1007         QModelIndex index = selected->currentIndex();
1008         Clip clip = *cliplist_clips->clip(index.row());
1009         QString filename = QFileDialog::getSaveFileName(this,
1010                 "Export multitrack clip", QString(), tr("Matroska video files (*.mkv)"));
1011         if (filename.isNull()) {
1012                 // Cancel.
1013                 return;
1014         }
1015         if (!filename.endsWith(".mkv")) {
1016                 filename += ".mkv";
1017         }
1018         export_multitrack_clip(filename.toStdString(), clip);
1019 }
1020
1021 void MainWindow::export_playlist_clip_interpolated_triggered()
1022 {
1023         QItemSelectionModel *selected = ui->playlist->selectionModel();
1024         if (!selected->hasSelection()) {
1025                 QMessageBox msgbox;
1026                 msgbox.setText("No clip selected in the playlist. Select one and try exporting again.");
1027                 msgbox.exec();
1028                 return;
1029         }
1030
1031         QString filename = QFileDialog::getSaveFileName(this,
1032                 "Export interpolated clip", QString(), tr("Matroska video files (*.mkv)"));
1033         if (filename.isNull()) {
1034                 // Cancel.
1035                 return;
1036         }
1037         if (!filename.endsWith(".mkv")) {
1038                 filename += ".mkv";
1039         }
1040
1041         vector<Clip> clips;
1042         QModelIndexList rows = selected->selectedRows();
1043         for (QModelIndex index : rows) {
1044                 clips.push_back(*playlist_clips->clip(index.row()));
1045         }
1046         export_interpolated_clip(filename.toStdString(), clips);
1047 }
1048
1049 void MainWindow::manual_triggered()
1050 {
1051         if (!QDesktopServices::openUrl(QUrl("https://nageru.sesse.net/doc/"))) {
1052                 QMessageBox msgbox;
1053                 msgbox.setText("Could not launch manual in web browser.\nPlease see https://nageru.sesse.net/doc/ manually.");
1054                 msgbox.exec();
1055         }
1056 }
1057
1058 void MainWindow::about_triggered()
1059 {
1060         AboutDialog("Futatabi", "Multicamera slow motion video server").exec();
1061 }
1062
1063 void MainWindow::undo_triggered()
1064 {
1065         // Finish any deferred action.
1066         if (defer_timeout->isActive()) {
1067                 defer_timeout->stop();
1068                 state_changed(deferred_state);
1069         }
1070
1071         StateProto redo_state;
1072         *redo_state.mutable_clip_list() = cliplist_clips->serialize();
1073         *redo_state.mutable_play_list() = playlist_clips->serialize();
1074         redo_stack.push_back(std::move(redo_state));
1075         ui->redo_action->setEnabled(true);
1076
1077         assert(undo_stack.size() > 1);
1078
1079         // Pop off the current state, which is always at the top of the stack.
1080         undo_stack.pop_back();
1081
1082         StateProto state = undo_stack.back();
1083         ui->undo_action->setEnabled(undo_stack.size() > 1);
1084
1085         replace_model(ui->clip_list, &cliplist_clips, new ClipList(state.clip_list()));
1086         replace_model(ui->playlist, &playlist_clips, new PlayList(state.play_list()));
1087
1088         db.store_state(state);
1089 }
1090
1091 void MainWindow::redo_triggered()
1092 {
1093         assert(!redo_stack.empty());
1094
1095         ui->undo_action->setEnabled(true);
1096         ui->redo_action->setEnabled(true);
1097
1098         undo_stack.push_back(std::move(redo_stack.back()));
1099         redo_stack.pop_back();
1100         ui->undo_action->setEnabled(true);
1101         ui->redo_action->setEnabled(!redo_stack.empty());
1102
1103         const StateProto &state = undo_stack.back();
1104         replace_model(ui->clip_list, &cliplist_clips, new ClipList(state.clip_list()));
1105         replace_model(ui->playlist, &playlist_clips, new PlayList(state.play_list()));
1106
1107         db.store_state(state);
1108 }
1109
1110 void MainWindow::quality_toggled(int quality, bool checked)
1111 {
1112         if (!checked) {
1113                 return;
1114         }
1115         global_flags.interpolation_quality = quality;
1116         if (quality != 0 &&  // Turning interpolation off is always possible.
1117             quality != flow_initialized_interpolation_quality) {
1118                 QMessageBox msgbox;
1119                 msgbox.setText(QString::fromStdString(
1120                         "The interpolation quality for the main output cannot be changed at runtime, "
1121                         "except being turned completely off; it will take effect for exported files "
1122                         "only until next restart. The live output quality thus remains at " +
1123                         to_string(flow_initialized_interpolation_quality) + "."));
1124                 msgbox.exec();
1125         }
1126
1127         save_settings();
1128 }
1129
1130 void MainWindow::padding_toggled(double seconds, bool checked)
1131 {
1132         if (!checked) {
1133                 return;
1134         }
1135         global_flags.cue_point_padding_seconds = seconds;
1136         save_settings();
1137 }
1138
1139 void MainWindow::highlight_camera_input(int stream_idx)
1140 {
1141         for (unsigned i = 0; i < num_cameras; ++i) {
1142                 if (unsigned(stream_idx) == i) {
1143                         displays[i].frame->setStyleSheet("background: rgb(0,255,0)");
1144                 } else {
1145                         displays[i].frame->setStyleSheet("");
1146                 }
1147         }
1148         midi_mapper.highlight_camera_input(stream_idx);
1149 }
1150
1151 void MainWindow::enable_or_disable_preview_button()
1152 {
1153         // Follows the logic in preview_clicked().
1154
1155         if (ui->playlist->hasFocus()) {
1156                 // Allow the playlist as preview iff it has focus and something is selected.
1157                 // TODO: Is this part really relevant?
1158                 QItemSelectionModel *selected = ui->playlist->selectionModel();
1159                 if (selected->hasSelection()) {
1160                         ui->preview_btn->setEnabled(true);
1161                         midi_mapper.set_preview_enabled(preview_playing ? MIDIMapper::On : MIDIMapper::Blinking);
1162                         return;
1163                 }
1164         }
1165
1166         // TODO: Perhaps only enable this if something is actually selected.
1167         ui->preview_btn->setEnabled(!cliplist_clips->empty());
1168         if (preview_playing) {
1169                 midi_mapper.set_preview_enabled(MIDIMapper::On);
1170         } else {
1171                 midi_mapper.set_preview_enabled(cliplist_clips->empty() ? MIDIMapper::Off : MIDIMapper::Blinking);
1172         }
1173 }
1174
1175 void MainWindow::enable_or_disable_queue_button()
1176 {
1177         // Follows the logic in queue_clicked().
1178         // TODO: Perhaps only enable this if something is actually selected.
1179
1180         bool enabled;
1181
1182         if (cliplist_clips->empty()) {
1183                 enabled = false;
1184         } else {
1185                 QItemSelectionModel *selected = ui->clip_list->selectionModel();
1186                 if (!selected->hasSelection()) {
1187                         Clip clip = *cliplist_clips->back();
1188                         enabled = clip.pts_out != -1;
1189                 } else {
1190                         QModelIndex index = selected->currentIndex();
1191                         Clip clip = *cliplist_clips->clip(index.row());
1192                         enabled = clip.pts_out != -1;
1193                 }
1194         }
1195
1196         ui->queue_btn->setEnabled(enabled);
1197         midi_mapper.set_queue_enabled(enabled);
1198 }
1199
1200 void MainWindow::set_output_status(const string &status)
1201 {
1202         ui->live_label->setText(QString::fromStdString("Current output (" + status + ")"));
1203         if (live_player != nullptr) {
1204                 live_player->set_pause_status(status);
1205         }
1206
1207         lock_guard<mutex> lock(queue_status_mu);
1208         queue_status = status;
1209 }
1210
1211 pair<string, string> MainWindow::get_queue_status() const
1212 {
1213         lock_guard<mutex> lock(queue_status_mu);
1214         return { queue_status, "text/plain" };
1215 }
1216
1217 void MainWindow::display_frame(unsigned stream_idx, const FrameOnDisk &frame)
1218 {
1219         if (stream_idx >= MAX_STREAMS) {
1220                 fprintf(stderr, "WARNING: Ignoring too-high stream index %u.\n", stream_idx);
1221                 return;
1222         }
1223         if (stream_idx >= num_cameras) {
1224                 post_to_main_thread_and_wait([this, stream_idx] {
1225                         num_cameras = stream_idx + 1;
1226                         change_num_cameras();
1227                 });
1228         }
1229         displays[stream_idx].display->setFrame(stream_idx, frame);
1230 }
1231
1232 void MainWindow::preview()
1233 {
1234         post_to_main_thread([this] {
1235                 preview_clicked();
1236         });
1237 }
1238
1239 void MainWindow::queue()
1240 {
1241         post_to_main_thread([this] {
1242                 queue_clicked();
1243         });
1244 }
1245
1246 void MainWindow::play()
1247 {
1248         post_to_main_thread([this] {
1249                 play_clicked();
1250         });
1251 }
1252
1253 void MainWindow::toggle_lock()
1254 {
1255         post_to_main_thread([this] {
1256                 ui->speed_lock_btn->setChecked(!ui->speed_lock_btn->isChecked());
1257                 speed_lock_clicked();
1258         });
1259 }
1260
1261 void MainWindow::jog(int delta)
1262 {
1263         post_to_main_thread([this, delta] {
1264                 int64_t pts_delta = delta * (TIMEBASE / 60);  // One click = frame at 60 fps.
1265                 if (ui->playlist->hasFocus()) {
1266                         QModelIndex selected = ui->playlist->selectionModel()->currentIndex();
1267                         if (selected.column() != -1 && selected.row() != -1) {
1268                                 jog_internal(JOG_PLAYLIST, selected.row(), selected.column(), /*stream_idx=*/-1, pts_delta);
1269                         }
1270                 } else if (ui->clip_list->hasFocus()) {
1271                         QModelIndex selected = ui->clip_list->selectionModel()->currentIndex();
1272                         if (cliplist_clips->is_camera_column(selected.column()) &&
1273                             hidden_jog_column != -1) {
1274                                 // See the definition on hidden_jog_column.
1275                                 selected = selected.sibling(selected.row(), hidden_jog_column);
1276                                 ui->clip_list->selectionModel()->setCurrentIndex(selected, QItemSelectionModel::ClearAndSelect);
1277                                 hidden_jog_column = -1;
1278                         }
1279                         if (selected.column() != -1 && selected.row() != -1) {
1280                                 jog_internal(JOG_CLIP_LIST, selected.row(), selected.column(), ui->preview_display->get_stream_idx(), pts_delta);
1281                         }
1282                 }
1283         });
1284 }
1285
1286 void MainWindow::switch_camera(unsigned camera_idx)
1287 {
1288         post_to_main_thread([this, camera_idx] {
1289                 if (camera_idx < num_cameras) {  // TODO: Also make this change a highlighted clip?
1290                         preview_angle_clicked(camera_idx);
1291                 }
1292         });
1293 }
1294
1295 void MainWindow::set_master_speed(float speed)
1296 {
1297         speed = min(max(speed, 0.1f), 2.0f);
1298
1299         post_to_main_thread([this, speed] {
1300                 if (ui->speed_lock_btn->isChecked()) {
1301                         midi_mapper.set_locked(MIDIMapper::Blinking);
1302                         lock_blink_timeout->start(1000);
1303                         return;
1304                 }
1305
1306                 int percent = lrintf(speed * 100.0f);
1307                 ui->speed_slider->blockSignals(true);
1308                 ui->speed_slider->setValue(percent);
1309                 ui->speed_slider->blockSignals(false);
1310                 ui->speed_lock_btn->setText(QString::fromStdString(" " + to_string(percent) + "%"));
1311
1312                 live_player->set_master_speed(speed);
1313                 midi_mapper.set_speed_light(speed);
1314         });
1315 }
1316
1317 void MainWindow::cue_in()
1318 {
1319         post_to_main_thread([this] { cue_in_clicked(); });
1320 }
1321
1322 void MainWindow::cue_out()
1323 {
1324         post_to_main_thread([this] { cue_out_clicked(); });
1325 }
1326
1327 template<class Model>
1328 void MainWindow::replace_model(QTableView *view, Model **model, Model *new_model)
1329 {
1330         QItemSelectionModel *old_selection_model = view->selectionModel();
1331         view->setModel(new_model);
1332         delete *model;
1333         delete old_selection_model;
1334         *model = new_model;
1335         connect(new_model, &Model::any_content_changed, this, &MainWindow::content_changed);
1336 }
1337
1338 void MainWindow::start_tally()
1339 {
1340         http_reply = http.get(QNetworkRequest(QString::fromStdString(global_flags.tally_url)));
1341         connect(http_reply, &QNetworkReply::finished, this, &MainWindow::tally_received);
1342 }
1343
1344 void MainWindow::tally_received()
1345 {
1346         unsigned time_to_next_tally_ms;
1347         if (http_reply->error()) {
1348                 fprintf(stderr, "HTTP get of '%s' failed: %s\n", global_flags.tally_url.c_str(),
1349                         http_reply->errorString().toStdString().c_str());
1350                 ui->live_frame->setStyleSheet("");
1351                 time_to_next_tally_ms = 1000;
1352         } else {
1353                 string contents = http_reply->readAll().toStdString();
1354                 ui->live_frame->setStyleSheet(QString::fromStdString("background: " + contents));
1355                 time_to_next_tally_ms = 100;
1356         }
1357         http_reply->deleteLater();
1358         http_reply = nullptr;
1359
1360         QTimer::singleShot(time_to_next_tally_ms, this, &MainWindow::start_tally);
1361 }