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