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