1 #include "mainwindow.h"
6 #include "frame_on_disk.h"
8 #include "futatabi_midi_mapping.pb.h"
9 #include "shared/aboutdialog.h"
10 #include "shared/disk_space_estimator.h"
11 #include "shared/post_to_main_thread.h"
12 #include "shared/timebase.h"
13 #include "ui_mainwindow.h"
15 #include <QDesktopServices>
16 #include <QFileDialog>
17 #include <QMessageBox>
18 #include <QMouseEvent>
19 #include <QNetworkReply>
22 #include <QWheelEvent>
29 using namespace std::placeholders;
31 MainWindow *global_mainwindow = nullptr;
32 static ClipList *cliplist_clips;
33 static PlayList *playlist_clips;
35 extern int64_t current_pts;
39 void set_pts_in(int64_t pts, int64_t current_pts, ClipProxy &clip)
41 pts = std::max<int64_t>(pts, 0);
42 if (clip->pts_out == -1) {
43 pts = std::min(pts, current_pts);
45 pts = std::min(pts, clip->pts_out);
52 MainWindow::MainWindow()
53 : ui(new Ui::MainWindow),
54 db(global_flags.working_directory + "/futatabi.db"),
57 global_mainwindow = this;
60 // Load settings from database.
61 SettingsProto settings = db.get_settings();
62 if (!global_flags.interpolation_quality_set) {
63 if (settings.interpolation_quality() != 0) {
64 global_flags.interpolation_quality = settings.interpolation_quality() - 1;
67 if (!global_flags.cue_point_padding_set) {
68 global_flags.cue_point_padding_seconds = settings.cue_point_padding_seconds(); // Default 0 is fine.
70 if (global_flags.interpolation_quality == 0) {
71 // Allocate something just for simplicity; we won't be using it
72 // unless the user changes runtime, in which case 1 is fine.
73 flow_initialized_interpolation_quality = 1;
75 flow_initialized_interpolation_quality = global_flags.interpolation_quality;
80 connect(ui->exit_action, &QAction::triggered, this, &MainWindow::exit_triggered);
81 connect(ui->export_cliplist_clip_multitrack_action, &QAction::triggered, this, &MainWindow::export_cliplist_clip_multitrack_triggered);
82 connect(ui->export_playlist_clip_interpolated_action, &QAction::triggered, this, &MainWindow::export_playlist_clip_interpolated_triggered);
83 connect(ui->manual_action, &QAction::triggered, this, &MainWindow::manual_triggered);
84 connect(ui->about_action, &QAction::triggered, this, &MainWindow::about_triggered);
85 connect(ui->undo_action, &QAction::triggered, this, &MainWindow::undo_triggered);
86 connect(ui->redo_action, &QAction::triggered, this, &MainWindow::redo_triggered);
87 ui->undo_action->setEnabled(false);
88 ui->redo_action->setEnabled(false);
91 QActionGroup *quality_group = new QActionGroup(ui->interpolation_menu);
92 quality_group->addAction(ui->quality_0_action);
93 quality_group->addAction(ui->quality_1_action);
94 quality_group->addAction(ui->quality_2_action);
95 quality_group->addAction(ui->quality_3_action);
96 quality_group->addAction(ui->quality_4_action);
97 if (global_flags.interpolation_quality == 0) {
98 ui->quality_0_action->setChecked(true);
99 } else if (global_flags.interpolation_quality == 1) {
100 ui->quality_1_action->setChecked(true);
101 } else if (global_flags.interpolation_quality == 2) {
102 ui->quality_2_action->setChecked(true);
103 } else if (global_flags.interpolation_quality == 3) {
104 ui->quality_3_action->setChecked(true);
105 } else if (global_flags.interpolation_quality == 4) {
106 ui->quality_4_action->setChecked(true);
110 connect(ui->quality_0_action, &QAction::toggled, bind(&MainWindow::quality_toggled, this, 0, _1));
111 connect(ui->quality_1_action, &QAction::toggled, bind(&MainWindow::quality_toggled, this, 1, _1));
112 connect(ui->quality_2_action, &QAction::toggled, bind(&MainWindow::quality_toggled, this, 2, _1));
113 connect(ui->quality_3_action, &QAction::toggled, bind(&MainWindow::quality_toggled, this, 3, _1));
114 connect(ui->quality_4_action, &QAction::toggled, bind(&MainWindow::quality_toggled, this, 4, _1));
116 // The cue point padding group.
117 QActionGroup *padding_group = new QActionGroup(ui->interpolation_menu);
118 padding_group->addAction(ui->padding_0_action);
119 padding_group->addAction(ui->padding_1_action);
120 padding_group->addAction(ui->padding_2_action);
121 padding_group->addAction(ui->padding_5_action);
122 if (global_flags.cue_point_padding_seconds <= 1e-3) {
123 ui->padding_0_action->setChecked(true);
124 } else if (fabs(global_flags.cue_point_padding_seconds - 1.0) < 1e-3) {
125 ui->padding_1_action->setChecked(true);
126 } else if (fabs(global_flags.cue_point_padding_seconds - 2.0) < 1e-3) {
127 ui->padding_2_action->setChecked(true);
128 } else if (fabs(global_flags.cue_point_padding_seconds - 5.0) < 1e-3) {
129 ui->padding_5_action->setChecked(true);
131 // Nothing to check, which is fine.
133 connect(ui->padding_0_action, &QAction::toggled, bind(&MainWindow::padding_toggled, this, 0.0, _1));
134 connect(ui->padding_1_action, &QAction::toggled, bind(&MainWindow::padding_toggled, this, 1.0, _1));
135 connect(ui->padding_2_action, &QAction::toggled, bind(&MainWindow::padding_toggled, this, 2.0, _1));
136 connect(ui->padding_5_action, &QAction::toggled, bind(&MainWindow::padding_toggled, this, 5.0, _1));
138 global_disk_space_estimator = new DiskSpaceEstimator(bind(&MainWindow::report_disk_space, this, _1, _2));
139 disk_free_label = new QLabel(this);
140 disk_free_label->setStyleSheet("QLabel {padding-right: 5px;}");
141 ui->menuBar->setCornerWidget(disk_free_label);
143 StateProto state = db.get_state();
144 undo_stack.push_back(state); // The undo stack always has the current state on top.
146 cliplist_clips = new ClipList(state.clip_list());
147 ui->clip_list->setModel(cliplist_clips);
148 connect(cliplist_clips, &ClipList::any_content_changed, this, &MainWindow::content_changed);
150 playlist_clips = new PlayList(state.play_list());
151 ui->playlist->setModel(playlist_clips);
152 connect(playlist_clips, &PlayList::any_content_changed, this, &MainWindow::content_changed);
154 // For un-highlighting when we lose focus.
155 ui->clip_list->installEventFilter(this);
157 // For scrubbing in the pts columns.
158 ui->clip_list->viewport()->installEventFilter(this);
159 ui->playlist->viewport()->installEventFilter(this);
161 QShortcut *cue_in = new QShortcut(QKeySequence(Qt::Key_A), this);
162 connect(cue_in, &QShortcut::activated, ui->cue_in_btn, &QPushButton::click);
163 connect(ui->cue_in_btn, &QPushButton::clicked, this, &MainWindow::cue_in_clicked);
165 QShortcut *cue_out = new QShortcut(QKeySequence(Qt::Key_S), this);
166 connect(cue_out, &QShortcut::activated, ui->cue_out_btn, &QPushButton::click);
167 connect(ui->cue_out_btn, &QPushButton::clicked, this, &MainWindow::cue_out_clicked);
169 QShortcut *queue = new QShortcut(QKeySequence(Qt::Key_Q), this);
170 connect(queue, &QShortcut::activated, ui->queue_btn, &QPushButton::click);
171 connect(ui->queue_btn, &QPushButton::clicked, this, &MainWindow::queue_clicked);
173 QShortcut *preview = new QShortcut(QKeySequence(Qt::Key_W), this);
174 connect(preview, &QShortcut::activated, ui->preview_btn, &QPushButton::click);
175 connect(ui->preview_btn, &QPushButton::clicked, this, &MainWindow::preview_clicked);
177 QShortcut *play = new QShortcut(QKeySequence(Qt::Key_Space), this);
178 connect(play, &QShortcut::activated, ui->play_btn, &QPushButton::click);
179 connect(ui->play_btn, &QPushButton::clicked, this, &MainWindow::play_clicked);
181 connect(ui->stop_btn, &QPushButton::clicked, this, &MainWindow::stop_clicked);
182 ui->stop_btn->setEnabled(false);
184 connect(ui->speed_slider, &QAbstractSlider::valueChanged, this, &MainWindow::speed_slider_changed);
185 connect(ui->speed_lock_btn, &QPushButton::clicked, this, &MainWindow::speed_lock_clicked);
187 connect(ui->playlist_duplicate_btn, &QPushButton::clicked, this, &MainWindow::playlist_duplicate);
189 connect(ui->playlist_remove_btn, &QPushButton::clicked, this, &MainWindow::playlist_remove);
190 QShortcut *delete_key = new QShortcut(QKeySequence(Qt::Key_Delete), ui->playlist);
191 connect(delete_key, &QShortcut::activated, [this] {
192 if (ui->playlist->hasFocus()) {
197 // TODO: support drag-and-drop.
198 connect(ui->playlist_move_up_btn, &QPushButton::clicked, [this] { playlist_move(-1); });
199 connect(ui->playlist_move_down_btn, &QPushButton::clicked, [this] { playlist_move(1); });
201 connect(ui->playlist->selectionModel(), &QItemSelectionModel::selectionChanged,
202 this, &MainWindow::playlist_selection_changed);
203 playlist_selection_changed(); // First time set-up.
205 preview_player.reset(new Player(ui->preview_display, Player::NO_STREAM_OUTPUT));
206 live_player.reset(new Player(ui->live_display, Player::HTTPD_STREAM_OUTPUT));
207 live_player->set_done_callback([this] {
208 post_to_main_thread([this] {
212 live_player->set_progress_callback([this](const map<uint64_t, double> &progress, double time_remaining) {
213 post_to_main_thread([this, progress, time_remaining] {
214 live_player_clip_progress(progress, time_remaining);
217 set_output_status("paused");
218 enable_or_disable_queue_button();
220 defer_timeout = new QTimer(this);
221 defer_timeout->setSingleShot(true);
222 connect(defer_timeout, &QTimer::timeout, this, &MainWindow::defer_timer_expired);
223 ui->undo_action->setEnabled(true);
225 connect(ui->clip_list->selectionModel(), &QItemSelectionModel::currentChanged,
226 this, &MainWindow::clip_list_selection_changed);
227 enable_or_disable_queue_button();
229 // Find out how many cameras we have in the existing frames;
230 // if none, we start with two cameras.
233 lock_guard<mutex> lock(frame_mu);
234 for (size_t stream_idx = 2; stream_idx < MAX_STREAMS; ++stream_idx) {
235 if (!frames[stream_idx].empty()) {
236 num_cameras = stream_idx + 1;
240 change_num_cameras();
242 if (!global_flags.tally_url.empty()) {
246 if (!global_flags.midi_mapping_filename.empty()) {
247 MIDIMappingProto midi_mapping;
248 if (!load_midi_mapping_from_file(global_flags.midi_mapping_filename, &midi_mapping)) {
249 fprintf(stderr, "Couldn't load MIDI mapping '%s'; exiting.\n",
250 global_flags.midi_mapping_filename.c_str());
253 midi_mapper.set_midi_mapping(midi_mapping);
255 midi_mapper.refresh_lights();
256 midi_mapper.start_thread();
259 void MainWindow::change_num_cameras()
261 assert(num_cameras >= displays.size()); // We only add, never remove.
263 // Make new display rows.
264 unsigned display_rows = (num_cameras + 1) / 2;
265 ui->video_displays->setStretch(1, display_rows);
266 for (unsigned i = displays.size(); i < num_cameras; ++i) {
267 QFrame *frame = new QFrame(this);
268 frame->setAutoFillBackground(true);
270 QLayout *layout = new QGridLayout(frame);
271 frame->setLayout(layout);
272 layout->setContentsMargins(3, 3, 3, 3);
274 JPEGFrameView *display = new JPEGFrameView(frame);
275 display->setAutoFillBackground(true);
276 layout->addWidget(display);
278 ui->input_displays->addWidget(frame, i / 2, i % 2);
279 display->set_overlay(to_string(i + 1));
281 QPushButton *preview_btn = new QPushButton(this);
282 preview_btn->setMaximumSize(20, 17);
283 preview_btn->setText(QString::fromStdString(to_string(i + 1)));
284 ui->preview_layout->addWidget(preview_btn);
286 displays.emplace_back(FrameAndDisplay{ frame, display, preview_btn });
288 connect(display, &JPEGFrameView::clicked, preview_btn, &QPushButton::click);
289 QShortcut *shortcut = new QShortcut(QKeySequence(Qt::Key_1 + i), this);
290 connect(shortcut, &QShortcut::activated, preview_btn, &QPushButton::click);
292 connect(preview_btn, &QPushButton::clicked, [this, i] { preview_angle_clicked(i); });
295 cliplist_clips->change_num_cameras(num_cameras);
296 playlist_clips->change_num_cameras(num_cameras);
298 QMetaObject::invokeMethod(this, "relayout", Qt::QueuedConnection);
301 MainWindow::~MainWindow()
303 // Empty so that we can forward-declare Player in the .h file.
306 void MainWindow::cue_in_clicked()
308 if (!cliplist_clips->empty() && cliplist_clips->back()->pts_out < 0) {
309 cliplist_clips->mutable_back()->pts_in = current_pts;
312 clip.pts_in = max<int64_t>(current_pts - lrint(global_flags.cue_point_padding_seconds * TIMEBASE), 0);
313 cliplist_clips->add_clip(clip);
314 playlist_selection_changed();
317 // Select the item so that we can jog it.
318 ui->clip_list->setFocus();
319 QModelIndex index = cliplist_clips->index(cliplist_clips->size() - 1, int(ClipList::Column::IN));
320 ui->clip_list->selectionModel()->setCurrentIndex(index, QItemSelectionModel::ClearAndSelect);
321 ui->clip_list->scrollToBottom();
322 enable_or_disable_queue_button();
325 void MainWindow::cue_out_clicked()
327 if (cliplist_clips->empty()) {
331 cliplist_clips->mutable_back()->pts_out = current_pts + lrint(global_flags.cue_point_padding_seconds * TIMEBASE);
333 // Select the item so that we can jog it.
334 ui->clip_list->setFocus();
335 QModelIndex index = cliplist_clips->index(cliplist_clips->size() - 1, int(ClipList::Column::OUT));
336 ui->clip_list->selectionModel()->setCurrentIndex(index, QItemSelectionModel::ClearAndSelect);
337 ui->clip_list->scrollToBottom();
338 enable_or_disable_queue_button();
341 void MainWindow::queue_clicked()
343 // See also enable_or_disable_queue_button().
345 if (cliplist_clips->empty()) {
349 QItemSelectionModel *selected = ui->clip_list->selectionModel();
350 if (!selected->hasSelection()) {
351 Clip clip = *cliplist_clips->back();
353 if (clip.pts_out != -1) {
354 playlist_clips->add_clip(clip);
355 playlist_selection_changed();
356 ui->playlist->scrollToBottom();
361 QModelIndex index = selected->currentIndex();
362 Clip clip = *cliplist_clips->clip(index.row());
363 if (cliplist_clips->is_camera_column(index.column())) {
364 clip.stream_idx = index.column() - int(ClipList::Column::CAMERA_1);
366 clip.stream_idx = ui->preview_display->get_stream_idx();
369 if (clip.pts_out != -1) {
370 playlist_clips->add_clip(clip);
371 playlist_selection_changed();
372 ui->playlist->scrollToBottom();
373 if (!ui->playlist->selectionModel()->hasSelection()) {
374 // TODO: Figure out why this doesn't always seem to actually select the row.
375 QModelIndex bottom = playlist_clips->index(playlist_clips->size() - 1, 0);
376 ui->playlist->setCurrentIndex(bottom);
381 void MainWindow::preview_clicked()
383 // See also enable_or_disable_preview_button().
385 if (ui->playlist->hasFocus()) {
386 // Allow the playlist as preview iff it has focus and something is selected.
387 QItemSelectionModel *selected = ui->playlist->selectionModel();
388 if (selected->hasSelection()) {
389 QModelIndex index = selected->currentIndex();
390 const Clip &clip = *playlist_clips->clip(index.row());
391 preview_player->play(clip);
396 if (cliplist_clips->empty())
399 QItemSelectionModel *selected = ui->clip_list->selectionModel();
400 if (!selected->hasSelection()) {
401 preview_player->play(*cliplist_clips->back());
405 QModelIndex index = selected->currentIndex();
406 Clip clip = *cliplist_clips->clip(index.row());
407 if (cliplist_clips->is_camera_column(index.column())) {
408 clip.stream_idx = index.column() - int(ClipList::Column::CAMERA_1);
410 clip.stream_idx = ui->preview_display->get_stream_idx();
412 preview_player->play(clip);
415 void MainWindow::preview_angle_clicked(unsigned stream_idx)
417 preview_player->override_angle(stream_idx);
419 // Change the selection if we were previewing a clip from the clip list.
420 // (The only other thing we could be showing is a pts scrub, and if so,
421 // that would be selected.)
422 QItemSelectionModel *selected = ui->clip_list->selectionModel();
423 if (selected->hasSelection()) {
424 QModelIndex cell = selected->selectedIndexes()[0];
425 int column = int(ClipList::Column::CAMERA_1) + stream_idx;
426 selected->setCurrentIndex(cell.sibling(cell.row(), column), QItemSelectionModel::ClearAndSelect);
430 void MainWindow::playlist_duplicate()
432 QItemSelectionModel *selected = ui->playlist->selectionModel();
433 if (!selected->hasSelection()) {
434 // Should have been grayed out, but OK.
437 QModelIndexList rows = selected->selectedRows();
438 int first = rows.front().row(), last = rows.back().row();
439 playlist_clips->duplicate_clips(first, last);
440 playlist_selection_changed();
443 void MainWindow::playlist_remove()
445 QItemSelectionModel *selected = ui->playlist->selectionModel();
446 if (!selected->hasSelection()) {
447 // Should have been grayed out, but OK.
450 QModelIndexList rows = selected->selectedRows();
451 int first = rows.front().row(), last = rows.back().row();
452 playlist_clips->erase_clips(first, last);
454 // TODO: select the next one in the list?
456 playlist_selection_changed();
459 void MainWindow::playlist_move(int delta)
461 QItemSelectionModel *selected = ui->playlist->selectionModel();
462 if (!selected->hasSelection()) {
463 // Should have been grayed out, but OK.
467 QModelIndexList rows = selected->selectedRows();
468 int first = rows.front().row(), last = rows.back().row();
469 if ((delta == -1 && first == 0) ||
470 (delta == 1 && size_t(last) == playlist_clips->size() - 1)) {
471 // Should have been grayed out, but OK.
475 playlist_clips->move_clips(first, last, delta);
476 playlist_selection_changed();
479 void MainWindow::jog_internal(JogDestination jog_destination, int row, int column, int stream_idx, int pts_delta)
481 constexpr int camera_pts_per_pixel = 1500; // One click of most mice (15 degrees), multiplied by the default wheel_sensitivity.
483 int in_column, out_column, camera_column;
484 if (jog_destination == JOG_CLIP_LIST) {
485 in_column = int(ClipList::Column::IN);
486 out_column = int(ClipList::Column::OUT);
488 } else if (jog_destination == JOG_PLAYLIST) {
489 in_column = int(PlayList::Column::IN);
490 out_column = int(PlayList::Column::OUT);
491 camera_column = int(PlayList::Column::CAMERA);
496 currently_deferring_model_changes = true;
498 current_change_id = (jog_destination == JOG_CLIP_LIST) ? "cliplist:" : "playlist:";
499 ClipProxy clip = (jog_destination == JOG_CLIP_LIST) ? cliplist_clips->mutable_clip(row) : playlist_clips->mutable_clip(row);
500 if (jog_destination == JOG_PLAYLIST) {
501 stream_idx = clip->stream_idx;
504 if (column == in_column) {
505 current_change_id += "in:" + to_string(row);
506 int64_t pts = clip->pts_in + pts_delta;
507 set_pts_in(pts, current_pts, clip);
508 preview_single_frame(pts, stream_idx, FIRST_AT_OR_AFTER);
509 } else if (column == out_column) {
510 current_change_id += "out:" + to_string(row);
511 int64_t pts = clip->pts_out + pts_delta;
512 pts = std::max(pts, clip->pts_in);
513 pts = std::min(pts, current_pts);
515 preview_single_frame(pts, stream_idx, LAST_BEFORE);
516 } else if (column == camera_column) {
517 current_change_id += "camera:" + to_string(row);
518 int angle_degrees = pts_delta;
519 if (last_mousewheel_camera_row == row) {
520 angle_degrees += leftover_angle_degrees;
523 int stream_idx = clip->stream_idx + angle_degrees / camera_pts_per_pixel;
524 stream_idx = std::max(stream_idx, 0);
525 stream_idx = std::min<int>(stream_idx, num_cameras - 1);
526 clip->stream_idx = stream_idx;
528 last_mousewheel_camera_row = row;
529 leftover_angle_degrees = angle_degrees % camera_pts_per_pixel;
531 // Don't update the live view, that's rarely what the operator wants.
534 currently_deferring_model_changes = false;
537 void MainWindow::defer_timer_expired()
539 state_changed(deferred_state);
542 void MainWindow::content_changed()
544 // If we are playing, update the part of the playlist that's not playing yet.
545 vector<ClipWithID> clips;
546 for (unsigned row = 0; row < playlist_clips->size(); ++row) {
547 clips.emplace_back(*playlist_clips->clip_with_id(row));
549 live_player->splice_play(clips);
551 // Serialize the state.
552 if (defer_timeout->isActive() &&
553 (!currently_deferring_model_changes || deferred_change_id != current_change_id)) {
554 // There's some deferred event waiting, but this event is unrelated.
555 // So it's time to short-circuit that timer and do the work it wanted to do.
556 defer_timeout->stop();
557 state_changed(deferred_state);
560 *state.mutable_clip_list() = cliplist_clips->serialize();
561 *state.mutable_play_list() = playlist_clips->serialize();
562 if (currently_deferring_model_changes) {
563 deferred_change_id = current_change_id;
564 deferred_state = std::move(state);
565 defer_timeout->start(200);
568 state_changed(state);
571 void MainWindow::state_changed(const StateProto &state)
573 db.store_state(state);
576 ui->redo_action->setEnabled(false);
578 undo_stack.push_back(state);
579 ui->undo_action->setEnabled(undo_stack.size() > 1);
581 // Make sure it doesn't grow without bounds.
582 while (undo_stack.size() >= 100) {
583 undo_stack.pop_front();
587 void MainWindow::save_settings()
589 SettingsProto settings;
590 settings.set_interpolation_quality(global_flags.interpolation_quality + 1);
591 settings.set_cue_point_padding_seconds(global_flags.cue_point_padding_seconds);
592 db.store_settings(settings);
595 void MainWindow::play_clicked()
597 if (playlist_clips->empty())
600 QItemSelectionModel *selected = ui->playlist->selectionModel();
602 if (!selected->hasSelection()) {
605 start_row = selected->selectedRows(0)[0].row();
608 vector<ClipWithID> clips;
609 for (unsigned row = start_row; row < playlist_clips->size(); ++row) {
610 clips.emplace_back(*playlist_clips->clip_with_id(row));
612 live_player->play(clips);
613 playlist_clips->set_progress({ { start_row, 0.0f } });
614 ui->playlist->selectionModel()->clear();
615 playlist_selection_changed();
617 ui->stop_btn->setEnabled(true);
620 void MainWindow::stop_clicked()
623 fake_clip.pts_in = 0;
624 fake_clip.pts_out = 0;
625 playlist_clips->set_progress({});
626 live_player->play(fake_clip);
627 ui->stop_btn->setEnabled(false);
630 void MainWindow::speed_slider_changed(int percent)
632 float speed = percent / 100.0f;
633 ui->speed_lock_btn->setText(QString::fromStdString(" " + to_string(percent) + "%"));
634 live_player->set_master_speed(speed);
637 void MainWindow::speed_lock_clicked()
639 // TODO: Make for a less abrupt transition if we're not already at 100%.
640 ui->speed_slider->setValue(100); // Also actually sets the master speed and updates the label.
641 ui->speed_slider->setEnabled(!ui->speed_lock_btn->isChecked());
642 midi_mapper.set_locked(ui->speed_lock_btn->isChecked());
645 void MainWindow::live_player_done()
647 playlist_selection_changed();
648 playlist_clips->set_progress({});
649 ui->stop_btn->setEnabled(false);
652 void MainWindow::live_player_clip_progress(const map<uint64_t, double> &progress, double time_remaining)
654 playlist_clips->set_progress(progress);
655 set_output_status(format_duration(time_remaining) + " left");
658 void MainWindow::resizeEvent(QResizeEvent *event)
660 QMainWindow::resizeEvent(event);
662 // Ask for a relayout, but only after the event loop is done doing relayout
663 // on everything else.
664 QMetaObject::invokeMethod(this, "relayout", Qt::QueuedConnection);
667 void MainWindow::relayout()
669 ui->live_display->setMinimumWidth(ui->live_display->height() * 16 / 9);
670 ui->preview_display->setMinimumWidth(ui->preview_display->height() * 16 / 9);
673 bool MainWindow::eventFilter(QObject *watched, QEvent *event)
675 constexpr int dead_zone_pixels = 3; // To avoid that simple clicks get misinterpreted.
676 int scrub_sensitivity = 100; // pts units per pixel.
677 int wheel_sensitivity = 100; // pts units per degree.
679 if (event->type() == QEvent::FocusIn || event->type() == QEvent::FocusOut) {
680 enable_or_disable_preview_button();
681 hidden_jog_column = -1;
684 unsigned stream_idx = ui->preview_display->get_stream_idx();
686 if (watched == ui->clip_list) {
687 if (event->type() == QEvent::FocusOut) {
688 highlight_camera_input(-1);
693 if (event->type() != QEvent::Wheel) {
694 last_mousewheel_camera_row = -1;
697 if (event->type() == QEvent::MouseButtonPress) {
698 QMouseEvent *mouse = (QMouseEvent *)event;
700 QTableView *destination;
703 if (watched == ui->clip_list->viewport()) {
704 destination = ui->clip_list;
705 type = SCRUBBING_CLIP_LIST;
706 } else if (watched == ui->playlist->viewport()) {
707 destination = ui->playlist;
708 type = SCRUBBING_PLAYLIST;
712 int column = destination->columnAt(mouse->x());
713 int row = destination->rowAt(mouse->y());
714 if (column == -1 || row == -1)
717 if (type == SCRUBBING_CLIP_LIST) {
718 if (ClipList::Column(column) == ClipList::Column::IN) {
719 scrub_pts_origin = cliplist_clips->clip(row)->pts_in;
720 preview_single_frame(scrub_pts_origin, stream_idx, FIRST_AT_OR_AFTER);
721 } else if (ClipList::Column(column) == ClipList::Column::OUT) {
722 scrub_pts_origin = cliplist_clips->clip(row)->pts_out;
723 preview_single_frame(scrub_pts_origin, stream_idx, LAST_BEFORE);
728 if (PlayList::Column(column) == PlayList::Column::IN) {
729 scrub_pts_origin = playlist_clips->clip(row)->pts_in;
730 preview_single_frame(scrub_pts_origin, stream_idx, FIRST_AT_OR_AFTER);
731 } else if (PlayList::Column(column) == PlayList::Column::OUT) {
732 scrub_pts_origin = playlist_clips->clip(row)->pts_out;
733 preview_single_frame(scrub_pts_origin, stream_idx, LAST_BEFORE);
741 scrub_column = column;
742 scrub_x_origin = mouse->x();
744 } else if (event->type() == QEvent::MouseMove) {
745 QMouseEvent *mouse = (QMouseEvent *)event;
746 if (mouse->modifiers() & Qt::KeyboardModifier::ShiftModifier) {
747 scrub_sensitivity *= 10;
748 wheel_sensitivity *= 10;
750 if (mouse->modifiers() & Qt::KeyboardModifier::AltModifier) { // Note: Shift + Alt cancel each other out.
751 scrub_sensitivity /= 10;
752 wheel_sensitivity /= 10;
755 int offset = mouse->x() - scrub_x_origin;
757 if (offset >= dead_zone_pixels) {
758 adjusted_offset = offset - dead_zone_pixels;
759 } else if (offset < -dead_zone_pixels) {
760 adjusted_offset = offset + dead_zone_pixels;
765 int64_t pts = scrub_pts_origin + adjusted_offset * scrub_sensitivity;
766 currently_deferring_model_changes = true;
767 if (scrub_type == SCRUBBING_CLIP_LIST) {
768 ClipProxy clip = cliplist_clips->mutable_clip(scrub_row);
769 if (scrub_column == int(ClipList::Column::IN)) {
770 current_change_id = "cliplist:in:" + to_string(scrub_row);
771 set_pts_in(pts, current_pts, clip);
772 preview_single_frame(pts, stream_idx, FIRST_AT_OR_AFTER);
774 current_change_id = "cliplist:out" + to_string(scrub_row);
775 pts = std::max(pts, clip->pts_in);
776 pts = std::min(pts, current_pts);
778 preview_single_frame(pts, stream_idx, LAST_BEFORE);
781 ClipProxy clip = playlist_clips->mutable_clip(scrub_row);
782 if (scrub_column == int(PlayList::Column::IN)) {
783 current_change_id = "playlist:in:" + to_string(scrub_row);
784 set_pts_in(pts, current_pts, clip);
785 preview_single_frame(pts, clip->stream_idx, FIRST_AT_OR_AFTER);
787 current_change_id = "playlist:out:" + to_string(scrub_row);
788 pts = std::max(pts, clip->pts_in);
789 pts = std::min(pts, current_pts);
791 preview_single_frame(pts, clip->stream_idx, LAST_BEFORE);
794 currently_deferring_model_changes = false;
796 return true; // Don't use this mouse movement for selecting things.
798 } else if (event->type() == QEvent::Wheel) {
799 QWheelEvent *wheel = (QWheelEvent *)event;
800 int angle_delta = wheel->angleDelta().y();
801 if (wheel->modifiers() & Qt::KeyboardModifier::ShiftModifier) {
802 scrub_sensitivity *= 10;
803 wheel_sensitivity *= 10;
805 if (wheel->modifiers() & Qt::KeyboardModifier::AltModifier) { // Note: Shift + Alt cancel each other out.
806 scrub_sensitivity /= 10;
807 wheel_sensitivity /= 10;
808 angle_delta = wheel->angleDelta().x(); // Qt ickiness.
811 QTableView *destination;
812 JogDestination jog_destination;
813 if (watched == ui->clip_list->viewport()) {
814 destination = ui->clip_list;
815 jog_destination = JOG_CLIP_LIST;
816 last_mousewheel_camera_row = -1;
817 } else if (watched == ui->playlist->viewport()) {
818 destination = ui->playlist;
819 jog_destination = JOG_PLAYLIST;
820 if (destination->columnAt(wheel->x()) != int(PlayList::Column::CAMERA)) {
821 last_mousewheel_camera_row = -1;
824 last_mousewheel_camera_row = -1;
828 int column = destination->columnAt(wheel->x());
829 int row = destination->rowAt(wheel->y());
830 if (column == -1 || row == -1)
833 // Only adjust pts with the wheel if the given row is selected.
834 if (!destination->hasFocus() ||
835 row != destination->selectionModel()->currentIndex().row()) {
839 jog_internal(jog_destination, row, column, stream_idx, angle_delta * wheel_sensitivity);
840 return true; // Don't scroll.
841 } else if (event->type() == QEvent::MouseButtonRelease) {
847 void MainWindow::preview_single_frame(int64_t pts, unsigned stream_idx, MainWindow::Rounding rounding)
849 if (rounding == LAST_BEFORE) {
850 lock_guard<mutex> lock(frame_mu);
851 if (frames[stream_idx].empty())
853 auto it = find_last_frame_before(frames[stream_idx], pts);
854 if (it != frames[stream_idx].end()) {
858 assert(rounding == FIRST_AT_OR_AFTER);
859 lock_guard<mutex> lock(frame_mu);
860 if (frames[stream_idx].empty())
862 auto it = find_first_frame_at_or_after(frames[stream_idx], pts);
863 if (it != frames[stream_idx].end()) {
869 fake_clip.pts_in = pts;
870 fake_clip.pts_out = pts + 1;
871 fake_clip.stream_idx = stream_idx;
872 preview_player->play(fake_clip);
875 void MainWindow::playlist_selection_changed()
877 enable_or_disable_preview_button();
879 QItemSelectionModel *selected = ui->playlist->selectionModel();
880 bool any_selected = selected->hasSelection();
881 ui->playlist_duplicate_btn->setEnabled(any_selected);
882 ui->playlist_remove_btn->setEnabled(any_selected);
883 ui->playlist_move_up_btn->setEnabled(
884 any_selected && selected->selectedRows().front().row() > 0);
885 ui->playlist_move_down_btn->setEnabled(
886 any_selected && selected->selectedRows().back().row() < int(playlist_clips->size()) - 1);
888 ui->play_btn->setEnabled(!playlist_clips->empty());
889 midi_mapper.set_play_enabled(!playlist_clips->empty());
892 set_output_status("paused");
894 vector<ClipWithID> clips;
895 for (size_t row = selected->selectedRows().front().row(); row < playlist_clips->size(); ++row) {
896 clips.emplace_back(*playlist_clips->clip_with_id(row));
898 double remaining = compute_total_time(clips);
899 set_output_status(format_duration(remaining) + " ready");
903 void MainWindow::clip_list_selection_changed(const QModelIndex ¤t, const QModelIndex &previous)
905 int camera_selected = -1;
906 if (cliplist_clips->is_camera_column(current.column())) {
907 camera_selected = current.column() - int(ClipList::Column::CAMERA_1);
909 // See the comment on hidden_jog_column.
910 if (current.row() != previous.row()) {
911 hidden_jog_column = -1;
912 } else if (hidden_jog_column == -1) {
913 hidden_jog_column = previous.column();
916 hidden_jog_column = -1;
918 highlight_camera_input(camera_selected);
919 enable_or_disable_queue_button();
922 void MainWindow::report_disk_space(off_t free_bytes, double estimated_seconds_left)
925 if (estimated_seconds_left < 60.0) {
926 strcpy(time_str, "<font color=\"red\">Less than a minute</font>");
927 } else if (estimated_seconds_left < 1800.0) { // Less than half an hour: Xm Ys (red).
928 int s = lrintf(estimated_seconds_left);
931 snprintf(time_str, sizeof(time_str), "<font color=\"red\">%dm %ds</font>", m, s);
932 } else if (estimated_seconds_left < 3600.0) { // Less than an hour: Xm.
933 int m = lrintf(estimated_seconds_left / 60.0);
934 snprintf(time_str, sizeof(time_str), "%dm", m);
935 } else if (estimated_seconds_left < 36000.0) { // Less than ten hours: Xh Ym.
936 int m = lrintf(estimated_seconds_left / 60.0);
939 snprintf(time_str, sizeof(time_str), "%dh %dm", h, m);
940 } else { // More than ten hours: Xh.
941 int h = lrintf(estimated_seconds_left / 3600.0);
942 snprintf(time_str, sizeof(time_str), "%dh", h);
945 snprintf(buf, sizeof(buf), "Disk free: %'.0f MB (approx. %s)", free_bytes / 1048576.0, time_str);
947 std::string label = buf;
949 post_to_main_thread([this, label] {
950 disk_free_label->setText(QString::fromStdString(label));
951 ui->menuBar->setCornerWidget(disk_free_label); // Need to set this again for the sizing to get right.
955 void MainWindow::exit_triggered()
960 void MainWindow::export_cliplist_clip_multitrack_triggered()
962 QItemSelectionModel *selected = ui->clip_list->selectionModel();
963 if (!selected->hasSelection()) {
965 msgbox.setText("No clip selected in the clip list. Select one and try exporting again.");
970 QModelIndex index = selected->currentIndex();
971 Clip clip = *cliplist_clips->clip(index.row());
972 QString filename = QFileDialog::getSaveFileName(this,
973 "Export multitrack clip", QString(), tr("Matroska video files (*.mkv)"));
974 if (filename.isNull()) {
978 if (!filename.endsWith(".mkv")) {
981 export_multitrack_clip(filename.toStdString(), clip);
984 void MainWindow::export_playlist_clip_interpolated_triggered()
986 QItemSelectionModel *selected = ui->playlist->selectionModel();
987 if (!selected->hasSelection()) {
989 msgbox.setText("No clip selected in the playlist. Select one and try exporting again.");
994 QString filename = QFileDialog::getSaveFileName(this,
995 "Export interpolated clip", QString(), tr("Matroska video files (*.mkv)"));
996 if (filename.isNull()) {
1000 if (!filename.endsWith(".mkv")) {
1005 QModelIndexList rows = selected->selectedRows();
1006 for (QModelIndex index : rows) {
1007 clips.push_back(*playlist_clips->clip(index.row()));
1009 export_interpolated_clip(filename.toStdString(), clips);
1012 void MainWindow::manual_triggered()
1014 if (!QDesktopServices::openUrl(QUrl("https://nageru.sesse.net/doc/"))) {
1016 msgbox.setText("Could not launch manual in web browser.\nPlease see https://nageru.sesse.net/doc/ manually.");
1021 void MainWindow::about_triggered()
1023 AboutDialog("Futatabi", "Multicamera slow motion video server").exec();
1026 void MainWindow::undo_triggered()
1028 // Finish any deferred action.
1029 if (defer_timeout->isActive()) {
1030 defer_timeout->stop();
1031 state_changed(deferred_state);
1034 StateProto redo_state;
1035 *redo_state.mutable_clip_list() = cliplist_clips->serialize();
1036 *redo_state.mutable_play_list() = playlist_clips->serialize();
1037 redo_stack.push_back(std::move(redo_state));
1038 ui->redo_action->setEnabled(true);
1040 assert(undo_stack.size() > 1);
1042 // Pop off the current state, which is always at the top of the stack.
1043 undo_stack.pop_back();
1045 StateProto state = undo_stack.back();
1046 ui->undo_action->setEnabled(undo_stack.size() > 1);
1048 replace_model(ui->clip_list, &cliplist_clips, new ClipList(state.clip_list()));
1049 replace_model(ui->playlist, &playlist_clips, new PlayList(state.play_list()));
1051 db.store_state(state);
1054 void MainWindow::redo_triggered()
1056 assert(!redo_stack.empty());
1058 ui->undo_action->setEnabled(true);
1059 ui->redo_action->setEnabled(true);
1061 undo_stack.push_back(std::move(redo_stack.back()));
1062 redo_stack.pop_back();
1063 ui->undo_action->setEnabled(true);
1064 ui->redo_action->setEnabled(!redo_stack.empty());
1066 const StateProto &state = undo_stack.back();
1067 replace_model(ui->clip_list, &cliplist_clips, new ClipList(state.clip_list()));
1068 replace_model(ui->playlist, &playlist_clips, new PlayList(state.play_list()));
1070 db.store_state(state);
1073 void MainWindow::quality_toggled(int quality, bool checked)
1078 global_flags.interpolation_quality = quality;
1079 if (quality != 0 && // Turning interpolation off is always possible.
1080 quality != flow_initialized_interpolation_quality) {
1082 msgbox.setText(QString::fromStdString(
1083 "The interpolation quality for the main output cannot be changed at runtime, "
1084 "except being turned completely off; it will take effect for exported files "
1085 "only until next restart. The live output quality thus remains at " +
1086 to_string(flow_initialized_interpolation_quality) + "."));
1093 void MainWindow::padding_toggled(double seconds, bool checked)
1098 global_flags.cue_point_padding_seconds = seconds;
1102 void MainWindow::highlight_camera_input(int stream_idx)
1104 for (unsigned i = 0; i < num_cameras; ++i) {
1105 if (unsigned(stream_idx) == i) {
1106 displays[i].frame->setStyleSheet("background: rgb(0,255,0)");
1108 displays[i].frame->setStyleSheet("");
1111 midi_mapper.highlight_camera_input(stream_idx);
1114 void MainWindow::enable_or_disable_preview_button()
1116 // Follows the logic in preview_clicked().
1118 if (ui->playlist->hasFocus()) {
1119 // Allow the playlist as preview iff it has focus and something is selected.
1120 // TODO: Is this part really relevant?
1121 QItemSelectionModel *selected = ui->playlist->selectionModel();
1122 if (selected->hasSelection()) {
1123 ui->preview_btn->setEnabled(true);
1124 midi_mapper.set_preview_enabled(true);
1129 // TODO: Perhaps only enable this if something is actually selected.
1130 ui->preview_btn->setEnabled(!cliplist_clips->empty());
1131 midi_mapper.set_preview_enabled(!cliplist_clips->empty());
1134 void MainWindow::enable_or_disable_queue_button()
1136 // Follows the logic in queue_clicked().
1137 // TODO: Perhaps only enable this if something is actually selected.
1141 if (cliplist_clips->empty()) {
1144 QItemSelectionModel *selected = ui->clip_list->selectionModel();
1145 if (!selected->hasSelection()) {
1146 Clip clip = *cliplist_clips->back();
1147 enabled = clip.pts_out != -1;
1149 QModelIndex index = selected->currentIndex();
1150 Clip clip = *cliplist_clips->clip(index.row());
1151 enabled = clip.pts_out != -1;
1155 ui->queue_btn->setEnabled(enabled);
1156 midi_mapper.set_queue_enabled(enabled);
1159 void MainWindow::set_output_status(const string &status)
1161 ui->live_label->setText(QString::fromStdString("Current output (" + status + ")"));
1162 if (live_player != nullptr) {
1163 live_player->set_pause_status(status);
1166 lock_guard<mutex> lock(queue_status_mu);
1167 queue_status = status;
1170 pair<string, string> MainWindow::get_queue_status() const
1172 lock_guard<mutex> lock(queue_status_mu);
1173 return { queue_status, "text/plain" };
1176 void MainWindow::display_frame(unsigned stream_idx, const FrameOnDisk &frame)
1178 if (stream_idx >= MAX_STREAMS) {
1179 fprintf(stderr, "WARNING: Ignoring too-high stream index %u.\n", stream_idx);
1182 if (stream_idx >= num_cameras) {
1183 post_to_main_thread_and_wait([this, stream_idx] {
1184 num_cameras = stream_idx + 1;
1185 change_num_cameras();
1188 displays[stream_idx].display->setFrame(stream_idx, frame);
1191 void MainWindow::preview()
1193 post_to_main_thread([this] {
1198 void MainWindow::queue()
1200 post_to_main_thread([this] {
1205 void MainWindow::play()
1207 post_to_main_thread([this] {
1212 void MainWindow::toggle_lock()
1214 post_to_main_thread([this] {
1215 ui->speed_lock_btn->setChecked(!ui->speed_lock_btn->isChecked());
1216 speed_lock_clicked();
1220 void MainWindow::jog(int delta)
1222 post_to_main_thread([this, delta] {
1223 int64_t pts_delta = delta * (TIMEBASE / 60); // One click = frame at 60 fps.
1224 if (ui->playlist->hasFocus()) {
1225 QModelIndex selected = ui->playlist->selectionModel()->currentIndex();
1226 if (selected.column() != -1 && selected.row() != -1) {
1227 jog_internal(JOG_PLAYLIST, selected.row(), selected.column(), /*stream_idx=*/-1, pts_delta);
1229 } else if (ui->clip_list->hasFocus()) {
1230 QModelIndex selected = ui->clip_list->selectionModel()->currentIndex();
1231 if (cliplist_clips->is_camera_column(selected.column()) &&
1232 hidden_jog_column != -1) {
1233 // See the definition on hidden_jog_column.
1234 selected = selected.sibling(selected.row(), hidden_jog_column);
1235 ui->clip_list->selectionModel()->setCurrentIndex(selected, QItemSelectionModel::ClearAndSelect);
1236 hidden_jog_column = -1;
1238 if (selected.column() != -1 && selected.row() != -1) {
1239 jog_internal(JOG_CLIP_LIST, selected.row(), selected.column(), ui->preview_display->get_stream_idx(), pts_delta);
1245 void MainWindow::switch_camera(unsigned camera_idx)
1247 post_to_main_thread([this, camera_idx] {
1248 if (camera_idx < num_cameras) { // TODO: Also make this change a highlighted clip?
1249 preview_angle_clicked(camera_idx);
1254 void MainWindow::set_master_speed(float speed)
1256 speed = min(max(speed, 0.1f), 2.0f);
1258 post_to_main_thread([this, speed] {
1259 if (ui->speed_lock_btn->isChecked()) {
1263 int percent = lrintf(speed * 100.0f);
1264 ui->speed_slider->blockSignals(true);
1265 ui->speed_slider->setValue(percent);
1266 ui->speed_slider->blockSignals(false);
1267 ui->speed_lock_btn->setText(QString::fromStdString(" " + to_string(percent) + "%"));
1269 live_player->set_master_speed(speed);
1273 void MainWindow::cue_in()
1275 post_to_main_thread([this] { cue_in_clicked(); });
1278 void MainWindow::cue_out()
1280 post_to_main_thread([this] { cue_out_clicked(); });
1283 template<class Model>
1284 void MainWindow::replace_model(QTableView *view, Model **model, Model *new_model)
1286 QItemSelectionModel *old_selection_model = view->selectionModel();
1287 view->setModel(new_model);
1289 delete old_selection_model;
1291 connect(new_model, &Model::any_content_changed, this, &MainWindow::content_changed);
1294 void MainWindow::start_tally()
1296 http_reply = http.get(QNetworkRequest(QString::fromStdString(global_flags.tally_url)));
1297 connect(http_reply, &QNetworkReply::finished, this, &MainWindow::tally_received);
1300 void MainWindow::tally_received()
1302 unsigned time_to_next_tally_ms;
1303 if (http_reply->error()) {
1304 fprintf(stderr, "HTTP get of '%s' failed: %s\n", global_flags.tally_url.c_str(),
1305 http_reply->errorString().toStdString().c_str());
1306 ui->live_frame->setStyleSheet("");
1307 time_to_next_tally_ms = 1000;
1309 string contents = http_reply->readAll().toStdString();
1310 ui->live_frame->setStyleSheet(QString::fromStdString("background: " + contents));
1311 time_to_next_tally_ms = 100;
1313 http_reply->deleteLater();
1314 http_reply = nullptr;
1316 QTimer::singleShot(time_to_next_tally_ms, this, &MainWindow::start_tally);