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