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