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