]> git.sesse.net Git - nageru/blob - futatabi/mainwindow.cpp
Only enable the queue button if we can actually queue something.
[nageru] / futatabi / mainwindow.cpp
1 #include "mainwindow.h"
2
3 #include "clip_list.h"
4 #include "export.h"
5 #include "flags.h"
6 #include "frame_on_disk.h"
7 #include "player.h"
8 #include "shared/aboutdialog.h"
9 #include "shared/disk_space_estimator.h"
10 #include "shared/post_to_main_thread.h"
11 #include "shared/timebase.h"
12 #include "ui_mainwindow.h"
13
14 #include <QDesktopServices>
15 #include <QFileDialog>
16 #include <QMessageBox>
17 #include <QMouseEvent>
18 #include <QNetworkReply>
19 #include <QShortcut>
20 #include <QTimer>
21 #include <QWheelEvent>
22 #include <future>
23 #include <sqlite3.h>
24 #include <string>
25 #include <vector>
26
27 using namespace std;
28 using namespace std::placeholders;
29
30 MainWindow *global_mainwindow = nullptr;
31 static ClipList *cliplist_clips;
32 static PlayList *playlist_clips;
33
34 extern int64_t current_pts;
35
36 MainWindow::MainWindow()
37         : ui(new Ui::MainWindow),
38           db(global_flags.working_directory + "/futatabi.db")
39 {
40         global_mainwindow = this;
41         ui->setupUi(this);
42
43         // Load settings from database.
44         SettingsProto settings = db.get_settings();
45         if (!global_flags.interpolation_quality_set) {
46                 if (settings.interpolation_quality() != 0) {
47                         global_flags.interpolation_quality = settings.interpolation_quality() - 1;
48                 }
49         }
50         if (!global_flags.cue_point_padding_set) {
51                 global_flags.cue_point_padding_seconds = settings.cue_point_padding_seconds();  // Default 0 is fine.
52         }
53         if (global_flags.interpolation_quality == 0) {
54                 // Allocate something just for simplicity; we won't be using it
55                 // unless the user changes runtime, in which case 1 is fine.
56                 flow_initialized_interpolation_quality = 1;
57         } else {
58                 flow_initialized_interpolation_quality = global_flags.interpolation_quality;
59         }
60         save_settings();
61
62         // The menus.
63         connect(ui->exit_action, &QAction::triggered, this, &MainWindow::exit_triggered);
64         connect(ui->export_cliplist_clip_multitrack_action, &QAction::triggered, this, &MainWindow::export_cliplist_clip_multitrack_triggered);
65         connect(ui->export_playlist_clip_interpolated_action, &QAction::triggered, this, &MainWindow::export_playlist_clip_interpolated_triggered);
66         connect(ui->manual_action, &QAction::triggered, this, &MainWindow::manual_triggered);
67         connect(ui->about_action, &QAction::triggered, this, &MainWindow::about_triggered);
68         connect(ui->undo_action, &QAction::triggered, this, &MainWindow::undo_triggered);
69         connect(ui->redo_action, &QAction::triggered, this, &MainWindow::redo_triggered);
70         ui->undo_action->setEnabled(false);
71         ui->redo_action->setEnabled(false);
72
73         // The quality group.
74         QActionGroup *quality_group = new QActionGroup(ui->interpolation_menu);
75         quality_group->addAction(ui->quality_0_action);
76         quality_group->addAction(ui->quality_1_action);
77         quality_group->addAction(ui->quality_2_action);
78         quality_group->addAction(ui->quality_3_action);
79         quality_group->addAction(ui->quality_4_action);
80         if (global_flags.interpolation_quality == 0) {
81                 ui->quality_0_action->setChecked(true);
82         } else if (global_flags.interpolation_quality == 1) {
83                 ui->quality_1_action->setChecked(true);
84         } else if (global_flags.interpolation_quality == 2) {
85                 ui->quality_2_action->setChecked(true);
86         } else if (global_flags.interpolation_quality == 3) {
87                 ui->quality_3_action->setChecked(true);
88         } else if (global_flags.interpolation_quality == 4) {
89                 ui->quality_4_action->setChecked(true);
90         } else {
91                 assert(false);
92         }
93         connect(ui->quality_0_action, &QAction::toggled, bind(&MainWindow::quality_toggled, this, 0, _1));
94         connect(ui->quality_1_action, &QAction::toggled, bind(&MainWindow::quality_toggled, this, 1, _1));
95         connect(ui->quality_2_action, &QAction::toggled, bind(&MainWindow::quality_toggled, this, 2, _1));
96         connect(ui->quality_3_action, &QAction::toggled, bind(&MainWindow::quality_toggled, this, 3, _1));
97         connect(ui->quality_4_action, &QAction::toggled, bind(&MainWindow::quality_toggled, this, 4, _1));
98
99         // The cue point padding group.
100         QActionGroup *padding_group = new QActionGroup(ui->interpolation_menu);
101         padding_group->addAction(ui->padding_0_action);
102         padding_group->addAction(ui->padding_1_action);
103         padding_group->addAction(ui->padding_2_action);
104         padding_group->addAction(ui->padding_5_action);
105         if (global_flags.cue_point_padding_seconds <= 1e-3) {
106                 ui->padding_0_action->setChecked(true);
107         } else if (fabs(global_flags.cue_point_padding_seconds - 1.0) < 1e-3) {
108                 ui->padding_1_action->setChecked(true);
109         } else if (fabs(global_flags.cue_point_padding_seconds - 2.0) < 1e-3) {
110                 ui->padding_2_action->setChecked(true);
111         } else if (fabs(global_flags.cue_point_padding_seconds - 5.0) < 1e-3) {
112                 ui->padding_5_action->setChecked(true);
113         } else {
114                 // Nothing to check, which is fine.
115         }
116         connect(ui->padding_0_action, &QAction::toggled, bind(&MainWindow::padding_toggled, this, 0.0, _1));
117         connect(ui->padding_1_action, &QAction::toggled, bind(&MainWindow::padding_toggled, this, 1.0, _1));
118         connect(ui->padding_2_action, &QAction::toggled, bind(&MainWindow::padding_toggled, this, 2.0, _1));
119         connect(ui->padding_5_action, &QAction::toggled, bind(&MainWindow::padding_toggled, this, 5.0, _1));
120
121         global_disk_space_estimator = new DiskSpaceEstimator(bind(&MainWindow::report_disk_space, this, _1, _2));
122         disk_free_label = new QLabel(this);
123         disk_free_label->setStyleSheet("QLabel {padding-right: 5px;}");
124         ui->menuBar->setCornerWidget(disk_free_label);
125
126         StateProto state = db.get_state();
127         undo_stack.push_back(state);  // The undo stack always has the current state on top.
128
129         cliplist_clips = new ClipList(state.clip_list());
130         ui->clip_list->setModel(cliplist_clips);
131         connect(cliplist_clips, &ClipList::any_content_changed, this, &MainWindow::content_changed);
132
133         playlist_clips = new PlayList(state.play_list());
134         ui->playlist->setModel(playlist_clips);
135         connect(playlist_clips, &PlayList::any_content_changed, this, &MainWindow::content_changed);
136
137         // For un-highlighting when we lose focus.
138         ui->clip_list->installEventFilter(this);
139
140         // For scrubbing in the pts columns.
141         ui->clip_list->viewport()->installEventFilter(this);
142         ui->playlist->viewport()->installEventFilter(this);
143
144         QShortcut *cue_in = new QShortcut(QKeySequence(Qt::Key_A), this);
145         connect(cue_in, &QShortcut::activated, ui->cue_in_btn, &QPushButton::click);
146         connect(ui->cue_in_btn, &QPushButton::clicked, this, &MainWindow::cue_in_clicked);
147
148         QShortcut *cue_out = new QShortcut(QKeySequence(Qt::Key_S), this);
149         connect(cue_out, &QShortcut::activated, ui->cue_out_btn, &QPushButton::click);
150         connect(ui->cue_out_btn, &QPushButton::clicked, this, &MainWindow::cue_out_clicked);
151
152         QShortcut *queue = new QShortcut(QKeySequence(Qt::Key_Q), this);
153         connect(queue, &QShortcut::activated, ui->queue_btn, &QPushButton::click);
154         connect(ui->queue_btn, &QPushButton::clicked, this, &MainWindow::queue_clicked);
155
156         QShortcut *preview = new QShortcut(QKeySequence(Qt::Key_W), this);
157         connect(preview, &QShortcut::activated, ui->preview_btn, &QPushButton::click);
158         connect(ui->preview_btn, &QPushButton::clicked, this, &MainWindow::preview_clicked);
159
160         QShortcut *play = new QShortcut(QKeySequence(Qt::Key_Space), this);
161         connect(play, &QShortcut::activated, ui->play_btn, &QPushButton::click);
162         connect(ui->play_btn, &QPushButton::clicked, this, &MainWindow::play_clicked);
163
164         connect(ui->stop_btn, &QPushButton::clicked, this, &MainWindow::stop_clicked);
165         ui->stop_btn->setEnabled(false);
166
167         connect(ui->playlist_duplicate_btn, &QPushButton::clicked, this, &MainWindow::playlist_duplicate);
168
169         connect(ui->playlist_remove_btn, &QPushButton::clicked, this, &MainWindow::playlist_remove);
170         QShortcut *delete_key = new QShortcut(QKeySequence(Qt::Key_Delete), ui->playlist);
171         connect(delete_key, &QShortcut::activated, [this] {
172                 if (ui->playlist->hasFocus()) {
173                         playlist_remove();
174                 }
175         });
176
177         // TODO: support drag-and-drop.
178         connect(ui->playlist_move_up_btn, &QPushButton::clicked, [this] { playlist_move(-1); });
179         connect(ui->playlist_move_down_btn, &QPushButton::clicked, [this] { playlist_move(1); });
180
181         connect(ui->playlist->selectionModel(), &QItemSelectionModel::selectionChanged,
182                 this, &MainWindow::playlist_selection_changed);
183         playlist_selection_changed();  // First time set-up.
184
185         preview_player.reset(new Player(ui->preview_display, Player::NO_STREAM_OUTPUT));
186         live_player.reset(new Player(ui->live_display, Player::HTTPD_STREAM_OUTPUT));
187         live_player->set_done_callback([this] {
188                 post_to_main_thread([this] {
189                         live_player_done();
190                 });
191         });
192         live_player->set_progress_callback([this](const map<uint64_t, double> &progress, double time_remaining) {
193                 post_to_main_thread([this, progress, time_remaining] {
194                         live_player_clip_progress(progress, time_remaining);
195                 });
196         });
197         set_output_status("paused");
198
199         defer_timeout = new QTimer(this);
200         defer_timeout->setSingleShot(true);
201         connect(defer_timeout, &QTimer::timeout, this, &MainWindow::defer_timer_expired);
202         ui->undo_action->setEnabled(true);
203
204         connect(ui->clip_list->selectionModel(), &QItemSelectionModel::currentChanged,
205                 this, &MainWindow::clip_list_selection_changed);
206         enable_or_disable_queue_button();
207
208         // Find out how many cameras we have in the existing frames;
209         // if none, we start with two cameras.
210         num_cameras = 2;
211         {
212                 lock_guard<mutex> lock(frame_mu);
213                 for (size_t stream_idx = 2; stream_idx < MAX_STREAMS; ++stream_idx) {
214                         if (!frames[stream_idx].empty()) {
215                                 num_cameras = stream_idx + 1;
216                         }
217                 }
218         }
219         change_num_cameras();
220
221         if (!global_flags.tally_url.empty()) {
222                 start_tally();
223         }
224 }
225
226 void MainWindow::change_num_cameras()
227 {
228         assert(num_cameras >= displays.size());  // We only add, never remove.
229
230         // Make new display rows.
231         unsigned display_rows = (num_cameras + 1) / 2;
232         ui->video_displays->setStretch(1, display_rows);
233         for (unsigned i = displays.size(); i < num_cameras; ++i) {
234                 QFrame *frame = new QFrame(this);
235                 frame->setAutoFillBackground(true);
236
237                 QLayout *layout = new QGridLayout(frame);
238                 frame->setLayout(layout);
239                 layout->setContentsMargins(3, 3, 3, 3);
240
241                 JPEGFrameView *display = new JPEGFrameView(frame);
242                 display->setAutoFillBackground(true);
243                 layout->addWidget(display);
244
245                 ui->input_displays->addWidget(frame, i / 2, i % 2);
246                 display->set_overlay(to_string(i + 1));
247
248                 QPushButton *preview_btn = new QPushButton(this);
249                 preview_btn->setMaximumSize(20, 17);
250                 preview_btn->setText(QString::fromStdString(to_string(i + 1)));
251                 ui->preview_layout->addWidget(preview_btn);
252
253                 displays.emplace_back(FrameAndDisplay{ frame, display, preview_btn });
254
255                 connect(display, &JPEGFrameView::clicked, preview_btn, &QPushButton::click);
256                 QShortcut *shortcut = new QShortcut(QKeySequence(Qt::Key_1 + i), this);
257                 connect(shortcut, &QShortcut::activated, preview_btn, &QPushButton::click);
258
259                 connect(preview_btn, &QPushButton::clicked, [this, i] { preview_angle_clicked(i); });
260         }
261
262         cliplist_clips->change_num_cameras(num_cameras);
263         playlist_clips->change_num_cameras(num_cameras);
264
265         QMetaObject::invokeMethod(this, "relayout", Qt::QueuedConnection);
266 }
267
268 MainWindow::~MainWindow()
269 {
270         // Empty so that we can forward-declare Player in the .h file.
271 }
272
273 void MainWindow::cue_in_clicked()
274 {
275         if (!cliplist_clips->empty() && cliplist_clips->back()->pts_out < 0) {
276                 cliplist_clips->mutable_back()->pts_in = current_pts;
277         } else {
278                 Clip clip;
279                 clip.pts_in = max<int64_t>(current_pts - lrint(global_flags.cue_point_padding_seconds * TIMEBASE), 0);
280                 cliplist_clips->add_clip(clip);
281                 playlist_selection_changed();
282         }
283
284         // Select the item so that we can jog it.
285         ui->clip_list->setFocus();
286         QModelIndex index = cliplist_clips->index(cliplist_clips->size() - 1, int(ClipList::Column::IN));
287         ui->clip_list->selectionModel()->setCurrentIndex(index, QItemSelectionModel::ClearAndSelect);
288         ui->clip_list->scrollToBottom();
289         enable_or_disable_queue_button();
290 }
291
292 void MainWindow::cue_out_clicked()
293 {
294         if (cliplist_clips->empty()) {
295                 return;
296         }
297
298         cliplist_clips->mutable_back()->pts_out = current_pts + lrint(global_flags.cue_point_padding_seconds * TIMEBASE);
299
300         // Select the item so that we can jog it.
301         ui->clip_list->setFocus();
302         QModelIndex index = cliplist_clips->index(cliplist_clips->size() - 1, int(ClipList::Column::OUT));
303         ui->clip_list->selectionModel()->setCurrentIndex(index, QItemSelectionModel::ClearAndSelect);
304         ui->clip_list->scrollToBottom();
305         enable_or_disable_queue_button();
306 }
307
308 void MainWindow::queue_clicked()
309 {
310         // See also enable_or_disable_queue_button().
311
312         if (cliplist_clips->empty()) {
313                 return;
314         }
315
316         QItemSelectionModel *selected = ui->clip_list->selectionModel();
317         if (!selected->hasSelection()) {
318                 Clip clip = *cliplist_clips->back();
319                 clip.stream_idx = 0;
320                 if (clip.pts_out != -1) {
321                         playlist_clips->add_clip(clip);
322                         playlist_selection_changed();
323                         ui->playlist->scrollToBottom();
324                 }
325                 return;
326         }
327
328         QModelIndex index = selected->currentIndex();
329         Clip clip = *cliplist_clips->clip(index.row());
330         if (cliplist_clips->is_camera_column(index.column())) {
331                 clip.stream_idx = index.column() - int(ClipList::Column::CAMERA_1);
332         } else {
333                 clip.stream_idx = ui->preview_display->get_stream_idx();
334         }
335
336         if (clip.pts_out != -1) {
337                 playlist_clips->add_clip(clip);
338                 playlist_selection_changed();
339                 ui->playlist->scrollToBottom();
340                 if (!ui->playlist->selectionModel()->hasSelection()) {
341                         // TODO: Figure out why this doesn't always seem to actually select the row.
342                         QModelIndex bottom = playlist_clips->index(playlist_clips->size() - 1, 0);
343                         ui->playlist->setCurrentIndex(bottom);
344                 }
345         }
346 }
347
348 void MainWindow::preview_clicked()
349 {
350         // See also enable_or_disable_preview_button().
351
352         if (ui->playlist->hasFocus()) {
353                 // Allow the playlist as preview iff it has focus and something is selected.
354                 QItemSelectionModel *selected = ui->playlist->selectionModel();
355                 if (selected->hasSelection()) {
356                         QModelIndex index = selected->currentIndex();
357                         const Clip &clip = *playlist_clips->clip(index.row());
358                         preview_player->play(clip);
359                         return;
360                 }
361         }
362
363         if (cliplist_clips->empty())
364                 return;
365
366         QItemSelectionModel *selected = ui->clip_list->selectionModel();
367         if (!selected->hasSelection()) {
368                 preview_player->play(*cliplist_clips->back());
369                 return;
370         }
371
372         QModelIndex index = selected->currentIndex();
373         Clip clip = *cliplist_clips->clip(index.row());
374         if (cliplist_clips->is_camera_column(index.column())) {
375                 clip.stream_idx = index.column() - int(ClipList::Column::CAMERA_1);
376         } else {
377                 clip.stream_idx = ui->preview_display->get_stream_idx();
378         }
379         preview_player->play(clip);
380 }
381
382 void MainWindow::preview_angle_clicked(unsigned stream_idx)
383 {
384         preview_player->override_angle(stream_idx);
385
386         // Change the selection if we were previewing a clip from the clip list.
387         // (The only other thing we could be showing is a pts scrub, and if so,
388         // that would be selected.)
389         QItemSelectionModel *selected = ui->clip_list->selectionModel();
390         if (selected->hasSelection()) {
391                 QModelIndex cell = selected->selectedIndexes()[0];
392                 int column = int(ClipList::Column::CAMERA_1) + stream_idx;
393                 selected->setCurrentIndex(cell.sibling(cell.row(), column), QItemSelectionModel::ClearAndSelect);
394         }
395 }
396
397 void MainWindow::playlist_duplicate()
398 {
399         QItemSelectionModel *selected = ui->playlist->selectionModel();
400         if (!selected->hasSelection()) {
401                 // Should have been grayed out, but OK.
402                 return;
403         }
404         QModelIndexList rows = selected->selectedRows();
405         int first = rows.front().row(), last = rows.back().row();
406         playlist_clips->duplicate_clips(first, last);
407         playlist_selection_changed();
408 }
409
410 void MainWindow::playlist_remove()
411 {
412         QItemSelectionModel *selected = ui->playlist->selectionModel();
413         if (!selected->hasSelection()) {
414                 // Should have been grayed out, but OK.
415                 return;
416         }
417         QModelIndexList rows = selected->selectedRows();
418         int first = rows.front().row(), last = rows.back().row();
419         playlist_clips->erase_clips(first, last);
420
421         // TODO: select the next one in the list?
422
423         playlist_selection_changed();
424 }
425
426 void MainWindow::playlist_move(int delta)
427 {
428         QItemSelectionModel *selected = ui->playlist->selectionModel();
429         if (!selected->hasSelection()) {
430                 // Should have been grayed out, but OK.
431                 return;
432         }
433
434         QModelIndexList rows = selected->selectedRows();
435         int first = rows.front().row(), last = rows.back().row();
436         if ((delta == -1 && first == 0) ||
437             (delta == 1 && size_t(last) == playlist_clips->size() - 1)) {
438                 // Should have been grayed out, but OK.
439                 return;
440         }
441
442         playlist_clips->move_clips(first, last, delta);
443         playlist_selection_changed();
444 }
445
446 void MainWindow::defer_timer_expired()
447 {
448         state_changed(deferred_state);
449 }
450
451 void MainWindow::content_changed()
452 {
453         // If we are playing, update the part of the playlist that's not playing yet.
454         vector<ClipWithID> clips;
455         for (unsigned row = 0; row < playlist_clips->size(); ++row) {
456                 clips.emplace_back(*playlist_clips->clip_with_id(row));
457         }
458         live_player->splice_play(clips);
459
460         // Serialize the state.
461         if (defer_timeout->isActive() &&
462             (!currently_deferring_model_changes || deferred_change_id != current_change_id)) {
463                 // There's some deferred event waiting, but this event is unrelated.
464                 // So it's time to short-circuit that timer and do the work it wanted to do.
465                 defer_timeout->stop();
466                 state_changed(deferred_state);
467         }
468         StateProto state;
469         *state.mutable_clip_list() = cliplist_clips->serialize();
470         *state.mutable_play_list() = playlist_clips->serialize();
471         if (currently_deferring_model_changes) {
472                 deferred_change_id = current_change_id;
473                 deferred_state = std::move(state);
474                 defer_timeout->start(200);
475                 return;
476         }
477         state_changed(state);
478 }
479
480 void MainWindow::state_changed(const StateProto &state)
481 {
482         db.store_state(state);
483
484         redo_stack.clear();
485         ui->redo_action->setEnabled(false);
486
487         undo_stack.push_back(state);
488         ui->undo_action->setEnabled(undo_stack.size() > 1);
489
490         // Make sure it doesn't grow without bounds.
491         while (undo_stack.size() >= 100) {
492                 undo_stack.pop_front();
493         }
494 }
495
496 void MainWindow::save_settings()
497 {
498         SettingsProto settings;
499         settings.set_interpolation_quality(global_flags.interpolation_quality + 1);
500         settings.set_cue_point_padding_seconds(global_flags.cue_point_padding_seconds);
501         db.store_settings(settings);
502 }
503
504 void MainWindow::play_clicked()
505 {
506         if (playlist_clips->empty())
507                 return;
508
509         QItemSelectionModel *selected = ui->playlist->selectionModel();
510         unsigned start_row;
511         if (!selected->hasSelection()) {
512                 start_row = 0;
513         } else {
514                 start_row = selected->selectedRows(0)[0].row();
515         }
516
517         vector<ClipWithID> clips;
518         for (unsigned row = start_row; row < playlist_clips->size(); ++row) {
519                 clips.emplace_back(*playlist_clips->clip_with_id(row));
520         }
521         live_player->play(clips);
522         playlist_clips->set_progress({ { start_row, 0.0f } });
523         ui->playlist->selectionModel()->clear();
524         playlist_selection_changed();
525
526         ui->stop_btn->setEnabled(true);
527 }
528
529 void MainWindow::stop_clicked()
530 {
531         Clip fake_clip;
532         fake_clip.pts_in = 0;
533         fake_clip.pts_out = 0;
534         playlist_clips->set_progress({});
535         live_player->play(fake_clip);
536         ui->stop_btn->setEnabled(false);
537 }
538
539 void MainWindow::live_player_done()
540 {
541         playlist_selection_changed();
542         playlist_clips->set_progress({});
543         ui->stop_btn->setEnabled(false);
544 }
545
546 void MainWindow::live_player_clip_progress(const map<uint64_t, double> &progress, double time_remaining)
547 {
548         playlist_clips->set_progress(progress);
549         set_output_status(format_duration(time_remaining) + " left");
550 }
551
552 void MainWindow::resizeEvent(QResizeEvent *event)
553 {
554         QMainWindow::resizeEvent(event);
555
556         // Ask for a relayout, but only after the event loop is done doing relayout
557         // on everything else.
558         QMetaObject::invokeMethod(this, "relayout", Qt::QueuedConnection);
559 }
560
561 void MainWindow::relayout()
562 {
563         ui->live_display->setMinimumWidth(ui->live_display->height() * 16 / 9);
564         ui->preview_display->setMinimumWidth(ui->preview_display->height() * 16 / 9);
565 }
566
567 void set_pts_in(int64_t pts, int64_t current_pts, ClipProxy &clip)
568 {
569         pts = std::max<int64_t>(pts, 0);
570         if (clip->pts_out == -1) {
571                 pts = std::min(pts, current_pts);
572         } else {
573                 pts = std::min(pts, clip->pts_out);
574         }
575         clip->pts_in = pts;
576 }
577
578 bool MainWindow::eventFilter(QObject *watched, QEvent *event)
579 {
580         constexpr int dead_zone_pixels = 3;  // To avoid that simple clicks get misinterpreted.
581         constexpr int camera_degrees_per_pixel = 15;  // One click of most mice.
582         int scrub_sensitivity = 100;  // pts units per pixel.
583         int wheel_sensitivity = 100;  // pts units per degree.
584
585         if (event->type() == QEvent::FocusIn || event->type() == QEvent::FocusOut) {
586                 enable_or_disable_preview_button();
587         }
588
589         unsigned stream_idx = ui->preview_display->get_stream_idx();
590
591         if (watched == ui->clip_list) {
592                 if (event->type() == QEvent::FocusOut) {
593                         highlight_camera_input(-1);
594                 }
595                 return false;
596         }
597
598         if (event->type() != QEvent::Wheel) {
599                 last_mousewheel_camera_row = -1;
600         }
601
602         if (event->type() == QEvent::MouseButtonPress) {
603                 QMouseEvent *mouse = (QMouseEvent *)event;
604
605                 QTableView *destination;
606                 ScrubType type;
607
608                 if (watched == ui->clip_list->viewport()) {
609                         destination = ui->clip_list;
610                         type = SCRUBBING_CLIP_LIST;
611                 } else if (watched == ui->playlist->viewport()) {
612                         destination = ui->playlist;
613                         type = SCRUBBING_PLAYLIST;
614                 } else {
615                         return false;
616                 }
617                 int column = destination->columnAt(mouse->x());
618                 int row = destination->rowAt(mouse->y());
619                 if (column == -1 || row == -1)
620                         return false;
621
622                 if (type == SCRUBBING_CLIP_LIST) {
623                         if (ClipList::Column(column) == ClipList::Column::IN) {
624                                 scrub_pts_origin = cliplist_clips->clip(row)->pts_in;
625                                 preview_single_frame(scrub_pts_origin, stream_idx, FIRST_AT_OR_AFTER);
626                         } else if (ClipList::Column(column) == ClipList::Column::OUT) {
627                                 scrub_pts_origin = cliplist_clips->clip(row)->pts_out;
628                                 preview_single_frame(scrub_pts_origin, stream_idx, LAST_BEFORE);
629                         } else {
630                                 return false;
631                         }
632                 } else {
633                         if (PlayList::Column(column) == PlayList::Column::IN) {
634                                 scrub_pts_origin = playlist_clips->clip(row)->pts_in;
635                                 preview_single_frame(scrub_pts_origin, stream_idx, FIRST_AT_OR_AFTER);
636                         } else if (PlayList::Column(column) == PlayList::Column::OUT) {
637                                 scrub_pts_origin = playlist_clips->clip(row)->pts_out;
638                                 preview_single_frame(scrub_pts_origin, stream_idx, LAST_BEFORE);
639                         } else {
640                                 return false;
641                         }
642                 }
643
644                 scrubbing = true;
645                 scrub_row = row;
646                 scrub_column = column;
647                 scrub_x_origin = mouse->x();
648                 scrub_type = type;
649         } else if (event->type() == QEvent::MouseMove) {
650                 QMouseEvent *mouse = (QMouseEvent *)event;
651                 if (mouse->modifiers() & Qt::KeyboardModifier::ShiftModifier) {
652                         scrub_sensitivity *= 10;
653                         wheel_sensitivity *= 10;
654                 }
655                 if (mouse->modifiers() & Qt::KeyboardModifier::AltModifier) {  // Note: Shift + Alt cancel each other out.
656                         scrub_sensitivity /= 10;
657                         wheel_sensitivity /= 10;
658                 }
659                 if (scrubbing) {
660                         int offset = mouse->x() - scrub_x_origin;
661                         int adjusted_offset;
662                         if (offset >= dead_zone_pixels) {
663                                 adjusted_offset = offset - dead_zone_pixels;
664                         } else if (offset < -dead_zone_pixels) {
665                                 adjusted_offset = offset + dead_zone_pixels;
666                         } else {
667                                 adjusted_offset = 0;
668                         }
669
670                         int64_t pts = scrub_pts_origin + adjusted_offset * scrub_sensitivity;
671                         currently_deferring_model_changes = true;
672                         if (scrub_type == SCRUBBING_CLIP_LIST) {
673                                 ClipProxy clip = cliplist_clips->mutable_clip(scrub_row);
674                                 if (scrub_column == int(ClipList::Column::IN)) {
675                                         current_change_id = "cliplist:in:" + to_string(scrub_row);
676                                         set_pts_in(pts, current_pts, clip);
677                                         preview_single_frame(pts, stream_idx, FIRST_AT_OR_AFTER);
678                                 } else {
679                                         current_change_id = "cliplist:out" + to_string(scrub_row);
680                                         pts = std::max(pts, clip->pts_in);
681                                         pts = std::min(pts, current_pts);
682                                         clip->pts_out = pts;
683                                         preview_single_frame(pts, stream_idx, LAST_BEFORE);
684                                 }
685                         } else {
686                                 ClipProxy clip = playlist_clips->mutable_clip(scrub_row);
687                                 if (scrub_column == int(PlayList::Column::IN)) {
688                                         current_change_id = "playlist:in:" + to_string(scrub_row);
689                                         set_pts_in(pts, current_pts, clip);
690                                         preview_single_frame(pts, clip->stream_idx, FIRST_AT_OR_AFTER);
691                                 } else {
692                                         current_change_id = "playlist:out:" + to_string(scrub_row);
693                                         pts = std::max(pts, clip->pts_in);
694                                         pts = std::min(pts, current_pts);
695                                         clip->pts_out = pts;
696                                         preview_single_frame(pts, clip->stream_idx, LAST_BEFORE);
697                                 }
698                         }
699                         currently_deferring_model_changes = false;
700
701                         return true;  // Don't use this mouse movement for selecting things.
702                 }
703         } else if (event->type() == QEvent::Wheel) {
704                 QWheelEvent *wheel = (QWheelEvent *)event;
705                 int angle_delta = wheel->angleDelta().y();
706                 if (wheel->modifiers() & Qt::KeyboardModifier::ShiftModifier) {
707                         scrub_sensitivity *= 10;
708                         wheel_sensitivity *= 10;
709                 }
710                 if (wheel->modifiers() & Qt::KeyboardModifier::AltModifier) {  // Note: Shift + Alt cancel each other out.
711                         scrub_sensitivity /= 10;
712                         wheel_sensitivity /= 10;
713                         angle_delta = wheel->angleDelta().x();  // Qt ickiness.
714                 }
715
716                 QTableView *destination;
717                 int in_column, out_column, camera_column;
718                 if (watched == ui->clip_list->viewport()) {
719                         destination = ui->clip_list;
720                         in_column = int(ClipList::Column::IN);
721                         out_column = int(ClipList::Column::OUT);
722                         camera_column = -1;
723                         last_mousewheel_camera_row = -1;
724                 } else if (watched == ui->playlist->viewport()) {
725                         destination = ui->playlist;
726                         in_column = int(PlayList::Column::IN);
727                         out_column = int(PlayList::Column::OUT);
728                         camera_column = int(PlayList::Column::CAMERA);
729                 } else {
730                         last_mousewheel_camera_row = -1;
731                         return false;
732                 }
733                 int column = destination->columnAt(wheel->x());
734                 int row = destination->rowAt(wheel->y());
735                 if (column == -1 || row == -1)
736                         return false;
737
738                 // Only adjust pts with the wheel if the given row is selected.
739                 if (!destination->hasFocus() ||
740                     row != destination->selectionModel()->currentIndex().row()) {
741                         return false;
742                 }
743
744                 currently_deferring_model_changes = true;
745                 {
746                         current_change_id = (watched == ui->clip_list->viewport()) ? "cliplist:" : "playlist:";
747                         ClipProxy clip = (watched == ui->clip_list->viewport()) ? cliplist_clips->mutable_clip(row) : playlist_clips->mutable_clip(row);
748                         if (watched == ui->playlist->viewport()) {
749                                 stream_idx = clip->stream_idx;
750                         }
751
752                         if (column != camera_column) {
753                                 last_mousewheel_camera_row = -1;
754                         }
755                         if (column == in_column) {
756                                 current_change_id += "in:" + to_string(row);
757                                 int64_t pts = clip->pts_in + angle_delta * wheel_sensitivity;
758                                 set_pts_in(pts, current_pts, clip);
759                                 preview_single_frame(pts, stream_idx, FIRST_AT_OR_AFTER);
760                         } else if (column == out_column) {
761                                 current_change_id += "out:" + to_string(row);
762                                 int64_t pts = clip->pts_out + angle_delta * wheel_sensitivity;
763                                 pts = std::max(pts, clip->pts_in);
764                                 pts = std::min(pts, current_pts);
765                                 clip->pts_out = pts;
766                                 preview_single_frame(pts, stream_idx, LAST_BEFORE);
767                         } else if (column == camera_column) {
768                                 current_change_id += "camera:" + to_string(row);
769                                 int angle_degrees = angle_delta;
770                                 if (last_mousewheel_camera_row == row) {
771                                         angle_degrees += leftover_angle_degrees;
772                                 }
773
774                                 int stream_idx = clip->stream_idx + angle_degrees / camera_degrees_per_pixel;
775                                 stream_idx = std::max(stream_idx, 0);
776                                 stream_idx = std::min<int>(stream_idx, num_cameras - 1);
777                                 clip->stream_idx = stream_idx;
778
779                                 last_mousewheel_camera_row = row;
780                                 leftover_angle_degrees = angle_degrees % camera_degrees_per_pixel;
781
782                                 // Don't update the live view, that's rarely what the operator wants.
783                         }
784                 }
785                 currently_deferring_model_changes = false;
786                 return true;  // Don't scroll.
787         } else if (event->type() == QEvent::MouseButtonRelease) {
788                 scrubbing = false;
789         }
790         return false;
791 }
792
793 void MainWindow::preview_single_frame(int64_t pts, unsigned stream_idx, MainWindow::Rounding rounding)
794 {
795         if (rounding == LAST_BEFORE) {
796                 lock_guard<mutex> lock(frame_mu);
797                 if (frames[stream_idx].empty())
798                         return;
799                 auto it = find_last_frame_before(frames[stream_idx], pts);
800                 if (it != frames[stream_idx].end()) {
801                         pts = it->pts;
802                 }
803         } else {
804                 assert(rounding == FIRST_AT_OR_AFTER);
805                 lock_guard<mutex> lock(frame_mu);
806                 if (frames[stream_idx].empty())
807                         return;
808                 auto it = find_first_frame_at_or_after(frames[stream_idx], pts);
809                 if (it != frames[stream_idx].end()) {
810                         pts = it->pts;
811                 }
812         }
813
814         Clip fake_clip;
815         fake_clip.pts_in = pts;
816         fake_clip.pts_out = pts + 1;
817         fake_clip.stream_idx = stream_idx;
818         preview_player->play(fake_clip);
819 }
820
821 void MainWindow::playlist_selection_changed()
822 {
823         enable_or_disable_preview_button();
824
825         QItemSelectionModel *selected = ui->playlist->selectionModel();
826         bool any_selected = selected->hasSelection();
827         ui->playlist_duplicate_btn->setEnabled(any_selected);
828         ui->playlist_remove_btn->setEnabled(any_selected);
829         ui->playlist_move_up_btn->setEnabled(
830                 any_selected && selected->selectedRows().front().row() > 0);
831         ui->playlist_move_down_btn->setEnabled(
832                 any_selected && selected->selectedRows().back().row() < int(playlist_clips->size()) - 1);
833         ui->play_btn->setEnabled(!playlist_clips->empty());
834
835         if (!any_selected) {
836                 set_output_status("paused");
837         } else {
838                 vector<ClipWithID> clips;
839                 for (size_t row = selected->selectedRows().front().row(); row < playlist_clips->size(); ++row) {
840                         clips.emplace_back(*playlist_clips->clip_with_id(row));
841                 }
842                 double remaining = compute_total_time(clips);
843                 set_output_status(format_duration(remaining) + " ready");
844         }
845 }
846
847 void MainWindow::clip_list_selection_changed(const QModelIndex &current, const QModelIndex &)
848 {
849         int camera_selected = -1;
850         if (cliplist_clips->is_camera_column(current.column())) {
851                 camera_selected = current.column() - int(ClipList::Column::CAMERA_1);
852         }
853         highlight_camera_input(camera_selected);
854         enable_or_disable_queue_button();
855 }
856
857 void MainWindow::report_disk_space(off_t free_bytes, double estimated_seconds_left)
858 {
859         char time_str[256];
860         if (estimated_seconds_left < 60.0) {
861                 strcpy(time_str, "<font color=\"red\">Less than a minute</font>");
862         } else if (estimated_seconds_left < 1800.0) {  // Less than half an hour: Xm Ys (red).
863                 int s = lrintf(estimated_seconds_left);
864                 int m = s / 60;
865                 s %= 60;
866                 snprintf(time_str, sizeof(time_str), "<font color=\"red\">%dm %ds</font>", m, s);
867         } else if (estimated_seconds_left < 3600.0) {  // Less than an hour: Xm.
868                 int m = lrintf(estimated_seconds_left / 60.0);
869                 snprintf(time_str, sizeof(time_str), "%dm", m);
870         } else if (estimated_seconds_left < 36000.0) {  // Less than ten hours: Xh Ym.
871                 int m = lrintf(estimated_seconds_left / 60.0);
872                 int h = m / 60;
873                 m %= 60;
874                 snprintf(time_str, sizeof(time_str), "%dh %dm", h, m);
875         } else {  // More than ten hours: Xh.
876                 int h = lrintf(estimated_seconds_left / 3600.0);
877                 snprintf(time_str, sizeof(time_str), "%dh", h);
878         }
879         char buf[256];
880         snprintf(buf, sizeof(buf), "Disk free: %'.0f MB (approx. %s)", free_bytes / 1048576.0, time_str);
881
882         std::string label = buf;
883
884         post_to_main_thread([this, label] {
885                 disk_free_label->setText(QString::fromStdString(label));
886                 ui->menuBar->setCornerWidget(disk_free_label);  // Need to set this again for the sizing to get right.
887         });
888 }
889
890 void MainWindow::exit_triggered()
891 {
892         close();
893 }
894
895 void MainWindow::export_cliplist_clip_multitrack_triggered()
896 {
897         QItemSelectionModel *selected = ui->clip_list->selectionModel();
898         if (!selected->hasSelection()) {
899                 QMessageBox msgbox;
900                 msgbox.setText("No clip selected in the clip list. Select one and try exporting again.");
901                 msgbox.exec();
902                 return;
903         }
904
905         QModelIndex index = selected->currentIndex();
906         Clip clip = *cliplist_clips->clip(index.row());
907         QString filename = QFileDialog::getSaveFileName(this,
908                 "Export multitrack clip", QString(), tr("Matroska video files (*.mkv)"));
909         if (filename.isNull()) {
910                 // Cancel.
911                 return;
912         }
913         if (!filename.endsWith(".mkv")) {
914                 filename += ".mkv";
915         }
916         export_multitrack_clip(filename.toStdString(), clip);
917 }
918
919 void MainWindow::export_playlist_clip_interpolated_triggered()
920 {
921         QItemSelectionModel *selected = ui->playlist->selectionModel();
922         if (!selected->hasSelection()) {
923                 QMessageBox msgbox;
924                 msgbox.setText("No clip selected in the playlist. Select one and try exporting again.");
925                 msgbox.exec();
926                 return;
927         }
928
929         QString filename = QFileDialog::getSaveFileName(this,
930                 "Export interpolated clip", QString(), tr("Matroska video files (*.mkv)"));
931         if (filename.isNull()) {
932                 // Cancel.
933                 return;
934         }
935         if (!filename.endsWith(".mkv")) {
936                 filename += ".mkv";
937         }
938
939         vector<Clip> clips;
940         QModelIndexList rows = selected->selectedRows();
941         for (QModelIndex index : rows) {
942                 clips.push_back(*playlist_clips->clip(index.row()));
943         }
944         export_interpolated_clip(filename.toStdString(), clips);
945 }
946
947 void MainWindow::manual_triggered()
948 {
949         if (!QDesktopServices::openUrl(QUrl("https://nageru.sesse.net/doc/"))) {
950                 QMessageBox msgbox;
951                 msgbox.setText("Could not launch manual in web browser.\nPlease see https://nageru.sesse.net/doc/ manually.");
952                 msgbox.exec();
953         }
954 }
955
956 void MainWindow::about_triggered()
957 {
958         AboutDialog("Futatabi", "Multicamera slow motion video server").exec();
959 }
960
961 void MainWindow::undo_triggered()
962 {
963         // Finish any deferred action.
964         if (defer_timeout->isActive()) {
965                 defer_timeout->stop();
966                 state_changed(deferred_state);
967         }
968
969         StateProto redo_state;
970         *redo_state.mutable_clip_list() = cliplist_clips->serialize();
971         *redo_state.mutable_play_list() = playlist_clips->serialize();
972         redo_stack.push_back(std::move(redo_state));
973         ui->redo_action->setEnabled(true);
974
975         assert(undo_stack.size() > 1);
976
977         // Pop off the current state, which is always at the top of the stack.
978         undo_stack.pop_back();
979
980         StateProto state = undo_stack.back();
981         ui->undo_action->setEnabled(undo_stack.size() > 1);
982
983         replace_model(ui->clip_list, &cliplist_clips, new ClipList(state.clip_list()));
984         replace_model(ui->playlist, &playlist_clips, new PlayList(state.play_list()));
985
986         db.store_state(state);
987 }
988
989 void MainWindow::redo_triggered()
990 {
991         assert(!redo_stack.empty());
992
993         ui->undo_action->setEnabled(true);
994         ui->redo_action->setEnabled(true);
995
996         undo_stack.push_back(std::move(redo_stack.back()));
997         redo_stack.pop_back();
998         ui->undo_action->setEnabled(true);
999         ui->redo_action->setEnabled(!redo_stack.empty());
1000
1001         const StateProto &state = undo_stack.back();
1002         replace_model(ui->clip_list, &cliplist_clips, new ClipList(state.clip_list()));
1003         replace_model(ui->playlist, &playlist_clips, new PlayList(state.play_list()));
1004
1005         db.store_state(state);
1006 }
1007
1008 void MainWindow::quality_toggled(int quality, bool checked)
1009 {
1010         if (!checked) {
1011                 return;
1012         }
1013         global_flags.interpolation_quality = quality;
1014         if (quality != 0 &&  // Turning interpolation off is always possible.
1015             quality != flow_initialized_interpolation_quality) {
1016                 QMessageBox msgbox;
1017                 msgbox.setText(QString::fromStdString(
1018                         "The interpolation quality for the main output cannot be changed at runtime, "
1019                         "except being turned completely off; it will take effect for exported files "
1020                         "only until next restart. The live output quality thus remains at " +
1021                         to_string(flow_initialized_interpolation_quality) + "."));
1022                 msgbox.exec();
1023         }
1024
1025         save_settings();
1026 }
1027
1028 void MainWindow::padding_toggled(double seconds, bool checked)
1029 {
1030         if (!checked) {
1031                 return;
1032         }
1033         global_flags.cue_point_padding_seconds = seconds;
1034         save_settings();
1035 }
1036
1037 void MainWindow::highlight_camera_input(int stream_idx)
1038 {
1039         for (unsigned i = 0; i < num_cameras; ++i) {
1040                 if (unsigned(stream_idx) == i) {
1041                         displays[i].frame->setStyleSheet("background: rgb(0,255,0)");
1042                 } else {
1043                         displays[i].frame->setStyleSheet("");
1044                 }
1045         }
1046 }
1047
1048 void MainWindow::enable_or_disable_preview_button()
1049 {
1050         // Follows the logic in preview_clicked().
1051
1052         if (ui->playlist->hasFocus()) {
1053                 // Allow the playlist as preview iff it has focus and something is selected.
1054                 // TODO: Is this part really relevant?
1055                 QItemSelectionModel *selected = ui->playlist->selectionModel();
1056                 if (selected->hasSelection()) {
1057                         ui->preview_btn->setEnabled(true);
1058                         return;
1059                 }
1060         }
1061
1062         // TODO: Perhaps only enable this if something is actually selected.
1063         ui->preview_btn->setEnabled(!cliplist_clips->empty());
1064 }
1065
1066 void MainWindow::enable_or_disable_queue_button()
1067 {
1068         // Follows the logic in queue_clicked().
1069         // TODO: Perhaps only enable this if something is actually selected.
1070
1071         bool enabled;
1072
1073         if (cliplist_clips->empty()) {
1074                 enabled = false;
1075         } else {
1076                 QItemSelectionModel *selected = ui->clip_list->selectionModel();
1077                 if (!selected->hasSelection()) {
1078                         Clip clip = *cliplist_clips->back();
1079                         enabled = clip.pts_out != -1;
1080                 } else {
1081                         QModelIndex index = selected->currentIndex();
1082                         Clip clip = *cliplist_clips->clip(index.row());
1083                         enabled = clip.pts_out != -1;
1084                 }
1085         }
1086
1087         ui->queue_btn->setEnabled(enabled);
1088 }
1089
1090 void MainWindow::set_output_status(const string &status)
1091 {
1092         ui->live_label->setText(QString::fromStdString("Current output (" + status + ")"));
1093         if (live_player != nullptr) {
1094                 live_player->set_pause_status(status);
1095         }
1096
1097         lock_guard<mutex> lock(queue_status_mu);
1098         queue_status = status;
1099 }
1100
1101 pair<string, string> MainWindow::get_queue_status() const
1102 {
1103         lock_guard<mutex> lock(queue_status_mu);
1104         return { queue_status, "text/plain" };
1105 }
1106
1107 void MainWindow::display_frame(unsigned stream_idx, const FrameOnDisk &frame)
1108 {
1109         if (stream_idx >= MAX_STREAMS) {
1110                 fprintf(stderr, "WARNING: Ignoring too-high stream index %u.\n", stream_idx);
1111                 return;
1112         }
1113         if (stream_idx >= num_cameras) {
1114                 post_to_main_thread_and_wait([this, stream_idx] {
1115                         num_cameras = stream_idx + 1;
1116                         change_num_cameras();
1117                 });
1118         }
1119         displays[stream_idx].display->setFrame(stream_idx, frame);
1120 }
1121
1122 template<class Model>
1123 void MainWindow::replace_model(QTableView *view, Model **model, Model *new_model)
1124 {
1125         QItemSelectionModel *old_selection_model = view->selectionModel();
1126         view->setModel(new_model);
1127         delete *model;
1128         delete old_selection_model;
1129         *model = new_model;
1130         connect(new_model, &Model::any_content_changed, this, &MainWindow::content_changed);
1131 }
1132
1133 void MainWindow::start_tally()
1134 {
1135         http_reply = http.get(QNetworkRequest(QString::fromStdString(global_flags.tally_url)));
1136         connect(http_reply, &QNetworkReply::finished, this, &MainWindow::tally_received);
1137 }
1138
1139 void MainWindow::tally_received()
1140 {
1141         unsigned time_to_next_tally_ms;
1142         if (http_reply->error()) {
1143                 fprintf(stderr, "HTTP get of '%s' failed: %s\n", global_flags.tally_url.c_str(),
1144                         http_reply->errorString().toStdString().c_str());
1145                 ui->live_frame->setStyleSheet("");
1146                 time_to_next_tally_ms = 1000;
1147         } else {
1148                 string contents = http_reply->readAll().toStdString();
1149                 ui->live_frame->setStyleSheet(QString::fromStdString("background: " + contents));
1150                 time_to_next_tally_ms = 100;
1151         }
1152         http_reply->deleteLater();
1153         http_reply = nullptr;
1154
1155         QTimer::singleShot(time_to_next_tally_ms, this, &MainWindow::start_tally);
1156 }