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