]> git.sesse.net Git - nageru/blob - futatabi/mainwindow.cpp
Show preview display when using cue in or cue out, not just on scrubbing.
[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 "futatabi_midi_mapping.pb.h"
9 #include "midi_mapping_dialog.h"
10 #include "shared/aboutdialog.h"
11 #include "shared/disk_space_estimator.h"
12 #include "shared/post_to_main_thread.h"
13 #include "shared/timebase.h"
14 #include "ui_mainwindow.h"
15
16 #include <QDesktopServices>
17 #include <QFileDialog>
18 #include <QMessageBox>
19 #include <QMouseEvent>
20 #include <QNetworkReply>
21 #include <QShortcut>
22 #include <QTimer>
23 #include <QWheelEvent>
24 #include <future>
25 #include <sqlite3.h>
26 #include <string>
27 #include <vector>
28
29 using namespace std;
30 using namespace std::placeholders;
31
32 MainWindow *global_mainwindow = nullptr;
33 static ClipList *cliplist_clips;
34 static PlayList *playlist_clips;
35
36 extern int64_t current_pts;
37
38 namespace {
39
40 void set_pts_in(int64_t pts, int64_t current_pts, ClipProxy &clip)
41 {
42         pts = std::max<int64_t>(pts, 0);
43         if (clip->pts_out == -1) {
44                 pts = std::min(pts, current_pts);
45         } else {
46                 pts = std::min(pts, clip->pts_out);
47         }
48         clip->pts_in = pts;
49 }
50
51 }  // namespace
52
53 MainWindow::MainWindow()
54         : ui(new Ui::MainWindow),
55           db(global_flags.working_directory + "/futatabi.db"),
56           midi_mapper(this)
57 {
58         global_mainwindow = this;
59         ui->setupUi(this);
60
61         // Load settings from database.
62         SettingsProto settings = db.get_settings();
63         if (!global_flags.interpolation_quality_set) {
64                 if (settings.interpolation_quality() != 0) {
65                         global_flags.interpolation_quality = settings.interpolation_quality() - 1;
66                 }
67         }
68         if (!global_flags.cue_in_point_padding_set) {
69                 global_flags.cue_in_point_padding_seconds = settings.cue_in_point_padding_seconds();  // Default 0 is fine.
70         }
71         if (!global_flags.cue_out_point_padding_set) {
72                 global_flags.cue_out_point_padding_seconds = settings.cue_out_point_padding_seconds();  // Default 0 is fine.
73         }
74         if (global_flags.interpolation_quality == 0) {
75                 // Allocate something just for simplicity; we won't be using it
76                 // unless the user changes runtime, in which case 1 is fine.
77                 flow_initialized_interpolation_quality = 1;
78         } else {
79                 flow_initialized_interpolation_quality = global_flags.interpolation_quality;
80         }
81         save_settings();
82
83         // The menus.
84         connect(ui->midi_mapping_action, &QAction::triggered, this, &MainWindow::midi_mapping_triggered);
85         connect(ui->exit_action, &QAction::triggered, this, &MainWindow::exit_triggered);
86         connect(ui->export_cliplist_clip_multitrack_action, &QAction::triggered, this, &MainWindow::export_cliplist_clip_multitrack_triggered);
87         connect(ui->export_playlist_clip_interpolated_action, &QAction::triggered, this, &MainWindow::export_playlist_clip_interpolated_triggered);
88         connect(ui->manual_action, &QAction::triggered, this, &MainWindow::manual_triggered);
89         connect(ui->about_action, &QAction::triggered, this, &MainWindow::about_triggered);
90         connect(ui->undo_action, &QAction::triggered, this, &MainWindow::undo_triggered);
91         connect(ui->redo_action, &QAction::triggered, this, &MainWindow::redo_triggered);
92         ui->undo_action->setEnabled(false);
93         ui->redo_action->setEnabled(false);
94
95         // The quality group.
96         QActionGroup *quality_group = new QActionGroup(ui->interpolation_menu);
97         quality_group->addAction(ui->quality_0_action);
98         quality_group->addAction(ui->quality_1_action);
99         quality_group->addAction(ui->quality_2_action);
100         quality_group->addAction(ui->quality_3_action);
101         quality_group->addAction(ui->quality_4_action);
102         if (global_flags.interpolation_quality == 0) {
103                 ui->quality_0_action->setChecked(true);
104         } else if (global_flags.interpolation_quality == 1) {
105                 ui->quality_1_action->setChecked(true);
106         } else if (global_flags.interpolation_quality == 2) {
107                 ui->quality_2_action->setChecked(true);
108         } else if (global_flags.interpolation_quality == 3) {
109                 ui->quality_3_action->setChecked(true);
110         } else if (global_flags.interpolation_quality == 4) {
111                 ui->quality_4_action->setChecked(true);
112         } else {
113                 assert(false);
114         }
115         connect(ui->quality_0_action, &QAction::toggled, bind(&MainWindow::quality_toggled, this, 0, _1));
116         connect(ui->quality_1_action, &QAction::toggled, bind(&MainWindow::quality_toggled, this, 1, _1));
117         connect(ui->quality_2_action, &QAction::toggled, bind(&MainWindow::quality_toggled, this, 2, _1));
118         connect(ui->quality_3_action, &QAction::toggled, bind(&MainWindow::quality_toggled, this, 3, _1));
119         connect(ui->quality_4_action, &QAction::toggled, bind(&MainWindow::quality_toggled, this, 4, _1));
120
121         // The cue-in point padding group.
122         QActionGroup *in_padding_group = new QActionGroup(ui->in_padding_menu);
123         in_padding_group->addAction(ui->in_padding_0_action);
124         in_padding_group->addAction(ui->in_padding_1_action);
125         in_padding_group->addAction(ui->in_padding_2_action);
126         in_padding_group->addAction(ui->in_padding_5_action);
127         if (global_flags.cue_in_point_padding_seconds <= 1e-3) {
128                 ui->in_padding_0_action->setChecked(true);
129         } else if (fabs(global_flags.cue_in_point_padding_seconds - 1.0) < 1e-3) {
130                 ui->in_padding_1_action->setChecked(true);
131         } else if (fabs(global_flags.cue_in_point_padding_seconds - 2.0) < 1e-3) {
132                 ui->in_padding_2_action->setChecked(true);
133         } else if (fabs(global_flags.cue_in_point_padding_seconds - 5.0) < 1e-3) {
134                 ui->in_padding_5_action->setChecked(true);
135         } else {
136                 // Nothing to check, which is fine.
137         }
138         connect(ui->in_padding_0_action, &QAction::toggled, bind(&MainWindow::in_padding_toggled, this, 0.0, _1));
139         connect(ui->in_padding_1_action, &QAction::toggled, bind(&MainWindow::in_padding_toggled, this, 1.0, _1));
140         connect(ui->in_padding_2_action, &QAction::toggled, bind(&MainWindow::in_padding_toggled, this, 2.0, _1));
141         connect(ui->in_padding_5_action, &QAction::toggled, bind(&MainWindow::in_padding_toggled, this, 5.0, _1));
142
143         // Same for the cue-out padding.
144         QActionGroup *out_padding_group = new QActionGroup(ui->out_padding_menu);
145         out_padding_group->addAction(ui->out_padding_0_action);
146         out_padding_group->addAction(ui->out_padding_1_action);
147         out_padding_group->addAction(ui->out_padding_2_action);
148         out_padding_group->addAction(ui->out_padding_5_action);
149         if (global_flags.cue_out_point_padding_seconds <= 1e-3) {
150                 ui->out_padding_0_action->setChecked(true);
151         } else if (fabs(global_flags.cue_out_point_padding_seconds - 1.0) < 1e-3) {
152                 ui->out_padding_1_action->setChecked(true);
153         } else if (fabs(global_flags.cue_out_point_padding_seconds - 2.0) < 1e-3) {
154                 ui->out_padding_2_action->setChecked(true);
155         } else if (fabs(global_flags.cue_out_point_padding_seconds - 5.0) < 1e-3) {
156                 ui->out_padding_5_action->setChecked(true);
157         } else {
158                 // Nothing to check, which is fine.
159         }
160         connect(ui->out_padding_0_action, &QAction::toggled, bind(&MainWindow::out_padding_toggled, this, 0.0, _1));
161         connect(ui->out_padding_1_action, &QAction::toggled, bind(&MainWindow::out_padding_toggled, this, 1.0, _1));
162         connect(ui->out_padding_2_action, &QAction::toggled, bind(&MainWindow::out_padding_toggled, this, 2.0, _1));
163         connect(ui->out_padding_5_action, &QAction::toggled, bind(&MainWindow::out_padding_toggled, this, 5.0, _1));
164
165         global_disk_space_estimator = new DiskSpaceEstimator(bind(&MainWindow::report_disk_space, this, _1, _2));
166         disk_free_label = new QLabel(this);
167         disk_free_label->setStyleSheet("QLabel {padding-right: 5px;}");
168         ui->menuBar->setCornerWidget(disk_free_label);
169
170         StateProto state = db.get_state();
171         undo_stack.push_back(state);  // The undo stack always has the current state on top.
172
173         cliplist_clips = new ClipList(state.clip_list());
174         ui->clip_list->setModel(cliplist_clips);
175         connect(cliplist_clips, &ClipList::any_content_changed, this, &MainWindow::content_changed);
176
177         playlist_clips = new PlayList(state.play_list());
178         ui->playlist->setModel(playlist_clips);
179         connect(playlist_clips, &PlayList::any_content_changed, this, &MainWindow::content_changed);
180
181         // For un-highlighting when we lose focus.
182         ui->clip_list->installEventFilter(this);
183
184         // For scrubbing in the pts columns.
185         ui->clip_list->viewport()->installEventFilter(this);
186         ui->playlist->viewport()->installEventFilter(this);
187
188         QShortcut *cue_in = new QShortcut(QKeySequence(Qt::Key_A), this);
189         connect(cue_in, &QShortcut::activated, ui->cue_in_btn, &QPushButton::click);
190         connect(ui->cue_in_btn, &QPushButton::clicked, this, &MainWindow::cue_in_clicked);
191
192         QShortcut *cue_out = new QShortcut(QKeySequence(Qt::Key_S), this);
193         connect(cue_out, &QShortcut::activated, ui->cue_out_btn, &QPushButton::click);
194         connect(ui->cue_out_btn, &QPushButton::clicked, this, &MainWindow::cue_out_clicked);
195
196         QShortcut *queue = new QShortcut(QKeySequence(Qt::Key_Q), this);
197         connect(queue, &QShortcut::activated, ui->queue_btn, &QPushButton::click);
198         connect(ui->queue_btn, &QPushButton::clicked, this, &MainWindow::queue_clicked);
199
200         QShortcut *preview = new QShortcut(QKeySequence(Qt::Key_W), this);
201         connect(preview, &QShortcut::activated, ui->preview_btn, &QPushButton::click);
202         connect(ui->preview_btn, &QPushButton::clicked, this, &MainWindow::preview_clicked);
203
204         QShortcut *play = new QShortcut(QKeySequence(Qt::Key_Space), this);
205         connect(play, &QShortcut::activated, ui->play_btn, &QPushButton::click);
206         connect(ui->play_btn, &QPushButton::clicked, this, &MainWindow::play_clicked);
207
208         QShortcut *next = new QShortcut(QKeySequence(Qt::Key_N), this);
209         connect(next, &QShortcut::activated, ui->next_btn, &QPushButton::click);
210         connect(ui->next_btn, &QPushButton::clicked, this, &MainWindow::next_clicked);
211
212         connect(ui->stop_btn, &QPushButton::clicked, this, &MainWindow::stop_clicked);
213         ui->stop_btn->setEnabled(false);
214
215         connect(ui->speed_slider, &QAbstractSlider::valueChanged, this, &MainWindow::speed_slider_changed);
216         connect(ui->speed_lock_btn, &QPushButton::clicked, this, &MainWindow::speed_lock_clicked);
217
218         connect(ui->playlist_duplicate_btn, &QPushButton::clicked, this, &MainWindow::playlist_duplicate);
219
220         connect(ui->playlist_remove_btn, &QPushButton::clicked, this, &MainWindow::playlist_remove);
221         QShortcut *delete_key = new QShortcut(QKeySequence(Qt::Key_Delete), ui->playlist);
222         connect(delete_key, &QShortcut::activated, [this] {
223                 if (ui->playlist->hasFocus()) {
224                         playlist_remove();
225                 }
226         });
227
228         // TODO: support drag-and-drop.
229         connect(ui->playlist_move_up_btn, &QPushButton::clicked, [this] { playlist_move(-1); });
230         connect(ui->playlist_move_down_btn, &QPushButton::clicked, [this] { playlist_move(1); });
231
232         connect(ui->playlist->selectionModel(), &QItemSelectionModel::selectionChanged,
233                 this, &MainWindow::playlist_selection_changed);
234         playlist_selection_changed();  // First time set-up.
235
236         preview_player.reset(new Player(ui->preview_display, Player::NO_STREAM_OUTPUT));
237         preview_player->set_done_callback([this] {
238                 post_to_main_thread([this] {
239                         preview_player_done();
240                 });
241         });
242
243         live_player.reset(new Player(ui->live_display, Player::HTTPD_STREAM_OUTPUT));
244         live_player->set_done_callback([this] {
245                 post_to_main_thread([this] {
246                         live_player_done();
247                 });
248         });
249         live_player->set_progress_callback([this](const map<uint64_t, double> &progress, TimeRemaining time_remaining) {
250                 post_to_main_thread([this, progress, time_remaining] {
251                         live_player_clip_progress(progress, time_remaining);
252                 });
253         });
254         set_output_status("paused");
255         enable_or_disable_queue_button();
256
257         defer_timeout = new QTimer(this);
258         defer_timeout->setSingleShot(true);
259         connect(defer_timeout, &QTimer::timeout, this, &MainWindow::defer_timer_expired);
260         ui->undo_action->setEnabled(true);
261
262         lock_blink_timeout = new QTimer(this);
263         lock_blink_timeout->setSingleShot(true);
264         connect(lock_blink_timeout, &QTimer::timeout, this, &MainWindow::lock_blink_timer_expired);
265
266         connect(ui->clip_list->selectionModel(), &QItemSelectionModel::currentChanged,
267                 this, &MainWindow::clip_list_selection_changed);
268         enable_or_disable_queue_button();
269
270         // Find out how many cameras we have in the existing frames;
271         // if none, we start with two cameras.
272         num_cameras = 2;
273         {
274                 lock_guard<mutex> lock(frame_mu);
275                 for (size_t stream_idx = 2; stream_idx < MAX_STREAMS; ++stream_idx) {
276                         if (!frames[stream_idx].empty()) {
277                                 num_cameras = stream_idx + 1;
278                         }
279                 }
280         }
281         change_num_cameras();
282
283         if (!global_flags.tally_url.empty()) {
284                 start_tally();
285         }
286
287         if (!global_flags.midi_mapping_filename.empty()) {
288                 MIDIMappingProto midi_mapping;
289                 if (!load_midi_mapping_from_file(global_flags.midi_mapping_filename, &midi_mapping)) {
290                         fprintf(stderr, "Couldn't load MIDI mapping '%s'; exiting.\n",
291                                 global_flags.midi_mapping_filename.c_str());
292                         abort();
293                 }
294                 midi_mapper.set_midi_mapping(midi_mapping);
295         }
296         midi_mapper.refresh_lights();
297         midi_mapper.start_thread();
298 }
299
300 void MainWindow::change_num_cameras()
301 {
302         assert(num_cameras >= displays.size());  // We only add, never remove.
303
304         // Make new entries to hide the displays.
305         for (unsigned i = displays.size(); i < num_cameras; ++i) {
306                 char title[256];
307                 snprintf(title, sizeof(title), "Camera %u", i + 1);
308                 QAction *hide_action = ui->hide_camera_menu->addAction(title);
309                 hide_action->setCheckable(true);
310                 hide_action->setChecked(false);
311                 connect(hide_action, &QAction::toggled, bind(&MainWindow::hide_camera_toggled, this, i, _1));
312         }
313
314         // Make new display rows.
315         for (unsigned i = displays.size(); i < num_cameras; ++i) {
316                 QFrame *frame = new QFrame(this);
317                 frame->setAutoFillBackground(true);
318
319                 QLayout *layout = new QGridLayout(frame);
320                 frame->setLayout(layout);
321                 layout->setContentsMargins(3, 3, 3, 3);
322
323                 JPEGFrameView *display = new JPEGFrameView(frame);
324                 display->setAutoFillBackground(true);
325                 layout->addWidget(display);
326
327                 display->set_overlay(to_string(i + 1));
328
329                 QPushButton *preview_btn = new QPushButton(this);
330                 preview_btn->setMaximumSize(20, 17);
331                 preview_btn->setText(QString::fromStdString(to_string(i + 1)));
332                 ui->preview_layout->addWidget(preview_btn);
333
334                 displays.emplace_back(FrameAndDisplay{ frame, display, preview_btn, /*hidden=*/false });
335
336                 connect(display, &JPEGFrameView::clicked, preview_btn, &QPushButton::click);
337                 QShortcut *shortcut = new QShortcut(QKeySequence(Qt::Key_1 + i), this);
338                 connect(shortcut, &QShortcut::activated, preview_btn, &QPushButton::click);
339
340                 connect(preview_btn, &QPushButton::clicked, [this, i] { preview_angle_clicked(i); });
341         }
342         relayout_displays();
343
344         cliplist_clips->change_num_cameras(num_cameras);
345         playlist_clips->change_num_cameras(num_cameras);
346
347         QMetaObject::invokeMethod(this, "relayout", Qt::QueuedConnection);
348 }
349
350 void MainWindow::relayout_displays()
351 {
352         while (ui->input_displays->count() > 0) {
353                 QLayoutItem *item = ui->input_displays->takeAt(0);
354                 ui->input_displays->removeWidget(item->widget());
355         }
356
357         unsigned cell_idx = 0;
358         for (unsigned i = 0; i < displays.size(); ++i) {
359                 if (displays[i].hidden) {
360                         displays[i].frame->setVisible(false);
361                 } else {
362                         displays[i].frame->setVisible(true);
363                         ui->input_displays->addWidget(displays[i].frame, cell_idx / 2, cell_idx % 2);
364                         ++cell_idx;
365                 }
366         }
367         ui->video_displays->setStretch(1, (cell_idx + 1) / 2);
368
369         QMetaObject::invokeMethod(this, "relayout", Qt::QueuedConnection);
370 }
371
372 MainWindow::~MainWindow()
373 {
374         // We don't have a context to release Player's OpenGL resources in here,
375         // so instead of crashing on exit, leak it.
376         live_player.release();
377         preview_player.release();
378 }
379
380 void MainWindow::cue_in_clicked()
381 {
382         if (!cliplist_clips->empty() && cliplist_clips->back()->pts_out < 0) {
383                 cliplist_clips->mutable_back()->pts_in = current_pts;
384         } else {
385                 Clip clip;
386                 clip.pts_in = max<int64_t>(current_pts - lrint(global_flags.cue_in_point_padding_seconds * TIMEBASE), 0);
387                 cliplist_clips->add_clip(clip);
388                 playlist_selection_changed();
389         }
390
391         // Show the clip in the preview.
392         unsigned stream_idx = ui->preview_display->get_stream_idx();
393         preview_single_frame(cliplist_clips->mutable_back()->pts_in, stream_idx, FIRST_AT_OR_AFTER);
394
395         // Select the item so that we can jog it.
396         ui->clip_list->setFocus();
397         QModelIndex index = cliplist_clips->index(cliplist_clips->size() - 1, int(ClipList::Column::IN));
398         ui->clip_list->selectionModel()->setCurrentIndex(index, QItemSelectionModel::ClearAndSelect);
399         ui->clip_list->scrollToBottom();
400         enable_or_disable_queue_button();
401 }
402
403 void MainWindow::cue_out_clicked()
404 {
405         if (cliplist_clips->empty()) {
406                 return;
407         }
408
409         cliplist_clips->mutable_back()->pts_out = current_pts + lrint(global_flags.cue_out_point_padding_seconds * TIMEBASE);
410
411         // Show the clip in the preview. (TODO: This won't take padding into account.)
412         unsigned stream_idx = ui->preview_display->get_stream_idx();
413         preview_single_frame(cliplist_clips->mutable_back()->pts_out, stream_idx, LAST_BEFORE);
414
415         // Select the item so that we can jog it.
416         ui->clip_list->setFocus();
417         QModelIndex index = cliplist_clips->index(cliplist_clips->size() - 1, int(ClipList::Column::OUT));
418         ui->clip_list->selectionModel()->setCurrentIndex(index, QItemSelectionModel::ClearAndSelect);
419         ui->clip_list->scrollToBottom();
420         enable_or_disable_queue_button();
421 }
422
423 void MainWindow::queue_clicked()
424 {
425         // See also enable_or_disable_queue_button().
426
427         if (cliplist_clips->empty()) {
428                 return;
429         }
430
431         QItemSelectionModel *selected = ui->clip_list->selectionModel();
432         if (!selected->hasSelection()) {
433                 Clip clip = *cliplist_clips->back();
434                 clip.stream_idx = 0;
435                 playlist_clips->add_clip(clip);
436                 playlist_selection_changed();
437                 ui->playlist->scrollToBottom();
438                 return;
439         }
440
441         QModelIndex index = selected->currentIndex();
442         Clip clip = *cliplist_clips->clip(index.row());
443         if (cliplist_clips->is_camera_column(index.column())) {
444                 clip.stream_idx = index.column() - int(ClipList::Column::CAMERA_1);
445         } else {
446                 clip.stream_idx = ui->preview_display->get_stream_idx();
447         }
448         if (clip.pts_out == -1) {
449                 clip.pts_out = clip.pts_in + int64_t(TIMEBASE) * 86400 * 7;  // One week; effectively infinite, but without overflow issues.
450         }
451
452         playlist_clips->add_clip(clip);
453         playlist_selection_changed();
454         ui->playlist->scrollToBottom();
455         if (!ui->playlist->selectionModel()->hasSelection()) {
456                 // TODO: Figure out why this doesn't always seem to actually select the row.
457                 QModelIndex bottom = playlist_clips->index(playlist_clips->size() - 1, 0);
458                 ui->playlist->setCurrentIndex(bottom);
459         }
460 }
461
462 void MainWindow::preview_clicked()
463 {
464         // See also enable_or_disable_preview_button().
465
466         if (ui->playlist->hasFocus()) {
467                 // Allow the playlist as preview iff it has focus and something is selected.
468                 QItemSelectionModel *selected = ui->playlist->selectionModel();
469                 if (selected->hasSelection()) {
470                         QModelIndex index = selected->currentIndex();
471                         const Clip &clip = *playlist_clips->clip(index.row());
472                         preview_player->play(clip);
473                         preview_playing = true;
474                         enable_or_disable_preview_button();
475                         return;
476                 }
477         }
478
479         if (cliplist_clips->empty())
480                 return;
481
482         QItemSelectionModel *selected = ui->clip_list->selectionModel();
483         if (!selected->hasSelection()) {
484                 preview_player->play(*cliplist_clips->back());
485                 preview_playing = true;
486                 enable_or_disable_preview_button();
487                 return;
488         }
489
490         QModelIndex index = selected->currentIndex();
491         Clip clip = *cliplist_clips->clip(index.row());
492         if (cliplist_clips->is_camera_column(index.column())) {
493                 clip.stream_idx = index.column() - int(ClipList::Column::CAMERA_1);
494         } else {
495                 clip.stream_idx = ui->preview_display->get_stream_idx();
496         }
497         if (clip.pts_out == -1) {
498                 clip.pts_out = clip.pts_in + int64_t(TIMEBASE) * 86400 * 7;  // One week; effectively infinite, but without overflow issues.
499         }
500         preview_player->play(clip);
501         preview_playing = true;
502         enable_or_disable_preview_button();
503 }
504
505 void MainWindow::preview_angle_clicked(unsigned stream_idx)
506 {
507         preview_player->override_angle(stream_idx);
508
509         // Change the selection if we were previewing a clip from the clip list.
510         // (The only other thing we could be showing is a pts scrub, and if so,
511         // that would be selected.)
512         QItemSelectionModel *selected = ui->clip_list->selectionModel();
513         if (selected->hasSelection()) {
514                 QModelIndex cell = selected->selectedIndexes()[0];
515                 int column = int(ClipList::Column::CAMERA_1) + stream_idx;
516                 selected->setCurrentIndex(cell.sibling(cell.row(), column), QItemSelectionModel::ClearAndSelect);
517         }
518 }
519
520 void MainWindow::playlist_duplicate()
521 {
522         QItemSelectionModel *selected = ui->playlist->selectionModel();
523         if (!selected->hasSelection()) {
524                 // Should have been grayed out, but OK.
525                 return;
526         }
527         QModelIndexList rows = selected->selectedRows();
528         int first = rows.front().row(), last = rows.back().row();
529         playlist_clips->duplicate_clips(first, last);
530         playlist_selection_changed();
531 }
532
533 void MainWindow::playlist_remove()
534 {
535         QItemSelectionModel *selected = ui->playlist->selectionModel();
536         if (!selected->hasSelection()) {
537                 // Should have been grayed out, but OK.
538                 return;
539         }
540         QModelIndexList rows = selected->selectedRows();
541         int first = rows.front().row(), last = rows.back().row();
542         playlist_clips->erase_clips(first, last);
543
544         // TODO: select the next one in the list?
545
546         playlist_selection_changed();
547 }
548
549 void MainWindow::playlist_move(int delta)
550 {
551         QItemSelectionModel *selected = ui->playlist->selectionModel();
552         if (!selected->hasSelection()) {
553                 // Should have been grayed out, but OK.
554                 return;
555         }
556
557         QModelIndexList rows = selected->selectedRows();
558         int first = rows.front().row(), last = rows.back().row();
559         if ((delta == -1 && first == 0) ||
560             (delta == 1 && size_t(last) == playlist_clips->size() - 1)) {
561                 // Should have been grayed out, but OK.
562                 return;
563         }
564
565         playlist_clips->move_clips(first, last, delta);
566         playlist_selection_changed();
567 }
568
569 void MainWindow::jog_internal(JogDestination jog_destination, int row, int column, int stream_idx, int pts_delta)
570 {
571         constexpr int camera_pts_per_pixel = 1500;  // One click of most mice (15 degrees), multiplied by the default wheel_sensitivity.
572
573         int in_column, out_column, camera_column;
574         if (jog_destination == JOG_CLIP_LIST) {
575                 in_column = int(ClipList::Column::IN);
576                 out_column = int(ClipList::Column::OUT);
577                 camera_column = -1;
578         } else if (jog_destination == JOG_PLAYLIST) {
579                 in_column = int(PlayList::Column::IN);
580                 out_column = int(PlayList::Column::OUT);
581                 camera_column = int(PlayList::Column::CAMERA);
582         } else {
583                 assert(false);
584         }
585
586         currently_deferring_model_changes = true;
587         {
588                 current_change_id = (jog_destination == JOG_CLIP_LIST) ? "cliplist:" : "playlist:";
589                 ClipProxy clip = (jog_destination == JOG_CLIP_LIST) ? cliplist_clips->mutable_clip(row) : playlist_clips->mutable_clip(row);
590                 if (jog_destination == JOG_PLAYLIST) {
591                         stream_idx = clip->stream_idx;
592                 }
593
594                 if (column == in_column) {
595                         current_change_id += "in:" + to_string(row);
596                         int64_t pts = clip->pts_in + pts_delta;
597                         set_pts_in(pts, current_pts, clip);
598                         preview_single_frame(pts, stream_idx, FIRST_AT_OR_AFTER);
599                 } else if (column == out_column) {
600                         current_change_id += "out:" + to_string(row);
601                         int64_t pts = clip->pts_out + pts_delta;
602                         pts = std::max(pts, clip->pts_in);
603                         pts = std::min(pts, current_pts);
604                         clip->pts_out = pts;
605                         preview_single_frame(pts, stream_idx, LAST_BEFORE);
606                 } else if (column == camera_column) {
607                         current_change_id += "camera:" + to_string(row);
608                         int angle_degrees = pts_delta;
609                         if (last_mousewheel_camera_row == row) {
610                                 angle_degrees += leftover_angle_degrees;
611                         }
612
613                         int stream_idx = clip->stream_idx + angle_degrees / camera_pts_per_pixel;
614                         stream_idx = std::max(stream_idx, 0);
615                         stream_idx = std::min<int>(stream_idx, num_cameras - 1);
616                         clip->stream_idx = stream_idx;
617
618                         last_mousewheel_camera_row = row;
619                         leftover_angle_degrees = angle_degrees % camera_pts_per_pixel;
620
621                         // Don't update the live view, that's rarely what the operator wants.
622                 }
623         }
624         currently_deferring_model_changes = false;
625 }
626
627 void MainWindow::defer_timer_expired()
628 {
629         state_changed(deferred_state);
630 }
631
632 void MainWindow::content_changed()
633 {
634         // If we are playing, update the part of the playlist that's not playing yet.
635         vector<ClipWithID> clips;
636         for (unsigned row = 0; row < playlist_clips->size(); ++row) {
637                 clips.emplace_back(*playlist_clips->clip_with_id(row));
638         }
639         live_player->splice_play(clips);
640
641         // Serialize the state.
642         if (defer_timeout->isActive() &&
643             (!currently_deferring_model_changes || deferred_change_id != current_change_id)) {
644                 // There's some deferred event waiting, but this event is unrelated.
645                 // So it's time to short-circuit that timer and do the work it wanted to do.
646                 defer_timeout->stop();
647                 state_changed(deferred_state);
648         }
649         StateProto state;
650         *state.mutable_clip_list() = cliplist_clips->serialize();
651         *state.mutable_play_list() = playlist_clips->serialize();
652         if (currently_deferring_model_changes) {
653                 deferred_change_id = current_change_id;
654                 deferred_state = std::move(state);
655                 defer_timeout->start(200);
656                 return;
657         }
658         state_changed(state);
659 }
660
661 void MainWindow::state_changed(const StateProto &state)
662 {
663         db.store_state(state);
664
665         redo_stack.clear();
666         ui->redo_action->setEnabled(false);
667
668         undo_stack.push_back(state);
669         ui->undo_action->setEnabled(undo_stack.size() > 1);
670
671         // Make sure it doesn't grow without bounds.
672         while (undo_stack.size() >= 100) {
673                 undo_stack.pop_front();
674         }
675 }
676
677 void MainWindow::save_settings()
678 {
679         SettingsProto settings;
680         settings.set_interpolation_quality(global_flags.interpolation_quality + 1);
681         settings.set_cue_in_point_padding_seconds(global_flags.cue_in_point_padding_seconds);
682         settings.set_cue_out_point_padding_seconds(global_flags.cue_out_point_padding_seconds);
683         db.store_settings(settings);
684 }
685
686 void MainWindow::lock_blink_timer_expired()
687 {
688         midi_mapper.set_locked(MIDIMapper::LightState(ui->speed_lock_btn->isChecked()));  // Presumably On, or the timer should have been canceled.
689 }
690
691 void MainWindow::play_clicked()
692 {
693         QItemSelectionModel *selected = ui->playlist->selectionModel();
694         if (!selected->hasSelection()) {
695                 return;
696         }
697         unsigned start_row = selected->selectedRows(0)[0].row();
698
699         vector<ClipWithID> clips;
700         for (unsigned row = start_row; row < playlist_clips->size(); ++row) {
701                 ClipWithID clip = *playlist_clips->clip_with_id(row);
702                 if (clip.clip.pts_out == -1) {
703                         clip.clip.pts_out = clip.clip.pts_in + int64_t(TIMEBASE) * 86400 * 7;  // One week; effectively infinite, but without overflow issues.
704                 }
705                 clips.emplace_back(clip);
706         }
707         live_player->play(clips);
708         playlist_clips->set_progress({ { start_row, 0.0f } });
709         ui->playlist->selectionModel()->clear();
710         ui->stop_btn->setEnabled(true);
711         playlist_selection_changed();
712 }
713
714 void MainWindow::next_clicked()
715 {
716         live_player->skip_to_next();
717 }
718
719 void MainWindow::stop_clicked()
720 {
721         Clip fake_clip;
722         fake_clip.pts_in = 0;
723         fake_clip.pts_out = 0;
724         playlist_clips->set_progress({});
725         live_player->play(fake_clip);
726         ui->stop_btn->setEnabled(false);
727         playlist_selection_changed();
728 }
729
730 void MainWindow::speed_slider_changed(int percent)
731 {
732         float speed = percent / 100.0f;
733         ui->speed_lock_btn->setText(QString::fromStdString(" " + to_string(percent) + "%"));
734         live_player->set_master_speed(speed);
735         midi_mapper.set_speed_light(speed);
736 }
737
738 void MainWindow::speed_lock_clicked()
739 {
740         // TODO: Make for a less abrupt transition if we're not already at 100%.
741         ui->speed_slider->setValue(100);  // Also actually sets the master speed and updates the label.
742         ui->speed_slider->setEnabled(!ui->speed_lock_btn->isChecked());
743         midi_mapper.set_locked(MIDIMapper::LightState(ui->speed_lock_btn->isChecked()));
744         lock_blink_timeout->stop();
745 }
746
747 void MainWindow::preview_player_done()
748 {
749         preview_playing = false;
750         enable_or_disable_preview_button();
751 }
752
753 void MainWindow::live_player_done()
754 {
755         playlist_clips->set_progress({});
756         ui->stop_btn->setEnabled(false);
757         playlist_selection_changed();
758 }
759
760 void MainWindow::live_player_clip_progress(const map<uint64_t, double> &progress, TimeRemaining time_remaining)
761 {
762         playlist_clips->set_progress(progress);
763         set_output_status(format_duration(time_remaining) + " left");
764 }
765
766 void MainWindow::resizeEvent(QResizeEvent *event)
767 {
768         QMainWindow::resizeEvent(event);
769
770         // Ask for a relayout, but only after the event loop is done doing relayout
771         // on everything else.
772         QMetaObject::invokeMethod(this, "relayout", Qt::QueuedConnection);
773 }
774
775 void MainWindow::relayout()
776 {
777         ui->live_display->setMinimumWidth(ui->live_display->height() * 16 / 9);
778         ui->preview_display->setMinimumWidth(ui->preview_display->height() * 16 / 9);
779 }
780
781 bool MainWindow::eventFilter(QObject *watched, QEvent *event)
782 {
783         constexpr int dead_zone_pixels = 3;  // To avoid that simple clicks get misinterpreted.
784         int scrub_sensitivity = 100;  // pts units per pixel.
785         int wheel_sensitivity = 100;  // pts units per degree.
786
787         if (event->type() == QEvent::FocusIn || event->type() == QEvent::FocusOut) {
788                 enable_or_disable_preview_button();
789                 playlist_selection_changed();
790                 hidden_jog_column = -1;
791         }
792
793         unsigned stream_idx = ui->preview_display->get_stream_idx();
794
795         if (watched == ui->clip_list) {
796                 if (event->type() == QEvent::FocusOut) {
797                         highlight_camera_input(-1);
798                 }
799                 return false;
800         }
801
802         if (event->type() != QEvent::Wheel) {
803                 last_mousewheel_camera_row = -1;
804         }
805
806         if (event->type() == QEvent::MouseButtonPress) {
807                 QMouseEvent *mouse = (QMouseEvent *)event;
808
809                 QTableView *destination;
810                 ScrubType type;
811
812                 if (watched == ui->clip_list->viewport()) {
813                         destination = ui->clip_list;
814                         type = SCRUBBING_CLIP_LIST;
815                 } else if (watched == ui->playlist->viewport()) {
816                         destination = ui->playlist;
817                         type = SCRUBBING_PLAYLIST;
818                 } else {
819                         return false;
820                 }
821                 int column = destination->columnAt(mouse->x());
822                 int row = destination->rowAt(mouse->y());
823                 if (column == -1 || row == -1)
824                         return false;
825
826                 if (type == SCRUBBING_CLIP_LIST) {
827                         if (ClipList::Column(column) == ClipList::Column::IN) {
828                                 scrub_pts_origin = cliplist_clips->clip(row)->pts_in;
829                                 preview_single_frame(scrub_pts_origin, stream_idx, FIRST_AT_OR_AFTER);
830                         } else if (ClipList::Column(column) == ClipList::Column::OUT) {
831                                 scrub_pts_origin = cliplist_clips->clip(row)->pts_out;
832                                 preview_single_frame(scrub_pts_origin, stream_idx, LAST_BEFORE);
833                         } else {
834                                 return false;
835                         }
836                 } else {
837                         if (PlayList::Column(column) == PlayList::Column::IN) {
838                                 scrub_pts_origin = playlist_clips->clip(row)->pts_in;
839                                 preview_single_frame(scrub_pts_origin, stream_idx, FIRST_AT_OR_AFTER);
840                         } else if (PlayList::Column(column) == PlayList::Column::OUT) {
841                                 scrub_pts_origin = playlist_clips->clip(row)->pts_out;
842                                 preview_single_frame(scrub_pts_origin, stream_idx, LAST_BEFORE);
843                         } else {
844                                 return false;
845                         }
846                 }
847
848                 scrubbing = true;
849                 scrub_row = row;
850                 scrub_column = column;
851                 scrub_x_origin = mouse->x();
852                 scrub_type = type;
853         } else if (event->type() == QEvent::MouseMove) {
854                 QMouseEvent *mouse = (QMouseEvent *)event;
855                 if (mouse->modifiers() & Qt::KeyboardModifier::ShiftModifier) {
856                         scrub_sensitivity *= 10;
857                         wheel_sensitivity *= 10;
858                         if (mouse->modifiers() & Qt::KeyboardModifier::ControlModifier) {
859                                 // Ctrl+Shift is a super-modifier, meant only for things like “go back two hours”.
860                                 scrub_sensitivity *= 100;
861                                 wheel_sensitivity *= 100;
862                         }
863                 }
864                 if (mouse->modifiers() & Qt::KeyboardModifier::AltModifier) {  // Note: Shift + Alt cancel each other out.
865                         scrub_sensitivity /= 10;
866                         wheel_sensitivity /= 10;
867                 }
868                 if (scrubbing) {
869                         int offset = mouse->x() - scrub_x_origin;
870                         int adjusted_offset;
871                         if (offset >= dead_zone_pixels) {
872                                 adjusted_offset = offset - dead_zone_pixels;
873                         } else if (offset < -dead_zone_pixels) {
874                                 adjusted_offset = offset + dead_zone_pixels;
875                         } else {
876                                 adjusted_offset = 0;
877                         }
878
879                         int64_t pts = scrub_pts_origin + adjusted_offset * scrub_sensitivity;
880                         currently_deferring_model_changes = true;
881                         if (scrub_type == SCRUBBING_CLIP_LIST) {
882                                 ClipProxy clip = cliplist_clips->mutable_clip(scrub_row);
883                                 if (scrub_column == int(ClipList::Column::IN)) {
884                                         current_change_id = "cliplist:in:" + to_string(scrub_row);
885                                         set_pts_in(pts, current_pts, clip);
886                                         preview_single_frame(pts, stream_idx, FIRST_AT_OR_AFTER);
887                                 } else {
888                                         current_change_id = "cliplist:out" + to_string(scrub_row);
889                                         pts = std::max(pts, clip->pts_in);
890                                         pts = std::min(pts, current_pts);
891                                         clip->pts_out = pts;
892                                         preview_single_frame(pts, stream_idx, LAST_BEFORE);
893                                 }
894                         } else {
895                                 ClipProxy clip = playlist_clips->mutable_clip(scrub_row);
896                                 if (scrub_column == int(PlayList::Column::IN)) {
897                                         current_change_id = "playlist:in:" + to_string(scrub_row);
898                                         set_pts_in(pts, current_pts, clip);
899                                         preview_single_frame(pts, clip->stream_idx, FIRST_AT_OR_AFTER);
900                                 } else {
901                                         current_change_id = "playlist:out:" + to_string(scrub_row);
902                                         pts = std::max(pts, clip->pts_in);
903                                         pts = std::min(pts, current_pts);
904                                         clip->pts_out = pts;
905                                         preview_single_frame(pts, clip->stream_idx, LAST_BEFORE);
906                                 }
907                         }
908                         currently_deferring_model_changes = false;
909
910                         return true;  // Don't use this mouse movement for selecting things.
911                 }
912         } else if (event->type() == QEvent::Wheel) {
913                 QWheelEvent *wheel = (QWheelEvent *)event;
914                 int angle_delta = wheel->angleDelta().y();
915                 if (wheel->modifiers() & Qt::KeyboardModifier::ShiftModifier) {
916                         scrub_sensitivity *= 10;
917                         wheel_sensitivity *= 10;
918                         if (wheel->modifiers() & Qt::KeyboardModifier::ControlModifier) {
919                                 // Ctrl+Shift is a super-modifier, meant only for things like “go back two hours”.
920                                 scrub_sensitivity *= 100;
921                                 wheel_sensitivity *= 100;
922                         }
923                 }
924                 if (wheel->modifiers() & Qt::KeyboardModifier::AltModifier) {  // Note: Shift + Alt cancel each other out.
925                         scrub_sensitivity /= 10;
926                         wheel_sensitivity /= 10;
927                         angle_delta = wheel->angleDelta().x();  // Qt ickiness.
928                 }
929
930                 QTableView *destination;
931                 JogDestination jog_destination;
932                 if (watched == ui->clip_list->viewport()) {
933                         destination = ui->clip_list;
934                         jog_destination = JOG_CLIP_LIST;
935                         last_mousewheel_camera_row = -1;
936                 } else if (watched == ui->playlist->viewport()) {
937                         destination = ui->playlist;
938                         jog_destination = JOG_PLAYLIST;
939                         if (destination->columnAt(wheel->x()) != int(PlayList::Column::CAMERA)) {
940                                 last_mousewheel_camera_row = -1;
941                         }
942                 } else {
943                         last_mousewheel_camera_row = -1;
944                         return false;
945                 }
946
947                 int column = destination->columnAt(wheel->x());
948                 int row = destination->rowAt(wheel->y());
949                 if (column == -1 || row == -1)
950                         return false;
951
952                 // Only adjust pts with the wheel if the given row is selected.
953                 if (!destination->hasFocus() ||
954                     row != destination->selectionModel()->currentIndex().row()) {
955                         return false;
956                 }
957
958                 jog_internal(jog_destination, row, column, stream_idx, angle_delta * wheel_sensitivity);
959                 return true;  // Don't scroll.
960         } else if (event->type() == QEvent::MouseButtonRelease) {
961                 scrubbing = false;
962         }
963         return false;
964 }
965
966 void MainWindow::preview_single_frame(int64_t pts, unsigned stream_idx, MainWindow::Rounding rounding)
967 {
968         if (rounding == LAST_BEFORE) {
969                 lock_guard<mutex> lock(frame_mu);
970                 if (frames[stream_idx].empty())
971                         return;
972                 auto it = find_last_frame_before(frames[stream_idx], pts);
973                 if (it != frames[stream_idx].end()) {
974                         pts = it->pts;
975                 }
976         } else {
977                 assert(rounding == FIRST_AT_OR_AFTER);
978                 lock_guard<mutex> lock(frame_mu);
979                 if (frames[stream_idx].empty())
980                         return;
981                 auto it = find_first_frame_at_or_after(frames[stream_idx], pts);
982                 if (it != frames[stream_idx].end()) {
983                         pts = it->pts;
984                 }
985         }
986
987         Clip fake_clip;
988         fake_clip.pts_in = pts;
989         fake_clip.pts_out = pts + 1;
990         fake_clip.stream_idx = stream_idx;
991         preview_player->play(fake_clip);
992 }
993
994 void MainWindow::playlist_selection_changed()
995 {
996         enable_or_disable_preview_button();
997
998         QItemSelectionModel *selected = ui->playlist->selectionModel();
999         bool any_selected = selected->hasSelection();
1000         ui->playlist_duplicate_btn->setEnabled(any_selected);
1001         ui->playlist_remove_btn->setEnabled(any_selected);
1002         ui->playlist_move_up_btn->setEnabled(
1003                 any_selected && selected->selectedRows().front().row() > 0);
1004         ui->playlist_move_down_btn->setEnabled(
1005                 any_selected && selected->selectedRows().back().row() < int(playlist_clips->size()) - 1);
1006
1007         ui->play_btn->setEnabled(any_selected);
1008         ui->next_btn->setEnabled(ui->stop_btn->isEnabled());  // TODO: Perhaps not if we're on the last clip?
1009         midi_mapper.set_next_ready(ui->next_btn->isEnabled() ? MIDIMapper::On : MIDIMapper::Off);
1010
1011         // NOTE: The hidden button is still reachable by keyboard or MIDI.
1012         if (any_selected) {
1013                 ui->play_btn->setVisible(true);
1014         } else if (ui->stop_btn->isEnabled()) {  // Playing.
1015                 ui->play_btn->setVisible(false);
1016         } else {
1017                 ui->play_btn->setVisible(true);
1018         }
1019         ui->next_btn->setVisible(!ui->play_btn->isVisible());
1020
1021         if (ui->stop_btn->isEnabled()) {  // Playing.
1022                 midi_mapper.set_play_enabled(MIDIMapper::On);
1023         } else if (any_selected) {
1024                 midi_mapper.set_play_enabled(MIDIMapper::Blinking);
1025         } else {
1026                 midi_mapper.set_play_enabled(MIDIMapper::Off);
1027         }
1028
1029         if (!any_selected) {
1030                 set_output_status("paused");
1031         } else {
1032                 vector<ClipWithID> clips;
1033                 for (size_t row = selected->selectedRows().front().row(); row < playlist_clips->size(); ++row) {
1034                         clips.emplace_back(*playlist_clips->clip_with_id(row));
1035                 }
1036                 TimeRemaining remaining = compute_total_time(clips);
1037                 set_output_status(format_duration(remaining) + " ready");
1038         }
1039 }
1040
1041 void MainWindow::clip_list_selection_changed(const QModelIndex &current, const QModelIndex &previous)
1042 {
1043         int camera_selected = -1;
1044         if (cliplist_clips->is_camera_column(current.column())) {
1045                 camera_selected = current.column() - int(ClipList::Column::CAMERA_1);
1046
1047                 // See the comment on hidden_jog_column.
1048                 if (current.row() != previous.row()) {
1049                         hidden_jog_column = -1;
1050                 } else if (hidden_jog_column == -1) {
1051                         hidden_jog_column = previous.column();
1052                 }
1053         } else {
1054                 hidden_jog_column = -1;
1055         }
1056         highlight_camera_input(camera_selected);
1057         enable_or_disable_queue_button();
1058 }
1059
1060 void MainWindow::report_disk_space(off_t free_bytes, double estimated_seconds_left)
1061 {
1062         char time_str[256];
1063         if (estimated_seconds_left < 60.0) {
1064                 strcpy(time_str, "<font color=\"red\">Less than a minute</font>");
1065         } else if (estimated_seconds_left < 1800.0) {  // Less than half an hour: Xm Ys (red).
1066                 int s = lrintf(estimated_seconds_left);
1067                 int m = s / 60;
1068                 s %= 60;
1069                 snprintf(time_str, sizeof(time_str), "<font color=\"red\">%dm %ds</font>", m, s);
1070         } else if (estimated_seconds_left < 3600.0) {  // Less than an hour: Xm.
1071                 int m = lrintf(estimated_seconds_left / 60.0);
1072                 snprintf(time_str, sizeof(time_str), "%dm", m);
1073         } else if (estimated_seconds_left < 36000.0) {  // Less than ten hours: Xh Ym.
1074                 int m = lrintf(estimated_seconds_left / 60.0);
1075                 int h = m / 60;
1076                 m %= 60;
1077                 snprintf(time_str, sizeof(time_str), "%dh %dm", h, m);
1078         } else {  // More than ten hours: Xh.
1079                 int h = lrintf(estimated_seconds_left / 3600.0);
1080                 snprintf(time_str, sizeof(time_str), "%dh", h);
1081         }
1082         char buf[256];
1083         snprintf(buf, sizeof(buf), "Disk free: %'.0f MB (approx. %s)", free_bytes / 1048576.0, time_str);
1084
1085         std::string label = buf;
1086
1087         post_to_main_thread([this, label] {
1088                 disk_free_label->setText(QString::fromStdString(label));
1089                 ui->menuBar->setCornerWidget(disk_free_label);  // Need to set this again for the sizing to get right.
1090         });
1091 }
1092
1093 void MainWindow::midi_mapping_triggered()
1094 {
1095         MIDIMappingDialog(&midi_mapper).exec();
1096 }
1097
1098 void MainWindow::exit_triggered()
1099 {
1100         close();
1101 }
1102
1103 void MainWindow::export_cliplist_clip_multitrack_triggered()
1104 {
1105         QItemSelectionModel *selected = ui->clip_list->selectionModel();
1106         if (!selected->hasSelection()) {
1107                 QMessageBox msgbox;
1108                 msgbox.setText("No clip selected in the clip list. Select one and try exporting again.");
1109                 msgbox.exec();
1110                 return;
1111         }
1112
1113         QModelIndex index = selected->currentIndex();
1114         Clip clip = *cliplist_clips->clip(index.row());
1115         QString filename = QFileDialog::getSaveFileName(this,
1116                 "Export multitrack clip", QString(), tr("Matroska video files (*.mkv)"));
1117         if (filename.isNull()) {
1118                 // Cancel.
1119                 return;
1120         }
1121         if (!filename.endsWith(".mkv")) {
1122                 filename += ".mkv";
1123         }
1124         export_multitrack_clip(filename.toStdString(), clip);
1125 }
1126
1127 void MainWindow::export_playlist_clip_interpolated_triggered()
1128 {
1129         QItemSelectionModel *selected = ui->playlist->selectionModel();
1130         if (!selected->hasSelection()) {
1131                 QMessageBox msgbox;
1132                 msgbox.setText("No clip selected in the playlist. Select one and try exporting again.");
1133                 msgbox.exec();
1134                 return;
1135         }
1136
1137         QString filename = QFileDialog::getSaveFileName(this,
1138                 "Export interpolated clip", QString(), tr("Matroska video files (*.mkv)"));
1139         if (filename.isNull()) {
1140                 // Cancel.
1141                 return;
1142         }
1143         if (!filename.endsWith(".mkv")) {
1144                 filename += ".mkv";
1145         }
1146
1147         vector<Clip> clips;
1148         QModelIndexList rows = selected->selectedRows();
1149         for (QModelIndex index : rows) {
1150                 clips.push_back(*playlist_clips->clip(index.row()));
1151         }
1152         export_interpolated_clip(filename.toStdString(), clips);
1153 }
1154
1155 void MainWindow::manual_triggered()
1156 {
1157         if (!QDesktopServices::openUrl(QUrl("https://nageru.sesse.net/doc/"))) {
1158                 QMessageBox msgbox;
1159                 msgbox.setText("Could not launch manual in web browser.\nPlease see https://nageru.sesse.net/doc/ manually.");
1160                 msgbox.exec();
1161         }
1162 }
1163
1164 void MainWindow::about_triggered()
1165 {
1166         AboutDialog("Futatabi", "Multicamera slow motion video server").exec();
1167 }
1168
1169 void MainWindow::undo_triggered()
1170 {
1171         // Finish any deferred action.
1172         if (defer_timeout->isActive()) {
1173                 defer_timeout->stop();
1174                 state_changed(deferred_state);
1175         }
1176
1177         StateProto redo_state;
1178         *redo_state.mutable_clip_list() = cliplist_clips->serialize();
1179         *redo_state.mutable_play_list() = playlist_clips->serialize();
1180         redo_stack.push_back(std::move(redo_state));
1181         ui->redo_action->setEnabled(true);
1182
1183         assert(undo_stack.size() > 1);
1184
1185         // Pop off the current state, which is always at the top of the stack.
1186         undo_stack.pop_back();
1187
1188         StateProto state = undo_stack.back();
1189         ui->undo_action->setEnabled(undo_stack.size() > 1);
1190
1191         replace_model(ui->clip_list, &cliplist_clips, new ClipList(state.clip_list()));
1192         replace_model(ui->playlist, &playlist_clips, new PlayList(state.play_list()));
1193
1194         db.store_state(state);
1195 }
1196
1197 void MainWindow::redo_triggered()
1198 {
1199         assert(!redo_stack.empty());
1200
1201         ui->undo_action->setEnabled(true);
1202         ui->redo_action->setEnabled(true);
1203
1204         undo_stack.push_back(std::move(redo_stack.back()));
1205         redo_stack.pop_back();
1206         ui->undo_action->setEnabled(true);
1207         ui->redo_action->setEnabled(!redo_stack.empty());
1208
1209         const StateProto &state = undo_stack.back();
1210         replace_model(ui->clip_list, &cliplist_clips, new ClipList(state.clip_list()));
1211         replace_model(ui->playlist, &playlist_clips, new PlayList(state.play_list()));
1212
1213         db.store_state(state);
1214 }
1215
1216 void MainWindow::quality_toggled(int quality, bool checked)
1217 {
1218         if (!checked) {
1219                 return;
1220         }
1221         global_flags.interpolation_quality = quality;
1222         if (quality != 0 &&  // Turning interpolation off is always possible.
1223             quality != flow_initialized_interpolation_quality) {
1224                 QMessageBox msgbox;
1225                 msgbox.setText(QString::fromStdString(
1226                         "The interpolation quality for the main output cannot be changed at runtime, "
1227                         "except being turned completely off; it will take effect for exported files "
1228                         "only until next restart. The live output quality thus remains at " +
1229                         to_string(flow_initialized_interpolation_quality) + "."));
1230                 msgbox.exec();
1231         }
1232
1233         save_settings();
1234 }
1235
1236 void MainWindow::in_padding_toggled(double seconds, bool checked)
1237 {
1238         if (!checked) {
1239                 return;
1240         }
1241         global_flags.cue_in_point_padding_seconds = seconds;
1242         save_settings();
1243 }
1244
1245 void MainWindow::out_padding_toggled(double seconds, bool checked)
1246 {
1247         if (!checked) {
1248                 return;
1249         }
1250         global_flags.cue_out_point_padding_seconds = seconds;
1251         save_settings();
1252 }
1253
1254 void MainWindow::hide_camera_toggled(unsigned camera_idx, bool checked)
1255 {
1256         displays[camera_idx].hidden = checked;
1257         relayout_displays();
1258 }
1259
1260 void MainWindow::highlight_camera_input(int stream_idx)
1261 {
1262         for (unsigned i = 0; i < num_cameras; ++i) {
1263                 if (unsigned(stream_idx) == i) {
1264                         displays[i].frame->setStyleSheet("background: rgb(0,255,0)");
1265                 } else {
1266                         displays[i].frame->setStyleSheet("");
1267                 }
1268         }
1269         midi_mapper.highlight_camera_input(stream_idx);
1270 }
1271
1272 void MainWindow::enable_or_disable_preview_button()
1273 {
1274         // Follows the logic in preview_clicked().
1275
1276         if (ui->playlist->hasFocus()) {
1277                 // Allow the playlist as preview iff it has focus and something is selected.
1278                 // TODO: Is this part really relevant?
1279                 QItemSelectionModel *selected = ui->playlist->selectionModel();
1280                 if (selected->hasSelection()) {
1281                         ui->preview_btn->setEnabled(true);
1282                         midi_mapper.set_preview_enabled(preview_playing ? MIDIMapper::On : MIDIMapper::Blinking);
1283                         return;
1284                 }
1285         }
1286
1287         // TODO: Perhaps only enable this if something is actually selected.
1288         ui->preview_btn->setEnabled(!cliplist_clips->empty());
1289         if (preview_playing) {
1290                 midi_mapper.set_preview_enabled(MIDIMapper::On);
1291         } else {
1292                 midi_mapper.set_preview_enabled(cliplist_clips->empty() ? MIDIMapper::Off : MIDIMapper::Blinking);
1293         }
1294 }
1295
1296 void MainWindow::enable_or_disable_queue_button()
1297 {
1298         // Follows the logic in queue_clicked().
1299         // TODO: Perhaps only enable this if something is actually selected.
1300
1301         bool enabled;
1302
1303         if (cliplist_clips->empty()) {
1304                 enabled = false;
1305         } else {
1306                 enabled = true;
1307         }
1308
1309         ui->queue_btn->setEnabled(enabled);
1310         midi_mapper.set_queue_enabled(enabled);
1311 }
1312
1313 void MainWindow::set_output_status(const string &status)
1314 {
1315         ui->live_label->setText(QString::fromStdString("Current output (" + status + ")"));
1316         if (live_player != nullptr) {
1317                 live_player->set_pause_status(status);
1318         }
1319
1320         lock_guard<mutex> lock(queue_status_mu);
1321         queue_status = status;
1322 }
1323
1324 pair<string, string> MainWindow::get_queue_status() const
1325 {
1326         lock_guard<mutex> lock(queue_status_mu);
1327         return { queue_status, "text/plain" };
1328 }
1329
1330 void MainWindow::display_frame(unsigned stream_idx, const FrameOnDisk &frame)
1331 {
1332         if (stream_idx >= MAX_STREAMS) {
1333                 fprintf(stderr, "WARNING: Ignoring too-high stream index %u.\n", stream_idx);
1334                 return;
1335         }
1336         if (stream_idx >= num_cameras) {
1337                 post_to_main_thread_and_wait([this, stream_idx] {
1338                         num_cameras = stream_idx + 1;
1339                         change_num_cameras();
1340                 });
1341         }
1342         displays[stream_idx].display->setFrame(stream_idx, frame);
1343 }
1344
1345 void MainWindow::preview()
1346 {
1347         post_to_main_thread([this] {
1348                 preview_clicked();
1349         });
1350 }
1351
1352 void MainWindow::queue()
1353 {
1354         post_to_main_thread([this] {
1355                 queue_clicked();
1356         });
1357 }
1358
1359 void MainWindow::play()
1360 {
1361         post_to_main_thread([this] {
1362                 play_clicked();
1363         });
1364 }
1365
1366 void MainWindow::next()
1367 {
1368         post_to_main_thread([this] {
1369                 next_clicked();
1370         });
1371 }
1372
1373 void MainWindow::toggle_lock()
1374 {
1375         post_to_main_thread([this] {
1376                 ui->speed_lock_btn->setChecked(!ui->speed_lock_btn->isChecked());
1377                 speed_lock_clicked();
1378         });
1379 }
1380
1381 void MainWindow::jog(int delta)
1382 {
1383         post_to_main_thread([this, delta] {
1384                 int64_t pts_delta = delta * (TIMEBASE / 60);  // One click = frame at 60 fps.
1385                 if (ui->playlist->hasFocus()) {
1386                         QModelIndex selected = ui->playlist->selectionModel()->currentIndex();
1387                         if (selected.column() != -1 && selected.row() != -1) {
1388                                 jog_internal(JOG_PLAYLIST, selected.row(), selected.column(), /*stream_idx=*/-1, pts_delta);
1389                         }
1390                 } else if (ui->clip_list->hasFocus()) {
1391                         QModelIndex selected = ui->clip_list->selectionModel()->currentIndex();
1392                         if (cliplist_clips->is_camera_column(selected.column()) &&
1393                             hidden_jog_column != -1) {
1394                                 // See the definition on hidden_jog_column.
1395                                 selected = selected.sibling(selected.row(), hidden_jog_column);
1396                                 ui->clip_list->selectionModel()->setCurrentIndex(selected, QItemSelectionModel::ClearAndSelect);
1397                                 hidden_jog_column = -1;
1398                         }
1399                         if (selected.column() != -1 && selected.row() != -1) {
1400                                 jog_internal(JOG_CLIP_LIST, selected.row(), selected.column(), ui->preview_display->get_stream_idx(), pts_delta);
1401                         }
1402                 }
1403         });
1404 }
1405
1406 void MainWindow::switch_camera(unsigned camera_idx)
1407 {
1408         post_to_main_thread([this, camera_idx] {
1409                 if (camera_idx < num_cameras) {  // TODO: Also make this change a highlighted clip?
1410                         preview_angle_clicked(camera_idx);
1411                 }
1412         });
1413 }
1414
1415 void MainWindow::set_master_speed(float speed)
1416 {
1417         speed = min(max(speed, 0.1f), 2.0f);
1418
1419         post_to_main_thread([this, speed] {
1420                 if (ui->speed_lock_btn->isChecked()) {
1421                         midi_mapper.set_locked(MIDIMapper::Blinking);
1422                         lock_blink_timeout->start(1000);
1423                         return;
1424                 }
1425
1426                 int percent = lrintf(speed * 100.0f);
1427                 ui->speed_slider->blockSignals(true);
1428                 ui->speed_slider->setValue(percent);
1429                 ui->speed_slider->blockSignals(false);
1430                 ui->speed_lock_btn->setText(QString::fromStdString(" " + to_string(percent) + "%"));
1431
1432                 live_player->set_master_speed(speed);
1433                 midi_mapper.set_speed_light(speed);
1434         });
1435 }
1436
1437 void MainWindow::cue_in()
1438 {
1439         post_to_main_thread([this] { cue_in_clicked(); });
1440 }
1441
1442 void MainWindow::cue_out()
1443 {
1444         post_to_main_thread([this] { cue_out_clicked(); });
1445 }
1446
1447 template<class Model>
1448 void MainWindow::replace_model(QTableView *view, Model **model, Model *new_model)
1449 {
1450         QItemSelectionModel *old_selection_model = view->selectionModel();
1451         view->setModel(new_model);
1452         delete *model;
1453         delete old_selection_model;
1454         *model = new_model;
1455         connect(new_model, &Model::any_content_changed, this, &MainWindow::content_changed);
1456 }
1457
1458 void MainWindow::start_tally()
1459 {
1460         http_reply = http.get(QNetworkRequest(QString::fromStdString(global_flags.tally_url)));
1461         connect(http_reply, &QNetworkReply::finished, this, &MainWindow::tally_received);
1462 }
1463
1464 void MainWindow::tally_received()
1465 {
1466         unsigned time_to_next_tally_ms;
1467         if (http_reply->error()) {
1468                 fprintf(stderr, "HTTP get of '%s' failed: %s\n", global_flags.tally_url.c_str(),
1469                         http_reply->errorString().toStdString().c_str());
1470                 ui->live_frame->setStyleSheet("");
1471                 time_to_next_tally_ms = 1000;
1472         } else {
1473                 string contents = http_reply->readAll().toStdString();
1474                 ui->live_frame->setStyleSheet(QString::fromStdString("background: " + contents));
1475                 time_to_next_tally_ms = 100;
1476         }
1477         http_reply->deleteLater();
1478         http_reply = nullptr;
1479
1480         QTimer::singleShot(time_to_next_tally_ms, this, &MainWindow::start_tally);
1481 }