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