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