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