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