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