]> git.sesse.net Git - nageru/blob - futatabi/mainwindow.cpp
Fix a Clang warning.
[nageru] / futatabi / mainwindow.cpp
1 #include "mainwindow.h"
2
3 #include "shared/aboutdialog.h"
4 #include "clip_list.h"
5 #include "export.h"
6 #include "shared/disk_space_estimator.h"
7 #include "flags.h"
8 #include "frame_on_disk.h"
9 #include "player.h"
10 #include "shared/post_to_main_thread.h"
11 #include "shared/timebase.h"
12 #include "ui_mainwindow.h"
13
14 #include <QDesktopServices>
15 #include <QFileDialog>
16 #include <QMessageBox>
17 #include <QMouseEvent>
18 #include <QShortcut>
19 #include <QTimer>
20 #include <QWheelEvent>
21 #include <future>
22 #include <sqlite3.h>
23 #include <string>
24 #include <vector>
25
26 using namespace std;
27 using namespace std::placeholders;
28
29 MainWindow *global_mainwindow = nullptr;
30 static ClipList *cliplist_clips;
31 static PlayList *playlist_clips;
32
33 extern int64_t current_pts;
34
35 MainWindow::MainWindow()
36         : ui(new Ui::MainWindow),
37           db(global_flags.working_directory + "/futatabi.db")
38 {
39         global_mainwindow = this;
40         ui->setupUi(this);
41
42         // Load settings from database if needed.
43         if (!global_flags.interpolation_quality_set) {
44                 SettingsProto settings = db.get_settings();
45                 if (settings.interpolation_quality() != 0) {
46                         global_flags.interpolation_quality = settings.interpolation_quality() - 1;
47                 }
48         }
49         if (global_flags.interpolation_quality == 0) {
50                 // Allocate something just for simplicity; we won't be using it
51                 // unless the user changes runtime, in which case 1 is fine.
52                 flow_initialized_interpolation_quality = 1;
53         } else {
54                 flow_initialized_interpolation_quality = global_flags.interpolation_quality;
55         }
56         save_settings();
57
58         // The menus.
59         connect(ui->exit_action, &QAction::triggered, this, &MainWindow::exit_triggered);
60         connect(ui->export_cliplist_clip_multitrack_action, &QAction::triggered, this, &MainWindow::export_cliplist_clip_multitrack_triggered);
61         connect(ui->export_playlist_clip_interpolated_action, &QAction::triggered, this, &MainWindow::export_playlist_clip_interpolated_triggered);
62         connect(ui->manual_action, &QAction::triggered, this, &MainWindow::manual_triggered);
63         connect(ui->about_action, &QAction::triggered, this, &MainWindow::about_triggered);
64         connect(ui->undo_action, &QAction::triggered, this, &MainWindow::undo_triggered);
65         connect(ui->redo_action, &QAction::triggered, this, &MainWindow::redo_triggered);
66         ui->undo_action->setEnabled(false);
67         ui->redo_action->setEnabled(false);
68
69         // The quality group.
70         QActionGroup *quality_group = new QActionGroup(ui->interpolation_menu);
71         quality_group->addAction(ui->quality_0_action);
72         quality_group->addAction(ui->quality_1_action);
73         quality_group->addAction(ui->quality_2_action);
74         quality_group->addAction(ui->quality_3_action);
75         quality_group->addAction(ui->quality_4_action);
76         if (global_flags.interpolation_quality == 0) {
77                 ui->quality_0_action->setChecked(true);
78         } else if (global_flags.interpolation_quality == 1) {
79                 ui->quality_1_action->setChecked(true);
80         } else if (global_flags.interpolation_quality == 2) {
81                 ui->quality_2_action->setChecked(true);
82         } else if (global_flags.interpolation_quality == 3) {
83                 ui->quality_3_action->setChecked(true);
84         } else if (global_flags.interpolation_quality == 4) {
85                 ui->quality_4_action->setChecked(true);
86         } else {
87                 assert(false);
88         }
89         connect(ui->quality_0_action, &QAction::toggled, bind(&MainWindow::quality_toggled, this, 0, _1));
90         connect(ui->quality_1_action, &QAction::toggled, bind(&MainWindow::quality_toggled, this, 1, _1));
91         connect(ui->quality_2_action, &QAction::toggled, bind(&MainWindow::quality_toggled, this, 2, _1));
92         connect(ui->quality_3_action, &QAction::toggled, bind(&MainWindow::quality_toggled, this, 3, _1));
93         connect(ui->quality_4_action, &QAction::toggled, bind(&MainWindow::quality_toggled, this, 4, _1));
94
95         global_disk_space_estimator = new DiskSpaceEstimator(bind(&MainWindow::report_disk_space, this, _1, _2));
96         disk_free_label = new QLabel(this);
97         disk_free_label->setStyleSheet("QLabel {padding-right: 5px;}");
98         ui->menuBar->setCornerWidget(disk_free_label);
99
100         StateProto state = db.get_state();
101         undo_stack.push_back(state);  // The undo stack always has the current state on top.
102
103         cliplist_clips = new ClipList(state.clip_list());
104         ui->clip_list->setModel(cliplist_clips);
105         connect(cliplist_clips, &ClipList::any_content_changed, this, &MainWindow::content_changed);
106
107         playlist_clips = new PlayList(state.play_list());
108         ui->playlist->setModel(playlist_clips);
109         connect(playlist_clips, &PlayList::any_content_changed, this, &MainWindow::content_changed);
110
111         // For un-highlighting when we lose focus.
112         ui->clip_list->installEventFilter(this);
113
114         // For scrubbing in the pts columns.
115         ui->clip_list->viewport()->installEventFilter(this);
116         ui->playlist->viewport()->installEventFilter(this);
117
118         QShortcut *cue_in = new QShortcut(QKeySequence(Qt::Key_A), this);
119         connect(cue_in, &QShortcut::activated, ui->cue_in_btn, &QPushButton::click);
120         connect(ui->cue_in_btn, &QPushButton::clicked, this, &MainWindow::cue_in_clicked);
121
122         QShortcut *cue_out = new QShortcut(QKeySequence(Qt::Key_S), this);
123         connect(cue_out, &QShortcut::activated, ui->cue_out_btn, &QPushButton::click);
124         connect(ui->cue_out_btn, &QPushButton::clicked, this, &MainWindow::cue_out_clicked);
125
126         QShortcut *queue = new QShortcut(QKeySequence(Qt::Key_Q), this);
127         connect(queue, &QShortcut::activated, ui->queue_btn, &QPushButton::click);
128         connect(ui->queue_btn, &QPushButton::clicked, this, &MainWindow::queue_clicked);
129
130         QShortcut *preview = new QShortcut(QKeySequence(Qt::Key_W), this);
131         connect(preview, &QShortcut::activated, ui->preview_btn, &QPushButton::click);
132         connect(ui->preview_btn, &QPushButton::clicked, this, &MainWindow::preview_clicked);
133
134         QShortcut *play = new QShortcut(QKeySequence(Qt::Key_Space), this);
135         connect(play, &QShortcut::activated, ui->play_btn, &QPushButton::click);
136         connect(ui->play_btn, &QPushButton::clicked, this, &MainWindow::play_clicked);
137
138         connect(ui->stop_btn, &QPushButton::clicked, this, &MainWindow::stop_clicked);
139         ui->stop_btn->setEnabled(false);
140
141         QShortcut *preview_1 = new QShortcut(QKeySequence(Qt::Key_1), this);
142         connect(preview_1, &QShortcut::activated, ui->preview_1_btn, &QPushButton::click);
143         connect(ui->input1_display, &JPEGFrameView::clicked, ui->preview_1_btn, &QPushButton::click);
144         connect(ui->preview_1_btn, &QPushButton::clicked, [this]{ preview_angle_clicked(0); });
145         ui->input1_display->set_overlay("1");
146
147         QShortcut *preview_2 = new QShortcut(QKeySequence(Qt::Key_2), this);
148         connect(preview_2, &QShortcut::activated, ui->preview_2_btn, &QPushButton::click);
149         connect(ui->input2_display, &JPEGFrameView::clicked, ui->preview_2_btn, &QPushButton::click);
150         connect(ui->preview_2_btn, &QPushButton::clicked, [this]{ preview_angle_clicked(1); });
151         ui->input2_display->set_overlay("2");
152
153         QShortcut *preview_3 = new QShortcut(QKeySequence(Qt::Key_3), this);
154         connect(preview_3, &QShortcut::activated, ui->preview_3_btn, &QPushButton::click);
155         connect(ui->input3_display, &JPEGFrameView::clicked, ui->preview_3_btn, &QPushButton::click);
156         connect(ui->preview_3_btn, &QPushButton::clicked, [this]{ preview_angle_clicked(2); });
157         ui->input3_display->set_overlay("3");
158
159         QShortcut *preview_4 = new QShortcut(QKeySequence(Qt::Key_4), this);
160         connect(preview_4, &QShortcut::activated, ui->preview_4_btn, &QPushButton::click);
161         connect(ui->input4_display, &JPEGFrameView::clicked, ui->preview_4_btn, &QPushButton::click);
162         connect(ui->preview_4_btn, &QPushButton::clicked, [this]{ preview_angle_clicked(3); });
163         ui->input4_display->set_overlay("4");
164
165         connect(ui->playlist_duplicate_btn, &QPushButton::clicked, this, &MainWindow::playlist_duplicate);
166
167         connect(ui->playlist_remove_btn, &QPushButton::clicked, this, &MainWindow::playlist_remove);
168         QShortcut *delete_key = new QShortcut(QKeySequence(Qt::Key_Delete), ui->playlist);
169         connect(delete_key, &QShortcut::activated, [this] {
170                 if (ui->playlist->hasFocus()) {
171                         playlist_remove();
172                 }
173         });
174
175         // TODO: support drag-and-drop.
176         connect(ui->playlist_move_up_btn, &QPushButton::clicked, [this]{ playlist_move(-1); });
177         connect(ui->playlist_move_down_btn, &QPushButton::clicked, [this]{ playlist_move(1); });
178
179         connect(ui->playlist->selectionModel(), &QItemSelectionModel::selectionChanged,
180                 this, &MainWindow::playlist_selection_changed);
181         playlist_selection_changed();  // First time set-up.
182
183         preview_player.reset(new Player(ui->preview_display, Player::NO_STREAM_OUTPUT));
184         live_player.reset(new Player(ui->live_display, Player::HTTPD_STREAM_OUTPUT));
185         live_player->set_done_callback([this]{
186                 post_to_main_thread([this]{
187                         live_player_clip_done();
188                 });
189         });
190         live_player->set_next_clip_callback(bind(&MainWindow::live_player_get_next_clip, this));
191         live_player->set_progress_callback([this](const map<size_t, double> &progress) {
192                 post_to_main_thread([this, progress] {
193                         live_player_clip_progress(progress);
194                 });
195         });
196         set_output_status("paused");
197
198         defer_timeout = new QTimer(this);
199         defer_timeout->setSingleShot(true);
200         connect(defer_timeout, &QTimer::timeout, this, &MainWindow::defer_timer_expired);
201         ui->undo_action->setEnabled(true);
202
203         connect(ui->clip_list->selectionModel(), &QItemSelectionModel::currentChanged,
204                 this, &MainWindow::clip_list_selection_changed);
205 }
206
207 MainWindow::~MainWindow()
208 {
209         // Empty so that we can forward-declare Player in the .h file.
210 }
211
212 void MainWindow::cue_in_clicked()
213 {
214         if (!cliplist_clips->empty() && cliplist_clips->back()->pts_out < 0) {
215                 cliplist_clips->mutable_back()->pts_in = current_pts;
216                 return;
217         }
218         Clip clip;
219         clip.pts_in = current_pts;
220         cliplist_clips->add_clip(clip);
221         playlist_selection_changed();
222         ui->clip_list->scrollToBottom();
223 }
224
225 void MainWindow::cue_out_clicked()
226 {
227         if (!cliplist_clips->empty()) {
228                 cliplist_clips->mutable_back()->pts_out = current_pts;
229                 // TODO: select the row in the clip list?
230         }
231 }
232
233 void MainWindow::queue_clicked()
234 {
235         if (cliplist_clips->empty()) {
236                 return;
237         }
238
239         QItemSelectionModel *selected = ui->clip_list->selectionModel();
240         if (!selected->hasSelection()) {
241                 Clip clip = *cliplist_clips->back();
242                 clip.stream_idx = 0;
243                 if (clip.pts_out != -1) {
244                         playlist_clips->add_clip(clip);
245                         playlist_selection_changed();
246                         ui->playlist->scrollToBottom();
247                 }
248                 return;
249         }
250
251         QModelIndex index = selected->currentIndex();
252         Clip clip = *cliplist_clips->clip(index.row());
253         if (index.column() >= int(ClipList::Column::CAMERA_1) &&
254             index.column() <= int(ClipList::Column::CAMERA_4)) {
255                 clip.stream_idx = index.column() - int(ClipList::Column::CAMERA_1);
256         } else {
257                 clip.stream_idx = ui->preview_display->get_stream_idx();
258         }
259
260         if (clip.pts_out != -1) {
261                 playlist_clips->add_clip(clip);
262                 playlist_selection_changed();
263                 ui->playlist->scrollToBottom();
264                 if (!ui->playlist->selectionModel()->hasSelection()) {
265                         // TODO: Figure out why this doesn't always seem to actually select the row.
266                         QModelIndex bottom = playlist_clips->index(playlist_clips->size() - 1, 0);
267                         ui->playlist->setCurrentIndex(bottom);
268                 }
269         }
270 }
271
272 void MainWindow::preview_clicked()
273 {
274         if (ui->playlist->hasFocus()) {
275                 // Allow the playlist as preview iff it has focus and something is selected.
276                 QItemSelectionModel *selected = ui->playlist->selectionModel();
277                 if (selected->hasSelection()) {
278                         QModelIndex index = selected->currentIndex();
279                         const Clip &clip = *playlist_clips->clip(index.row());
280                         preview_player->play_clip(clip, index.row(), clip.stream_idx);
281                         return;
282                 }
283         }
284
285         if (cliplist_clips->empty())
286                 return;
287
288         QItemSelectionModel *selected = ui->clip_list->selectionModel();
289         if (!selected->hasSelection()) {
290                 preview_player->play_clip(*cliplist_clips->back(), cliplist_clips->size() - 1, 0);
291                 return;
292         }
293
294         QModelIndex index = selected->currentIndex();
295         unsigned stream_idx;
296         if (index.column() >= int(ClipList::Column::CAMERA_1) &&
297             index.column() <= int(ClipList::Column::CAMERA_4)) {
298                 stream_idx = index.column() - int(ClipList::Column::CAMERA_1);
299         } else {
300                 stream_idx = ui->preview_display->get_stream_idx();
301         }
302         preview_player->play_clip(*cliplist_clips->clip(index.row()), index.row(), stream_idx);
303 }
304
305 void MainWindow::preview_angle_clicked(unsigned stream_idx)
306 {
307         preview_player->override_angle(stream_idx);
308
309         // Change the selection if we were previewing a clip from the clip list.
310         // (The only other thing we could be showing is a pts scrub, and if so,
311         // that would be selected.)
312         QItemSelectionModel *selected = ui->clip_list->selectionModel();
313         if (selected->hasSelection()) {
314                 QModelIndex cell = selected->selectedIndexes()[0];
315                 int column = int(ClipList::Column::CAMERA_1) + stream_idx;
316                 selected->setCurrentIndex(cell.sibling(cell.row(), column), QItemSelectionModel::ClearAndSelect);
317         }
318 }
319
320 void MainWindow::playlist_duplicate()
321 {
322         QItemSelectionModel *selected = ui->playlist->selectionModel();
323         if (!selected->hasSelection()) {
324                 // Should have been grayed out, but OK.
325                 return;
326         }
327         QModelIndexList rows = selected->selectedRows();
328         int first = rows.front().row(), last = rows.back().row();
329         playlist_clips->duplicate_clips(first, last);
330         playlist_selection_changed();
331 }
332
333 void MainWindow::playlist_remove()
334 {
335         QItemSelectionModel *selected = ui->playlist->selectionModel();
336         if (!selected->hasSelection()) {
337                 // Should have been grayed out, but OK.
338                 return;
339         }
340         QModelIndexList rows = selected->selectedRows();
341         int first = rows.front().row(), last = rows.back().row();
342         playlist_clips->erase_clips(first, last);
343
344         // TODO: select the next one in the list?
345
346         playlist_selection_changed();
347 }
348
349 void MainWindow::playlist_move(int delta)
350 {
351         QItemSelectionModel *selected = ui->playlist->selectionModel();
352         if (!selected->hasSelection()) {
353                 // Should have been grayed out, but OK.
354                 return;
355         }
356
357         QModelIndexList rows = selected->selectedRows();
358         int first = rows.front().row(), last = rows.back().row();
359         if ((delta == -1 && first == 0) ||
360             (delta == 1 && size_t(last) == playlist_clips->size() - 1)) {
361                 // Should have been grayed out, but OK.
362                 return;
363         }
364
365         playlist_clips->move_clips(first, last, delta);
366         playlist_selection_changed();
367 }
368
369 void MainWindow::defer_timer_expired()
370 {
371         state_changed(deferred_state);
372 }
373
374 void MainWindow::content_changed()
375 {
376         if (defer_timeout->isActive() &&
377             (!currently_deferring_model_changes || deferred_change_id != current_change_id)) {
378                 // There's some deferred event waiting, but this event is unrelated.
379                 // So it's time to short-circuit that timer and do the work it wanted to do.
380                 defer_timeout->stop();
381                 state_changed(deferred_state);
382         }
383         StateProto state;
384         *state.mutable_clip_list() = cliplist_clips->serialize();
385         *state.mutable_play_list() = playlist_clips->serialize();
386         if (currently_deferring_model_changes) {
387                 deferred_change_id = current_change_id;
388                 deferred_state = std::move(state);
389                 defer_timeout->start(200);
390                 return;
391         }
392         state_changed(state);
393 }
394
395 void MainWindow::state_changed(const StateProto &state)
396 {
397         db.store_state(state);
398
399         redo_stack.clear();
400         ui->redo_action->setEnabled(false);
401
402         undo_stack.push_back(state);
403         ui->undo_action->setEnabled(undo_stack.size() > 1);
404
405         // Make sure it doesn't grow without bounds.
406         while (undo_stack.size() >= 100) {
407                 undo_stack.pop_front();
408         }
409 }
410
411 void MainWindow::save_settings()
412 {
413         SettingsProto settings;
414         settings.set_interpolation_quality(global_flags.interpolation_quality + 1);
415         db.store_settings(settings);
416 }
417
418 void MainWindow::play_clicked()
419 {
420         if (playlist_clips->empty())
421                 return;
422
423         QItemSelectionModel *selected = ui->playlist->selectionModel();
424         int row;
425         if (!selected->hasSelection()) {
426                 row = 0;
427         } else {
428                 row = selected->selectedRows(0)[0].row();
429         }
430
431         const Clip &clip = *playlist_clips->clip(row);
432         live_player->play_clip(clip, row, clip.stream_idx);
433         playlist_clips->set_progress({{ row, 0.0f }});
434         playlist_clips->set_currently_playing(row, 0.0f);
435         playlist_selection_changed();
436
437         ui->stop_btn->setEnabled(true);
438 }
439
440 void MainWindow::stop_clicked()
441 {
442         Clip fake_clip;
443         fake_clip.pts_in = 0;
444         fake_clip.pts_out = 0;
445         size_t last_row = playlist_clips->size() - 1;
446         playlist_clips->set_currently_playing(last_row, 0.0f);
447         live_player->play_clip(fake_clip, last_row, 0);
448 }
449
450 void MainWindow::live_player_clip_done()
451 {
452         int row = playlist_clips->get_currently_playing();
453         if (row == -1 || row == int(playlist_clips->size()) - 1) {
454                 set_output_status("paused");
455                 playlist_clips->set_progress({});
456                 playlist_clips->set_currently_playing(-1, 0.0f);
457         } else {
458                 playlist_clips->set_progress({{ row + 1, 0.0f }});
459                 playlist_clips->set_currently_playing(row + 1, 0.0f);
460         }
461         ui->stop_btn->setEnabled(false);
462 }
463
464 pair<Clip, size_t> MainWindow::live_player_get_next_clip()
465 {
466         // playlist_clips can only be accessed on the main thread.
467         // Hopefully, we won't have to wait too long for this to come back.
468         //
469         // TODO: If MainWindow is in the process of being destroyed and waiting
470         // for Player to shut down, we could have a deadlock here.
471         promise<pair<Clip, size_t>> clip_promise;
472         future<pair<Clip, size_t>> clip = clip_promise.get_future();
473         post_to_main_thread([&clip_promise] {
474                 int row = playlist_clips->get_currently_playing();
475                 if (row != -1 && row < int(playlist_clips->size()) - 1) {
476                         clip_promise.set_value(make_pair(*playlist_clips->clip(row + 1), row + 1));
477                 } else {
478                         clip_promise.set_value(make_pair(Clip(), 0));
479                 }
480         });
481         return clip.get();
482 }
483
484 static string format_duration(double t)
485 {
486         int t_ms = lrint(t * 1e3);
487
488         int ms = t_ms % 1000;
489         t_ms /= 1000;
490         int s = t_ms % 60;
491         t_ms /= 60;
492         int m = t_ms;
493
494         char buf[256];
495         snprintf(buf, sizeof(buf), "%d:%02d.%03d", m, s, ms);
496         return buf;
497 }
498
499 void MainWindow::live_player_clip_progress(const map<size_t, double> &progress)
500 {
501         playlist_clips->set_progress(progress);
502
503         vector<Clip> clips;
504         for (size_t row = 0; row < playlist_clips->size(); ++row) {
505                 clips.push_back(*playlist_clips->clip(row));
506         }
507         double remaining = compute_time_left(clips, progress);
508         set_output_status(format_duration(remaining) + " left");
509 }
510
511 void MainWindow::resizeEvent(QResizeEvent *event)
512 {
513         QMainWindow::resizeEvent(event);
514
515         // Ask for a relayout, but only after the event loop is done doing relayout
516         // on everything else.
517         QMetaObject::invokeMethod(this, "relayout", Qt::QueuedConnection);
518 }
519
520 void MainWindow::relayout()
521 {
522         ui->live_display->setMinimumWidth(ui->live_display->height() * 16 / 9);
523         ui->preview_display->setMinimumWidth(ui->preview_display->height() * 16 / 9);
524 }
525
526 void set_pts_in(int64_t pts, int64_t current_pts, ClipProxy &clip)
527 {
528         pts = std::max<int64_t>(pts, 0);
529         if (clip->pts_out == -1) {
530                 pts = std::min(pts, current_pts);
531         } else {
532                 pts = std::min(pts, clip->pts_out);
533         }
534         clip->pts_in = pts;
535 }
536
537 bool MainWindow::eventFilter(QObject *watched, QEvent *event)
538 {
539         constexpr int dead_zone_pixels = 3;  // To avoid that simple clicks get misinterpreted.
540         constexpr int camera_degrees_per_pixel = 15;  // One click of most mice.
541         int scrub_sensitivity = 100;  // pts units per pixel.
542         int wheel_sensitivity = 100;  // pts units per degree.
543
544         unsigned stream_idx = ui->preview_display->get_stream_idx();
545
546         if (watched == ui->clip_list) {
547                 if (event->type() == QEvent::FocusOut) {
548                         highlight_camera_input(-1);
549                 }
550                 return false;
551         }
552
553         if (event->type() != QEvent::Wheel) {
554                 last_mousewheel_camera_row = -1;
555         }
556
557         if (event->type() == QEvent::MouseButtonPress) {
558                 QMouseEvent *mouse = (QMouseEvent *)event;
559
560                 QTableView *destination;
561                 ScrubType type;
562
563                 if (watched == ui->clip_list->viewport()) {
564                         destination = ui->clip_list;
565                         type = SCRUBBING_CLIP_LIST;
566                 } else if (watched == ui->playlist->viewport()) {
567                         destination = ui->playlist;
568                         type = SCRUBBING_PLAYLIST;
569                 } else {
570                         return false;
571                 }
572                 int column = destination->columnAt(mouse->x());
573                 int row = destination->rowAt(mouse->y());
574                 if (column == -1 || row == -1)
575                         return false;
576
577                 if (type == SCRUBBING_CLIP_LIST) {
578                         if (ClipList::Column(column) == ClipList::Column::IN) {
579                                 scrub_pts_origin = cliplist_clips->clip(row)->pts_in;
580                                 preview_single_frame(scrub_pts_origin, stream_idx, FIRST_AT_OR_AFTER);
581                         } else if (ClipList::Column(column) == ClipList::Column::OUT) {
582                                 scrub_pts_origin = cliplist_clips->clip(row)->pts_out;
583                                 preview_single_frame(scrub_pts_origin, stream_idx, LAST_BEFORE);
584                         } else {
585                                 return false;
586                         }
587                 } else {
588                         if (PlayList::Column(column) == PlayList::Column::IN) {
589                                 scrub_pts_origin = playlist_clips->clip(row)->pts_in;
590                                 preview_single_frame(scrub_pts_origin, stream_idx, FIRST_AT_OR_AFTER);
591                         } else if (PlayList::Column(column) == PlayList::Column::OUT) {
592                                 scrub_pts_origin = playlist_clips->clip(row)->pts_out;
593                                 preview_single_frame(scrub_pts_origin, stream_idx, LAST_BEFORE);
594                         } else {
595                                 return false;
596                         }
597                 }
598
599                 scrubbing = true;
600                 scrub_row = row;
601                 scrub_column = column;
602                 scrub_x_origin = mouse->x();
603                 scrub_type = type;
604         } else if (event->type() == QEvent::MouseMove) {
605                 QMouseEvent *mouse = (QMouseEvent *)event;
606                 if (mouse->modifiers() & Qt::KeyboardModifier::ShiftModifier) {
607                         scrub_sensitivity *= 10;
608                         wheel_sensitivity *= 10;
609                 }
610                 if (mouse->modifiers() & Qt::KeyboardModifier::AltModifier) {  // Note: Shift + Alt cancel each other out.
611                         scrub_sensitivity /= 10;
612                         wheel_sensitivity /= 10;
613                 }
614                 if (scrubbing) {
615                         int offset = mouse->x() - scrub_x_origin;
616                         int adjusted_offset;
617                         if (offset >= dead_zone_pixels) {
618                                 adjusted_offset = offset - dead_zone_pixels;
619                         } else if (offset < -dead_zone_pixels) {
620                                 adjusted_offset = offset + dead_zone_pixels;
621                         } else {
622                                 adjusted_offset = 0;
623                         }
624
625                         int64_t pts = scrub_pts_origin + adjusted_offset * scrub_sensitivity;
626                         currently_deferring_model_changes = true;
627                         if (scrub_type == SCRUBBING_CLIP_LIST) {
628                                 ClipProxy clip = cliplist_clips->mutable_clip(scrub_row);
629                                 if (scrub_column == int(ClipList::Column::IN)) {
630                                         current_change_id = "cliplist:in:" + to_string(scrub_row);
631                                         set_pts_in(pts, current_pts, clip);
632                                         preview_single_frame(pts, stream_idx, FIRST_AT_OR_AFTER);
633                                 } else {
634                                         current_change_id = "cliplist:out" + to_string(scrub_row);
635                                         pts = std::max(pts, clip->pts_in);
636                                         pts = std::min(pts, current_pts);
637                                         clip->pts_out = pts;
638                                         preview_single_frame(pts, stream_idx, LAST_BEFORE);
639                                 }
640                         } else {
641                                 ClipProxy clip = playlist_clips->mutable_clip(scrub_row);
642                                 if (scrub_column == int(PlayList::Column::IN)) {
643                                         current_change_id = "playlist:in:" + to_string(scrub_row);
644                                         set_pts_in(pts, current_pts, clip);
645                                         preview_single_frame(pts, clip->stream_idx, FIRST_AT_OR_AFTER);
646                                 } else {
647                                         current_change_id = "playlist:out:" + to_string(scrub_row);
648                                         pts = std::max(pts, clip->pts_in);
649                                         pts = std::min(pts, current_pts);
650                                         clip->pts_out = pts;
651                                         preview_single_frame(pts, clip->stream_idx, LAST_BEFORE);
652                                 }
653                         }
654                         currently_deferring_model_changes = false;
655
656                         return true;  // Don't use this mouse movement for selecting things.
657                 }
658         } else if (event->type() == QEvent::Wheel) {
659                 QWheelEvent *wheel = (QWheelEvent *)event;
660                 int angle_delta = wheel->angleDelta().y();
661                 if (wheel->modifiers() & Qt::KeyboardModifier::ShiftModifier) {
662                         scrub_sensitivity *= 10;
663                         wheel_sensitivity *= 10;
664                 }
665                 if (wheel->modifiers() & Qt::KeyboardModifier::AltModifier) {  // Note: Shift + Alt cancel each other out.
666                         scrub_sensitivity /= 10;
667                         wheel_sensitivity /= 10;
668                         angle_delta = wheel->angleDelta().x();  // Qt ickiness.
669                 }
670
671                 QTableView *destination;
672                 int in_column, out_column, camera_column;
673                 if (watched == ui->clip_list->viewport()) {
674                         destination = ui->clip_list;
675                         in_column = int(ClipList::Column::IN);
676                         out_column = int(ClipList::Column::OUT);
677                         camera_column = -1;
678                         last_mousewheel_camera_row = -1;
679                 } else if (watched == ui->playlist->viewport()) {
680                         destination = ui->playlist;
681                         in_column = int(PlayList::Column::IN);
682                         out_column = int(PlayList::Column::OUT);
683                         camera_column = int(PlayList::Column::CAMERA);
684                 } else {
685                         last_mousewheel_camera_row = -1;
686                         return false;
687                 }
688                 int column = destination->columnAt(wheel->x());
689                 int row = destination->rowAt(wheel->y());
690                 if (column == -1 || row == -1) return false;
691
692                 // Only adjust pts with the wheel if the given row is selected.
693                 if (!destination->hasFocus() ||
694                     row != destination->selectionModel()->currentIndex().row()) {
695                         return false;
696                 }
697
698                 currently_deferring_model_changes = true;
699                 {
700                         current_change_id = (watched == ui->clip_list->viewport()) ? "cliplist:" : "playlist:";
701                         ClipProxy clip = (watched == ui->clip_list->viewport()) ?
702                                 cliplist_clips->mutable_clip(row) : playlist_clips->mutable_clip(row);
703                         if (watched == ui->playlist->viewport()) {
704                                 stream_idx = clip->stream_idx;
705                         }
706
707                         if (column != camera_column) {
708                                 last_mousewheel_camera_row = -1;
709                         }
710                         if (column == in_column) {
711                                 current_change_id += "in:" + to_string(row);
712                                 int64_t pts = clip->pts_in + angle_delta * wheel_sensitivity;
713                                 set_pts_in(pts, current_pts, clip);
714                                 preview_single_frame(pts, stream_idx, FIRST_AT_OR_AFTER);
715                         } else if (column == out_column) {
716                                 current_change_id += "out:" + to_string(row);
717                                 int64_t pts = clip->pts_out + angle_delta * wheel_sensitivity;
718                                 pts = std::max(pts, clip->pts_in);
719                                 pts = std::min(pts, current_pts);
720                                 clip->pts_out = pts;
721                                 preview_single_frame(pts, stream_idx, LAST_BEFORE);
722                         } else if (column == camera_column) {
723                                 current_change_id += "camera:" + to_string(row);
724                                 int angle_degrees = angle_delta;
725                                 if (last_mousewheel_camera_row == row) {
726                                         angle_degrees += leftover_angle_degrees;
727                                 }
728
729                                 int stream_idx = clip->stream_idx + angle_degrees / camera_degrees_per_pixel;
730                                 stream_idx = std::max(stream_idx, 0);
731                                 stream_idx = std::min(stream_idx, NUM_CAMERAS - 1);
732                                 clip->stream_idx = stream_idx;
733
734                                 last_mousewheel_camera_row = row;
735                                 leftover_angle_degrees = angle_degrees % camera_degrees_per_pixel;
736
737                                 // Don't update the live view, that's rarely what the operator wants.
738                         }
739                 }
740                 currently_deferring_model_changes = false;
741                 return true;  // Don't scroll.
742         } else if (event->type() == QEvent::MouseButtonRelease) {
743                 scrubbing = false;
744         }
745         return false;
746 }
747
748 void MainWindow::preview_single_frame(int64_t pts, unsigned stream_idx, MainWindow::Rounding rounding)
749 {
750         if (rounding == LAST_BEFORE) {
751                 lock_guard<mutex> lock(frame_mu);
752                 if (frames[stream_idx].empty())
753                         return;
754                 auto it = find_last_frame_before(frames[stream_idx], pts);
755                 if (it != frames[stream_idx].end()) {
756                         pts = it->pts;
757                 }
758         } else {
759                 assert(rounding == FIRST_AT_OR_AFTER);
760                 lock_guard<mutex> lock(frame_mu);
761                 if (frames[stream_idx].empty())
762                         return;
763                 auto it = find_first_frame_at_or_after(frames[stream_idx], pts);
764                 if (it != frames[stream_idx].end()) {
765                         pts = it->pts;
766                 }
767         }
768
769         Clip fake_clip;
770         fake_clip.pts_in = pts;
771         fake_clip.pts_out = pts + 1;
772         preview_player->play_clip(fake_clip, 0, stream_idx);
773 }
774
775 void MainWindow::playlist_selection_changed()
776 {
777         QItemSelectionModel *selected = ui->playlist->selectionModel();
778         bool any_selected = selected->hasSelection();
779         ui->playlist_duplicate_btn->setEnabled(any_selected);
780         ui->playlist_remove_btn->setEnabled(any_selected);
781         ui->playlist_move_up_btn->setEnabled(
782                 any_selected && selected->selectedRows().front().row() > 0);
783         ui->playlist_move_down_btn->setEnabled(
784                 any_selected && selected->selectedRows().back().row() < int(playlist_clips->size()) - 1);
785         ui->play_btn->setEnabled(!playlist_clips->empty());
786
787         if (!any_selected) {
788                 set_output_status("paused");
789         } else {
790                 double remaining = 0.0;
791                 for (int row = selected->selectedRows().front().row(); row < int(playlist_clips->size()); ++row) {
792                         const Clip clip = *playlist_clips->clip(row);
793                         remaining += double(clip.pts_out - clip.pts_in) / TIMEBASE / 0.5;  // FIXME: stop hardcoding speed.
794                 }
795                 set_output_status(format_duration(remaining) + " ready");
796         }
797 }
798
799 void MainWindow::clip_list_selection_changed(const QModelIndex &current, const QModelIndex &)
800 {
801         int camera_selected = -1;
802         if (current.column() >= int(ClipList::Column::CAMERA_1) &&
803             current.column() <= int(ClipList::Column::CAMERA_4)) {
804                 camera_selected = current.column() - int(ClipList::Column::CAMERA_1);
805         }
806         highlight_camera_input(camera_selected);
807 }
808
809 void MainWindow::report_disk_space(off_t free_bytes, double estimated_seconds_left)
810 {
811         char time_str[256];
812         if (estimated_seconds_left < 60.0) {
813                 strcpy(time_str, "<font color=\"red\">Less than a minute</font>");
814         } else if (estimated_seconds_left < 1800.0) {  // Less than half an hour: Xm Ys (red).
815                 int s = lrintf(estimated_seconds_left);
816                 int m = s / 60;
817                 s %= 60;
818                 snprintf(time_str, sizeof(time_str), "<font color=\"red\">%dm %ds</font>", m, s);
819         } else if (estimated_seconds_left < 3600.0) {  // Less than an hour: Xm.
820                 int m = lrintf(estimated_seconds_left / 60.0);
821                 snprintf(time_str, sizeof(time_str), "%dm", m);
822         } else if (estimated_seconds_left < 36000.0) {  // Less than ten hours: Xh Ym.
823                 int m = lrintf(estimated_seconds_left / 60.0);
824                 int h = m / 60;
825                 m %= 60;
826                 snprintf(time_str, sizeof(time_str), "%dh %dm", h, m);
827         } else {  // More than ten hours: Xh.
828                 int h = lrintf(estimated_seconds_left / 3600.0);
829                 snprintf(time_str, sizeof(time_str), "%dh", h);
830         }
831         char buf[256];
832         snprintf(buf, sizeof(buf), "Disk free: %'.0f MB (approx. %s)", free_bytes / 1048576.0, time_str);
833
834         std::string label = buf;
835
836         post_to_main_thread([this, label] {
837                 disk_free_label->setText(QString::fromStdString(label));
838                 ui->menuBar->setCornerWidget(disk_free_label);  // Need to set this again for the sizing to get right.
839         });
840 }
841
842 void MainWindow::exit_triggered()
843 {
844         close();
845 }
846
847 void MainWindow::export_cliplist_clip_multitrack_triggered()
848 {
849         QItemSelectionModel *selected = ui->clip_list->selectionModel();
850         if (!selected->hasSelection()) {
851                 QMessageBox msgbox;
852                 msgbox.setText("No clip selected in the clip list. Select one and try exporting again.");
853                 msgbox.exec();
854                 return;
855         }
856
857         QModelIndex index = selected->currentIndex();
858         Clip clip = *cliplist_clips->clip(index.row());
859         QString filename = QFileDialog::getSaveFileName(this,
860                 "Export multitrack clip", QString(), tr("Matroska video files (*.mkv)"));
861         if (filename.isNull()) {
862                 // Cancel.
863                 return;
864         }
865         if (!filename.endsWith(".mkv")) {
866                 filename += ".mkv";
867         }
868         export_multitrack_clip(filename.toStdString(), clip);
869 }
870
871 void MainWindow::export_playlist_clip_interpolated_triggered()
872 {
873         QItemSelectionModel *selected = ui->playlist->selectionModel();
874         if (!selected->hasSelection()) {
875                 QMessageBox msgbox;
876                 msgbox.setText("No clip selected in the playlist. Select one and try exporting again.");
877                 msgbox.exec();
878                 return;
879         }
880
881         QString filename = QFileDialog::getSaveFileName(this,
882                 "Export interpolated clip", QString(), tr("Matroska video files (*.mkv)"));
883         if (filename.isNull()) {
884                 // Cancel.
885                 return;
886         }
887         if (!filename.endsWith(".mkv")) {
888                 filename += ".mkv";
889         }
890
891         vector<Clip> clips;
892         QModelIndexList rows = selected->selectedRows();
893         for (QModelIndex index : rows) {
894                 clips.push_back(*playlist_clips->clip(index.row()));
895         }
896         export_interpolated_clip(filename.toStdString(), clips);
897 }
898
899 void MainWindow::manual_triggered()
900 {
901         if (!QDesktopServices::openUrl(QUrl("https://nageru.sesse.net/doc/"))) {
902                 QMessageBox msgbox;
903                 msgbox.setText("Could not launch manual in web browser.\nPlease see https://nageru.sesse.net/doc/ manually.");
904                 msgbox.exec();
905         }
906 }
907
908 void MainWindow::about_triggered()
909 {
910         AboutDialog("Futatabi", "Multicamera slow motion video server").exec();
911 }
912
913 void MainWindow::undo_triggered()
914 {
915         // Finish any deferred action.
916         if (defer_timeout->isActive()) {
917                 defer_timeout->stop();
918                 state_changed(deferred_state);
919         }
920
921         StateProto redo_state;
922         *redo_state.mutable_clip_list() = cliplist_clips->serialize();
923         *redo_state.mutable_play_list() = playlist_clips->serialize();
924         redo_stack.push_back(std::move(redo_state));
925         ui->redo_action->setEnabled(true);
926
927         assert(undo_stack.size() > 1);
928
929         // Pop off the current state, which is always at the top of the stack.
930         undo_stack.pop_back();
931
932         StateProto state = undo_stack.back();
933         ui->undo_action->setEnabled(undo_stack.size() > 1);
934
935         replace_model(ui->clip_list, &cliplist_clips, new ClipList(state.clip_list()));
936         replace_model(ui->playlist, &playlist_clips, new PlayList(state.play_list()));
937
938         db.store_state(state);
939 }
940
941 void MainWindow::redo_triggered()
942 {
943         assert(!redo_stack.empty());
944
945         ui->undo_action->setEnabled(true);
946         ui->redo_action->setEnabled(true);
947
948         undo_stack.push_back(std::move(redo_stack.back()));
949         redo_stack.pop_back();
950         ui->undo_action->setEnabled(true);
951         ui->redo_action->setEnabled(!redo_stack.empty());
952
953         const StateProto &state = undo_stack.back();
954         replace_model(ui->clip_list, &cliplist_clips, new ClipList(state.clip_list()));
955         replace_model(ui->playlist, &playlist_clips, new PlayList(state.play_list()));
956
957         db.store_state(state);
958 }
959
960 void MainWindow::quality_toggled(int quality, bool checked)
961 {
962         if (!checked) {
963                 return;
964         }
965         global_flags.interpolation_quality = quality;
966         if (quality != 0 &&  // Turning interpolation off is always possible.
967             quality != flow_initialized_interpolation_quality) {
968                 QMessageBox msgbox;
969                 msgbox.setText(QString::fromStdString(
970                         "The interpolation quality for the main output cannot be changed at runtime, "
971                         "except being turned completely off; it will take effect for exported files "
972                         "only until next restart. The live output quality thus remains at " + to_string(flow_initialized_interpolation_quality) + "."));
973                 msgbox.exec();
974         }
975
976         save_settings();
977 }
978
979 void MainWindow::highlight_camera_input(int stream_idx)
980 {
981         if (stream_idx == 0) {
982                 ui->input1_frame->setStyleSheet("background: rgb(0,255,0)");
983         } else {
984                 ui->input1_frame->setStyleSheet("");
985         }
986         if (stream_idx == 1) {
987                 ui->input2_frame->setStyleSheet("background: rgb(0,255,0)");
988         } else {
989                 ui->input2_frame->setStyleSheet("");
990         }
991         if (stream_idx == 2) {
992                 ui->input3_frame->setStyleSheet("background: rgb(0,255,0)");
993         } else {
994                 ui->input3_frame->setStyleSheet("");
995         }
996         if (stream_idx == 3) {
997                 ui->input4_frame->setStyleSheet("background: rgb(0,255,0)");
998         } else {
999                 ui->input4_frame->setStyleSheet("");
1000         }
1001 }
1002
1003 void MainWindow::set_output_status(const string &status)
1004 {
1005         ui->live_label->setText(QString::fromStdString("Current output (" + status + ")"));
1006
1007         lock_guard<mutex> lock(queue_status_mu);
1008         queue_status = status;
1009 }
1010
1011 pair<string, string> MainWindow::get_queue_status() const {
1012         lock_guard<mutex> lock(queue_status_mu);
1013         return {queue_status, "text/plain"};
1014 }
1015
1016 template <class Model>
1017 void MainWindow::replace_model(QTableView *view, Model **model, Model *new_model)
1018 {
1019         QItemSelectionModel *old_selection_model = view->selectionModel();
1020         view->setModel(new_model);
1021         delete *model;
1022         delete old_selection_model;
1023         *model = new_model;
1024         connect(new_model, &Model::any_content_changed, this, &MainWindow::content_changed);
1025 }