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