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);
186 connect(ui->playlist_duplicate_btn, &QPushButton::clicked, this, &MainWindow::playlist_duplicate);
188 connect(ui->playlist_remove_btn, &QPushButton::clicked, this, &MainWindow::playlist_remove);
189 QShortcut *delete_key = new QShortcut(QKeySequence(Qt::Key_Delete), ui->playlist);
190 connect(delete_key, &QShortcut::activated, [this] {
191 if (ui->playlist->hasFocus()) {
196 // TODO: support drag-and-drop.
197 connect(ui->playlist_move_up_btn, &QPushButton::clicked, [this] { playlist_move(-1); });
198 connect(ui->playlist_move_down_btn, &QPushButton::clicked, [this] { playlist_move(1); });
200 connect(ui->playlist->selectionModel(), &QItemSelectionModel::selectionChanged,
201 this, &MainWindow::playlist_selection_changed);
202 playlist_selection_changed(); // First time set-up.
204 preview_player.reset(new Player(ui->preview_display, Player::NO_STREAM_OUTPUT));
205 live_player.reset(new Player(ui->live_display, Player::HTTPD_STREAM_OUTPUT));
206 live_player->set_done_callback([this] {
207 post_to_main_thread([this] {
211 live_player->set_progress_callback([this](const map<uint64_t, double> &progress, double time_remaining) {
212 post_to_main_thread([this, progress, time_remaining] {
213 live_player_clip_progress(progress, time_remaining);
216 set_output_status("paused");
217 enable_or_disable_queue_button();
219 defer_timeout = new QTimer(this);
220 defer_timeout->setSingleShot(true);
221 connect(defer_timeout, &QTimer::timeout, this, &MainWindow::defer_timer_expired);
222 ui->undo_action->setEnabled(true);
224 connect(ui->clip_list->selectionModel(), &QItemSelectionModel::currentChanged,
225 this, &MainWindow::clip_list_selection_changed);
226 enable_or_disable_queue_button();
228 // Find out how many cameras we have in the existing frames;
229 // if none, we start with two cameras.
232 lock_guard<mutex> lock(frame_mu);
233 for (size_t stream_idx = 2; stream_idx < MAX_STREAMS; ++stream_idx) {
234 if (!frames[stream_idx].empty()) {
235 num_cameras = stream_idx + 1;
239 change_num_cameras();
241 if (!global_flags.tally_url.empty()) {
245 if (!global_flags.midi_mapping_filename.empty()) {
246 MIDIMappingProto midi_mapping;
247 if (!load_midi_mapping_from_file(global_flags.midi_mapping_filename, &midi_mapping)) {
248 fprintf(stderr, "Couldn't load MIDI mapping '%s'; exiting.\n",
249 global_flags.midi_mapping_filename.c_str());
252 midi_mapper.set_midi_mapping(midi_mapping);
254 midi_mapper.refresh_lights();
255 midi_mapper.start_thread();
258 void MainWindow::change_num_cameras()
260 assert(num_cameras >= displays.size()); // We only add, never remove.
262 // Make new display rows.
263 unsigned display_rows = (num_cameras + 1) / 2;
264 ui->video_displays->setStretch(1, display_rows);
265 for (unsigned i = displays.size(); i < num_cameras; ++i) {
266 QFrame *frame = new QFrame(this);
267 frame->setAutoFillBackground(true);
269 QLayout *layout = new QGridLayout(frame);
270 frame->setLayout(layout);
271 layout->setContentsMargins(3, 3, 3, 3);
273 JPEGFrameView *display = new JPEGFrameView(frame);
274 display->setAutoFillBackground(true);
275 layout->addWidget(display);
277 ui->input_displays->addWidget(frame, i / 2, i % 2);
278 display->set_overlay(to_string(i + 1));
280 QPushButton *preview_btn = new QPushButton(this);
281 preview_btn->setMaximumSize(20, 17);
282 preview_btn->setText(QString::fromStdString(to_string(i + 1)));
283 ui->preview_layout->addWidget(preview_btn);
285 displays.emplace_back(FrameAndDisplay{ frame, display, preview_btn });
287 connect(display, &JPEGFrameView::clicked, preview_btn, &QPushButton::click);
288 QShortcut *shortcut = new QShortcut(QKeySequence(Qt::Key_1 + i), this);
289 connect(shortcut, &QShortcut::activated, preview_btn, &QPushButton::click);
291 connect(preview_btn, &QPushButton::clicked, [this, i] { preview_angle_clicked(i); });
294 cliplist_clips->change_num_cameras(num_cameras);
295 playlist_clips->change_num_cameras(num_cameras);
297 QMetaObject::invokeMethod(this, "relayout", Qt::QueuedConnection);
300 MainWindow::~MainWindow()
302 // Empty so that we can forward-declare Player in the .h file.
305 void MainWindow::cue_in_clicked()
307 if (!cliplist_clips->empty() && cliplist_clips->back()->pts_out < 0) {
308 cliplist_clips->mutable_back()->pts_in = current_pts;
311 clip.pts_in = max<int64_t>(current_pts - lrint(global_flags.cue_point_padding_seconds * TIMEBASE), 0);
312 cliplist_clips->add_clip(clip);
313 playlist_selection_changed();
316 // Select the item so that we can jog it.
317 ui->clip_list->setFocus();
318 QModelIndex index = cliplist_clips->index(cliplist_clips->size() - 1, int(ClipList::Column::IN));
319 ui->clip_list->selectionModel()->setCurrentIndex(index, QItemSelectionModel::ClearAndSelect);
320 ui->clip_list->scrollToBottom();
321 enable_or_disable_queue_button();
324 void MainWindow::cue_out_clicked()
326 if (cliplist_clips->empty()) {
330 cliplist_clips->mutable_back()->pts_out = current_pts + lrint(global_flags.cue_point_padding_seconds * TIMEBASE);
332 // Select the item so that we can jog it.
333 ui->clip_list->setFocus();
334 QModelIndex index = cliplist_clips->index(cliplist_clips->size() - 1, int(ClipList::Column::OUT));
335 ui->clip_list->selectionModel()->setCurrentIndex(index, QItemSelectionModel::ClearAndSelect);
336 ui->clip_list->scrollToBottom();
337 enable_or_disable_queue_button();
340 void MainWindow::queue_clicked()
342 // See also enable_or_disable_queue_button().
344 if (cliplist_clips->empty()) {
348 QItemSelectionModel *selected = ui->clip_list->selectionModel();
349 if (!selected->hasSelection()) {
350 Clip clip = *cliplist_clips->back();
352 if (clip.pts_out != -1) {
353 playlist_clips->add_clip(clip);
354 playlist_selection_changed();
355 ui->playlist->scrollToBottom();
360 QModelIndex index = selected->currentIndex();
361 Clip clip = *cliplist_clips->clip(index.row());
362 if (cliplist_clips->is_camera_column(index.column())) {
363 clip.stream_idx = index.column() - int(ClipList::Column::CAMERA_1);
365 clip.stream_idx = ui->preview_display->get_stream_idx();
368 if (clip.pts_out != -1) {
369 playlist_clips->add_clip(clip);
370 playlist_selection_changed();
371 ui->playlist->scrollToBottom();
372 if (!ui->playlist->selectionModel()->hasSelection()) {
373 // TODO: Figure out why this doesn't always seem to actually select the row.
374 QModelIndex bottom = playlist_clips->index(playlist_clips->size() - 1, 0);
375 ui->playlist->setCurrentIndex(bottom);
380 void MainWindow::preview_clicked()
382 // See also enable_or_disable_preview_button().
384 if (ui->playlist->hasFocus()) {
385 // Allow the playlist as preview iff it has focus and something is selected.
386 QItemSelectionModel *selected = ui->playlist->selectionModel();
387 if (selected->hasSelection()) {
388 QModelIndex index = selected->currentIndex();
389 const Clip &clip = *playlist_clips->clip(index.row());
390 preview_player->play(clip);
395 if (cliplist_clips->empty())
398 QItemSelectionModel *selected = ui->clip_list->selectionModel();
399 if (!selected->hasSelection()) {
400 preview_player->play(*cliplist_clips->back());
404 QModelIndex index = selected->currentIndex();
405 Clip clip = *cliplist_clips->clip(index.row());
406 if (cliplist_clips->is_camera_column(index.column())) {
407 clip.stream_idx = index.column() - int(ClipList::Column::CAMERA_1);
409 clip.stream_idx = ui->preview_display->get_stream_idx();
411 preview_player->play(clip);
414 void MainWindow::preview_angle_clicked(unsigned stream_idx)
416 preview_player->override_angle(stream_idx);
418 // Change the selection if we were previewing a clip from the clip list.
419 // (The only other thing we could be showing is a pts scrub, and if so,
420 // that would be selected.)
421 QItemSelectionModel *selected = ui->clip_list->selectionModel();
422 if (selected->hasSelection()) {
423 QModelIndex cell = selected->selectedIndexes()[0];
424 int column = int(ClipList::Column::CAMERA_1) + stream_idx;
425 selected->setCurrentIndex(cell.sibling(cell.row(), column), QItemSelectionModel::ClearAndSelect);
429 void MainWindow::playlist_duplicate()
431 QItemSelectionModel *selected = ui->playlist->selectionModel();
432 if (!selected->hasSelection()) {
433 // Should have been grayed out, but OK.
436 QModelIndexList rows = selected->selectedRows();
437 int first = rows.front().row(), last = rows.back().row();
438 playlist_clips->duplicate_clips(first, last);
439 playlist_selection_changed();
442 void MainWindow::playlist_remove()
444 QItemSelectionModel *selected = ui->playlist->selectionModel();
445 if (!selected->hasSelection()) {
446 // Should have been grayed out, but OK.
449 QModelIndexList rows = selected->selectedRows();
450 int first = rows.front().row(), last = rows.back().row();
451 playlist_clips->erase_clips(first, last);
453 // TODO: select the next one in the list?
455 playlist_selection_changed();
458 void MainWindow::playlist_move(int delta)
460 QItemSelectionModel *selected = ui->playlist->selectionModel();
461 if (!selected->hasSelection()) {
462 // Should have been grayed out, but OK.
466 QModelIndexList rows = selected->selectedRows();
467 int first = rows.front().row(), last = rows.back().row();
468 if ((delta == -1 && first == 0) ||
469 (delta == 1 && size_t(last) == playlist_clips->size() - 1)) {
470 // Should have been grayed out, but OK.
474 playlist_clips->move_clips(first, last, delta);
475 playlist_selection_changed();
478 void MainWindow::jog_internal(JogDestination jog_destination, int row, int column, int stream_idx, int pts_delta)
480 constexpr int camera_pts_per_pixel = 1500; // One click of most mice (15 degrees), multiplied by the default wheel_sensitivity.
482 int in_column, out_column, camera_column;
483 if (jog_destination == JOG_CLIP_LIST) {
484 in_column = int(ClipList::Column::IN);
485 out_column = int(ClipList::Column::OUT);
487 } else if (jog_destination == JOG_PLAYLIST) {
488 in_column = int(PlayList::Column::IN);
489 out_column = int(PlayList::Column::OUT);
490 camera_column = int(PlayList::Column::CAMERA);
495 currently_deferring_model_changes = true;
497 current_change_id = (jog_destination == JOG_CLIP_LIST) ? "cliplist:" : "playlist:";
498 ClipProxy clip = (jog_destination == JOG_CLIP_LIST) ? cliplist_clips->mutable_clip(row) : playlist_clips->mutable_clip(row);
499 if (jog_destination == JOG_PLAYLIST) {
500 stream_idx = clip->stream_idx;
503 if (column == in_column) {
504 current_change_id += "in:" + to_string(row);
505 int64_t pts = clip->pts_in + pts_delta;
506 set_pts_in(pts, current_pts, clip);
507 preview_single_frame(pts, stream_idx, FIRST_AT_OR_AFTER);
508 } else if (column == out_column) {
509 current_change_id += "out:" + to_string(row);
510 int64_t pts = clip->pts_out + pts_delta;
511 pts = std::max(pts, clip->pts_in);
512 pts = std::min(pts, current_pts);
514 preview_single_frame(pts, stream_idx, LAST_BEFORE);
515 } else if (column == camera_column) {
516 current_change_id += "camera:" + to_string(row);
517 int angle_degrees = pts_delta;
518 if (last_mousewheel_camera_row == row) {
519 angle_degrees += leftover_angle_degrees;
522 int stream_idx = clip->stream_idx + angle_degrees / camera_pts_per_pixel;
523 stream_idx = std::max(stream_idx, 0);
524 stream_idx = std::min<int>(stream_idx, num_cameras - 1);
525 clip->stream_idx = stream_idx;
527 last_mousewheel_camera_row = row;
528 leftover_angle_degrees = angle_degrees % camera_pts_per_pixel;
530 // Don't update the live view, that's rarely what the operator wants.
533 currently_deferring_model_changes = false;
536 void MainWindow::defer_timer_expired()
538 state_changed(deferred_state);
541 void MainWindow::content_changed()
543 // If we are playing, update the part of the playlist that's not playing yet.
544 vector<ClipWithID> clips;
545 for (unsigned row = 0; row < playlist_clips->size(); ++row) {
546 clips.emplace_back(*playlist_clips->clip_with_id(row));
548 live_player->splice_play(clips);
550 // Serialize the state.
551 if (defer_timeout->isActive() &&
552 (!currently_deferring_model_changes || deferred_change_id != current_change_id)) {
553 // There's some deferred event waiting, but this event is unrelated.
554 // So it's time to short-circuit that timer and do the work it wanted to do.
555 defer_timeout->stop();
556 state_changed(deferred_state);
559 *state.mutable_clip_list() = cliplist_clips->serialize();
560 *state.mutable_play_list() = playlist_clips->serialize();
561 if (currently_deferring_model_changes) {
562 deferred_change_id = current_change_id;
563 deferred_state = std::move(state);
564 defer_timeout->start(200);
567 state_changed(state);
570 void MainWindow::state_changed(const StateProto &state)
572 db.store_state(state);
575 ui->redo_action->setEnabled(false);
577 undo_stack.push_back(state);
578 ui->undo_action->setEnabled(undo_stack.size() > 1);
580 // Make sure it doesn't grow without bounds.
581 while (undo_stack.size() >= 100) {
582 undo_stack.pop_front();
586 void MainWindow::save_settings()
588 SettingsProto settings;
589 settings.set_interpolation_quality(global_flags.interpolation_quality + 1);
590 settings.set_cue_point_padding_seconds(global_flags.cue_point_padding_seconds);
591 db.store_settings(settings);
594 void MainWindow::play_clicked()
596 if (playlist_clips->empty())
599 QItemSelectionModel *selected = ui->playlist->selectionModel();
601 if (!selected->hasSelection()) {
604 start_row = selected->selectedRows(0)[0].row();
607 vector<ClipWithID> clips;
608 for (unsigned row = start_row; row < playlist_clips->size(); ++row) {
609 clips.emplace_back(*playlist_clips->clip_with_id(row));
611 live_player->play(clips);
612 playlist_clips->set_progress({ { start_row, 0.0f } });
613 ui->playlist->selectionModel()->clear();
614 playlist_selection_changed();
616 ui->stop_btn->setEnabled(true);
619 void MainWindow::stop_clicked()
622 fake_clip.pts_in = 0;
623 fake_clip.pts_out = 0;
624 playlist_clips->set_progress({});
625 live_player->play(fake_clip);
626 ui->stop_btn->setEnabled(false);
629 void MainWindow::speed_slider_changed(int percent)
631 float speed = percent / 100.0f;
632 ui->speed_label->setText(QString::fromStdString(to_string(percent) + "%"));
633 live_player->set_master_speed(speed);
636 void MainWindow::live_player_done()
638 playlist_selection_changed();
639 playlist_clips->set_progress({});
640 ui->stop_btn->setEnabled(false);
643 void MainWindow::live_player_clip_progress(const map<uint64_t, double> &progress, double time_remaining)
645 playlist_clips->set_progress(progress);
646 set_output_status(format_duration(time_remaining) + " left");
649 void MainWindow::resizeEvent(QResizeEvent *event)
651 QMainWindow::resizeEvent(event);
653 // Ask for a relayout, but only after the event loop is done doing relayout
654 // on everything else.
655 QMetaObject::invokeMethod(this, "relayout", Qt::QueuedConnection);
658 void MainWindow::relayout()
660 ui->live_display->setMinimumWidth(ui->live_display->height() * 16 / 9);
661 ui->preview_display->setMinimumWidth(ui->preview_display->height() * 16 / 9);
664 bool MainWindow::eventFilter(QObject *watched, QEvent *event)
666 constexpr int dead_zone_pixels = 3; // To avoid that simple clicks get misinterpreted.
667 int scrub_sensitivity = 100; // pts units per pixel.
668 int wheel_sensitivity = 100; // pts units per degree.
670 if (event->type() == QEvent::FocusIn || event->type() == QEvent::FocusOut) {
671 enable_or_disable_preview_button();
672 hidden_jog_column = -1;
675 unsigned stream_idx = ui->preview_display->get_stream_idx();
677 if (watched == ui->clip_list) {
678 if (event->type() == QEvent::FocusOut) {
679 highlight_camera_input(-1);
684 if (event->type() != QEvent::Wheel) {
685 last_mousewheel_camera_row = -1;
688 if (event->type() == QEvent::MouseButtonPress) {
689 QMouseEvent *mouse = (QMouseEvent *)event;
691 QTableView *destination;
694 if (watched == ui->clip_list->viewport()) {
695 destination = ui->clip_list;
696 type = SCRUBBING_CLIP_LIST;
697 } else if (watched == ui->playlist->viewport()) {
698 destination = ui->playlist;
699 type = SCRUBBING_PLAYLIST;
703 int column = destination->columnAt(mouse->x());
704 int row = destination->rowAt(mouse->y());
705 if (column == -1 || row == -1)
708 if (type == SCRUBBING_CLIP_LIST) {
709 if (ClipList::Column(column) == ClipList::Column::IN) {
710 scrub_pts_origin = cliplist_clips->clip(row)->pts_in;
711 preview_single_frame(scrub_pts_origin, stream_idx, FIRST_AT_OR_AFTER);
712 } else if (ClipList::Column(column) == ClipList::Column::OUT) {
713 scrub_pts_origin = cliplist_clips->clip(row)->pts_out;
714 preview_single_frame(scrub_pts_origin, stream_idx, LAST_BEFORE);
719 if (PlayList::Column(column) == PlayList::Column::IN) {
720 scrub_pts_origin = playlist_clips->clip(row)->pts_in;
721 preview_single_frame(scrub_pts_origin, stream_idx, FIRST_AT_OR_AFTER);
722 } else if (PlayList::Column(column) == PlayList::Column::OUT) {
723 scrub_pts_origin = playlist_clips->clip(row)->pts_out;
724 preview_single_frame(scrub_pts_origin, stream_idx, LAST_BEFORE);
732 scrub_column = column;
733 scrub_x_origin = mouse->x();
735 } else if (event->type() == QEvent::MouseMove) {
736 QMouseEvent *mouse = (QMouseEvent *)event;
737 if (mouse->modifiers() & Qt::KeyboardModifier::ShiftModifier) {
738 scrub_sensitivity *= 10;
739 wheel_sensitivity *= 10;
741 if (mouse->modifiers() & Qt::KeyboardModifier::AltModifier) { // Note: Shift + Alt cancel each other out.
742 scrub_sensitivity /= 10;
743 wheel_sensitivity /= 10;
746 int offset = mouse->x() - scrub_x_origin;
748 if (offset >= dead_zone_pixels) {
749 adjusted_offset = offset - dead_zone_pixels;
750 } else if (offset < -dead_zone_pixels) {
751 adjusted_offset = offset + dead_zone_pixels;
756 int64_t pts = scrub_pts_origin + adjusted_offset * scrub_sensitivity;
757 currently_deferring_model_changes = true;
758 if (scrub_type == SCRUBBING_CLIP_LIST) {
759 ClipProxy clip = cliplist_clips->mutable_clip(scrub_row);
760 if (scrub_column == int(ClipList::Column::IN)) {
761 current_change_id = "cliplist:in:" + to_string(scrub_row);
762 set_pts_in(pts, current_pts, clip);
763 preview_single_frame(pts, stream_idx, FIRST_AT_OR_AFTER);
765 current_change_id = "cliplist:out" + to_string(scrub_row);
766 pts = std::max(pts, clip->pts_in);
767 pts = std::min(pts, current_pts);
769 preview_single_frame(pts, stream_idx, LAST_BEFORE);
772 ClipProxy clip = playlist_clips->mutable_clip(scrub_row);
773 if (scrub_column == int(PlayList::Column::IN)) {
774 current_change_id = "playlist:in:" + to_string(scrub_row);
775 set_pts_in(pts, current_pts, clip);
776 preview_single_frame(pts, clip->stream_idx, FIRST_AT_OR_AFTER);
778 current_change_id = "playlist:out:" + to_string(scrub_row);
779 pts = std::max(pts, clip->pts_in);
780 pts = std::min(pts, current_pts);
782 preview_single_frame(pts, clip->stream_idx, LAST_BEFORE);
785 currently_deferring_model_changes = false;
787 return true; // Don't use this mouse movement for selecting things.
789 } else if (event->type() == QEvent::Wheel) {
790 QWheelEvent *wheel = (QWheelEvent *)event;
791 int angle_delta = wheel->angleDelta().y();
792 if (wheel->modifiers() & Qt::KeyboardModifier::ShiftModifier) {
793 scrub_sensitivity *= 10;
794 wheel_sensitivity *= 10;
796 if (wheel->modifiers() & Qt::KeyboardModifier::AltModifier) { // Note: Shift + Alt cancel each other out.
797 scrub_sensitivity /= 10;
798 wheel_sensitivity /= 10;
799 angle_delta = wheel->angleDelta().x(); // Qt ickiness.
802 QTableView *destination;
803 JogDestination jog_destination;
804 if (watched == ui->clip_list->viewport()) {
805 destination = ui->clip_list;
806 jog_destination = JOG_CLIP_LIST;
807 last_mousewheel_camera_row = -1;
808 } else if (watched == ui->playlist->viewport()) {
809 destination = ui->playlist;
810 jog_destination = JOG_PLAYLIST;
811 if (destination->columnAt(wheel->x()) != int(PlayList::Column::CAMERA)) {
812 last_mousewheel_camera_row = -1;
815 last_mousewheel_camera_row = -1;
819 int column = destination->columnAt(wheel->x());
820 int row = destination->rowAt(wheel->y());
821 if (column == -1 || row == -1)
824 // Only adjust pts with the wheel if the given row is selected.
825 if (!destination->hasFocus() ||
826 row != destination->selectionModel()->currentIndex().row()) {
830 jog_internal(jog_destination, row, column, stream_idx, angle_delta * wheel_sensitivity);
831 return true; // Don't scroll.
832 } else if (event->type() == QEvent::MouseButtonRelease) {
838 void MainWindow::preview_single_frame(int64_t pts, unsigned stream_idx, MainWindow::Rounding rounding)
840 if (rounding == LAST_BEFORE) {
841 lock_guard<mutex> lock(frame_mu);
842 if (frames[stream_idx].empty())
844 auto it = find_last_frame_before(frames[stream_idx], pts);
845 if (it != frames[stream_idx].end()) {
849 assert(rounding == FIRST_AT_OR_AFTER);
850 lock_guard<mutex> lock(frame_mu);
851 if (frames[stream_idx].empty())
853 auto it = find_first_frame_at_or_after(frames[stream_idx], pts);
854 if (it != frames[stream_idx].end()) {
860 fake_clip.pts_in = pts;
861 fake_clip.pts_out = pts + 1;
862 fake_clip.stream_idx = stream_idx;
863 preview_player->play(fake_clip);
866 void MainWindow::playlist_selection_changed()
868 enable_or_disable_preview_button();
870 QItemSelectionModel *selected = ui->playlist->selectionModel();
871 bool any_selected = selected->hasSelection();
872 ui->playlist_duplicate_btn->setEnabled(any_selected);
873 ui->playlist_remove_btn->setEnabled(any_selected);
874 ui->playlist_move_up_btn->setEnabled(
875 any_selected && selected->selectedRows().front().row() > 0);
876 ui->playlist_move_down_btn->setEnabled(
877 any_selected && selected->selectedRows().back().row() < int(playlist_clips->size()) - 1);
879 ui->play_btn->setEnabled(!playlist_clips->empty());
880 midi_mapper.set_play_enabled(!playlist_clips->empty());
883 set_output_status("paused");
885 vector<ClipWithID> clips;
886 for (size_t row = selected->selectedRows().front().row(); row < playlist_clips->size(); ++row) {
887 clips.emplace_back(*playlist_clips->clip_with_id(row));
889 double remaining = compute_total_time(clips);
890 set_output_status(format_duration(remaining) + " ready");
894 void MainWindow::clip_list_selection_changed(const QModelIndex ¤t, const QModelIndex &previous)
896 int camera_selected = -1;
897 if (cliplist_clips->is_camera_column(current.column())) {
898 camera_selected = current.column() - int(ClipList::Column::CAMERA_1);
900 // See the comment on hidden_jog_column.
901 if (current.row() != previous.row()) {
902 hidden_jog_column = -1;
903 } else if (hidden_jog_column == -1) {
904 hidden_jog_column = previous.column();
907 hidden_jog_column = -1;
909 highlight_camera_input(camera_selected);
910 enable_or_disable_queue_button();
913 void MainWindow::report_disk_space(off_t free_bytes, double estimated_seconds_left)
916 if (estimated_seconds_left < 60.0) {
917 strcpy(time_str, "<font color=\"red\">Less than a minute</font>");
918 } else if (estimated_seconds_left < 1800.0) { // Less than half an hour: Xm Ys (red).
919 int s = lrintf(estimated_seconds_left);
922 snprintf(time_str, sizeof(time_str), "<font color=\"red\">%dm %ds</font>", m, s);
923 } else if (estimated_seconds_left < 3600.0) { // Less than an hour: Xm.
924 int m = lrintf(estimated_seconds_left / 60.0);
925 snprintf(time_str, sizeof(time_str), "%dm", m);
926 } else if (estimated_seconds_left < 36000.0) { // Less than ten hours: Xh Ym.
927 int m = lrintf(estimated_seconds_left / 60.0);
930 snprintf(time_str, sizeof(time_str), "%dh %dm", h, m);
931 } else { // More than ten hours: Xh.
932 int h = lrintf(estimated_seconds_left / 3600.0);
933 snprintf(time_str, sizeof(time_str), "%dh", h);
936 snprintf(buf, sizeof(buf), "Disk free: %'.0f MB (approx. %s)", free_bytes / 1048576.0, time_str);
938 std::string label = buf;
940 post_to_main_thread([this, label] {
941 disk_free_label->setText(QString::fromStdString(label));
942 ui->menuBar->setCornerWidget(disk_free_label); // Need to set this again for the sizing to get right.
946 void MainWindow::exit_triggered()
951 void MainWindow::export_cliplist_clip_multitrack_triggered()
953 QItemSelectionModel *selected = ui->clip_list->selectionModel();
954 if (!selected->hasSelection()) {
956 msgbox.setText("No clip selected in the clip list. Select one and try exporting again.");
961 QModelIndex index = selected->currentIndex();
962 Clip clip = *cliplist_clips->clip(index.row());
963 QString filename = QFileDialog::getSaveFileName(this,
964 "Export multitrack clip", QString(), tr("Matroska video files (*.mkv)"));
965 if (filename.isNull()) {
969 if (!filename.endsWith(".mkv")) {
972 export_multitrack_clip(filename.toStdString(), clip);
975 void MainWindow::export_playlist_clip_interpolated_triggered()
977 QItemSelectionModel *selected = ui->playlist->selectionModel();
978 if (!selected->hasSelection()) {
980 msgbox.setText("No clip selected in the playlist. Select one and try exporting again.");
985 QString filename = QFileDialog::getSaveFileName(this,
986 "Export interpolated clip", QString(), tr("Matroska video files (*.mkv)"));
987 if (filename.isNull()) {
991 if (!filename.endsWith(".mkv")) {
996 QModelIndexList rows = selected->selectedRows();
997 for (QModelIndex index : rows) {
998 clips.push_back(*playlist_clips->clip(index.row()));
1000 export_interpolated_clip(filename.toStdString(), clips);
1003 void MainWindow::manual_triggered()
1005 if (!QDesktopServices::openUrl(QUrl("https://nageru.sesse.net/doc/"))) {
1007 msgbox.setText("Could not launch manual in web browser.\nPlease see https://nageru.sesse.net/doc/ manually.");
1012 void MainWindow::about_triggered()
1014 AboutDialog("Futatabi", "Multicamera slow motion video server").exec();
1017 void MainWindow::undo_triggered()
1019 // Finish any deferred action.
1020 if (defer_timeout->isActive()) {
1021 defer_timeout->stop();
1022 state_changed(deferred_state);
1025 StateProto redo_state;
1026 *redo_state.mutable_clip_list() = cliplist_clips->serialize();
1027 *redo_state.mutable_play_list() = playlist_clips->serialize();
1028 redo_stack.push_back(std::move(redo_state));
1029 ui->redo_action->setEnabled(true);
1031 assert(undo_stack.size() > 1);
1033 // Pop off the current state, which is always at the top of the stack.
1034 undo_stack.pop_back();
1036 StateProto state = undo_stack.back();
1037 ui->undo_action->setEnabled(undo_stack.size() > 1);
1039 replace_model(ui->clip_list, &cliplist_clips, new ClipList(state.clip_list()));
1040 replace_model(ui->playlist, &playlist_clips, new PlayList(state.play_list()));
1042 db.store_state(state);
1045 void MainWindow::redo_triggered()
1047 assert(!redo_stack.empty());
1049 ui->undo_action->setEnabled(true);
1050 ui->redo_action->setEnabled(true);
1052 undo_stack.push_back(std::move(redo_stack.back()));
1053 redo_stack.pop_back();
1054 ui->undo_action->setEnabled(true);
1055 ui->redo_action->setEnabled(!redo_stack.empty());
1057 const StateProto &state = undo_stack.back();
1058 replace_model(ui->clip_list, &cliplist_clips, new ClipList(state.clip_list()));
1059 replace_model(ui->playlist, &playlist_clips, new PlayList(state.play_list()));
1061 db.store_state(state);
1064 void MainWindow::quality_toggled(int quality, bool checked)
1069 global_flags.interpolation_quality = quality;
1070 if (quality != 0 && // Turning interpolation off is always possible.
1071 quality != flow_initialized_interpolation_quality) {
1073 msgbox.setText(QString::fromStdString(
1074 "The interpolation quality for the main output cannot be changed at runtime, "
1075 "except being turned completely off; it will take effect for exported files "
1076 "only until next restart. The live output quality thus remains at " +
1077 to_string(flow_initialized_interpolation_quality) + "."));
1084 void MainWindow::padding_toggled(double seconds, bool checked)
1089 global_flags.cue_point_padding_seconds = seconds;
1093 void MainWindow::highlight_camera_input(int stream_idx)
1095 for (unsigned i = 0; i < num_cameras; ++i) {
1096 if (unsigned(stream_idx) == i) {
1097 displays[i].frame->setStyleSheet("background: rgb(0,255,0)");
1099 displays[i].frame->setStyleSheet("");
1102 midi_mapper.highlight_camera_input(stream_idx);
1105 void MainWindow::enable_or_disable_preview_button()
1107 // Follows the logic in preview_clicked().
1109 if (ui->playlist->hasFocus()) {
1110 // Allow the playlist as preview iff it has focus and something is selected.
1111 // TODO: Is this part really relevant?
1112 QItemSelectionModel *selected = ui->playlist->selectionModel();
1113 if (selected->hasSelection()) {
1114 ui->preview_btn->setEnabled(true);
1115 midi_mapper.set_preview_enabled(true);
1120 // TODO: Perhaps only enable this if something is actually selected.
1121 ui->preview_btn->setEnabled(!cliplist_clips->empty());
1122 midi_mapper.set_preview_enabled(!cliplist_clips->empty());
1125 void MainWindow::enable_or_disable_queue_button()
1127 // Follows the logic in queue_clicked().
1128 // TODO: Perhaps only enable this if something is actually selected.
1132 if (cliplist_clips->empty()) {
1135 QItemSelectionModel *selected = ui->clip_list->selectionModel();
1136 if (!selected->hasSelection()) {
1137 Clip clip = *cliplist_clips->back();
1138 enabled = clip.pts_out != -1;
1140 QModelIndex index = selected->currentIndex();
1141 Clip clip = *cliplist_clips->clip(index.row());
1142 enabled = clip.pts_out != -1;
1146 ui->queue_btn->setEnabled(enabled);
1147 midi_mapper.set_queue_enabled(enabled);
1150 void MainWindow::set_output_status(const string &status)
1152 ui->live_label->setText(QString::fromStdString("Current output (" + status + ")"));
1153 if (live_player != nullptr) {
1154 live_player->set_pause_status(status);
1157 lock_guard<mutex> lock(queue_status_mu);
1158 queue_status = status;
1161 pair<string, string> MainWindow::get_queue_status() const
1163 lock_guard<mutex> lock(queue_status_mu);
1164 return { queue_status, "text/plain" };
1167 void MainWindow::display_frame(unsigned stream_idx, const FrameOnDisk &frame)
1169 if (stream_idx >= MAX_STREAMS) {
1170 fprintf(stderr, "WARNING: Ignoring too-high stream index %u.\n", stream_idx);
1173 if (stream_idx >= num_cameras) {
1174 post_to_main_thread_and_wait([this, stream_idx] {
1175 num_cameras = stream_idx + 1;
1176 change_num_cameras();
1179 displays[stream_idx].display->setFrame(stream_idx, frame);
1182 void MainWindow::preview()
1184 post_to_main_thread([this] {
1189 void MainWindow::queue()
1191 post_to_main_thread([this] {
1196 void MainWindow::play()
1198 post_to_main_thread([this] {
1203 void MainWindow::jog(int delta)
1205 post_to_main_thread([this, delta] {
1206 int64_t pts_delta = delta * (TIMEBASE / 60); // One click = frame at 60 fps.
1207 if (ui->playlist->hasFocus()) {
1208 QModelIndex selected = ui->playlist->selectionModel()->currentIndex();
1209 if (selected.column() != -1 && selected.row() != -1) {
1210 jog_internal(JOG_PLAYLIST, selected.row(), selected.column(), /*stream_idx=*/-1, pts_delta);
1212 } else if (ui->clip_list->hasFocus()) {
1213 QModelIndex selected = ui->clip_list->selectionModel()->currentIndex();
1214 if (cliplist_clips->is_camera_column(selected.column()) &&
1215 hidden_jog_column != -1) {
1216 // See the definition on hidden_jog_column.
1217 selected = selected.sibling(selected.row(), hidden_jog_column);
1218 ui->clip_list->selectionModel()->setCurrentIndex(selected, QItemSelectionModel::ClearAndSelect);
1219 hidden_jog_column = -1;
1221 if (selected.column() != -1 && selected.row() != -1) {
1222 jog_internal(JOG_CLIP_LIST, selected.row(), selected.column(), ui->preview_display->get_stream_idx(), pts_delta);
1228 void MainWindow::switch_camera(unsigned camera_idx)
1230 post_to_main_thread([this, camera_idx] {
1231 if (camera_idx < num_cameras) { // TODO: Also make this change a highlighted clip?
1232 preview_angle_clicked(camera_idx);
1237 void MainWindow::set_master_speed(float speed)
1239 speed = min(max(speed, 0.1f), 2.0f);
1241 post_to_main_thread([this, speed] {
1242 int percent = lrintf(speed * 100.0f);
1243 ui->speed_slider->blockSignals(true);
1244 ui->speed_slider->setValue(percent);
1245 ui->speed_slider->blockSignals(false);
1246 ui->speed_label->setText(QString::fromStdString(to_string(percent) + "%"));
1249 live_player->set_master_speed(speed);
1252 void MainWindow::cue_in()
1254 post_to_main_thread([this] { cue_in_clicked(); });
1257 void MainWindow::cue_out()
1259 post_to_main_thread([this] { cue_out_clicked(); });
1262 template<class Model>
1263 void MainWindow::replace_model(QTableView *view, Model **model, Model *new_model)
1265 QItemSelectionModel *old_selection_model = view->selectionModel();
1266 view->setModel(new_model);
1268 delete old_selection_model;
1270 connect(new_model, &Model::any_content_changed, this, &MainWindow::content_changed);
1273 void MainWindow::start_tally()
1275 http_reply = http.get(QNetworkRequest(QString::fromStdString(global_flags.tally_url)));
1276 connect(http_reply, &QNetworkReply::finished, this, &MainWindow::tally_received);
1279 void MainWindow::tally_received()
1281 unsigned time_to_next_tally_ms;
1282 if (http_reply->error()) {
1283 fprintf(stderr, "HTTP get of '%s' failed: %s\n", global_flags.tally_url.c_str(),
1284 http_reply->errorString().toStdString().c_str());
1285 ui->live_frame->setStyleSheet("");
1286 time_to_next_tally_ms = 1000;
1288 string contents = http_reply->readAll().toStdString();
1289 ui->live_frame->setStyleSheet(QString::fromStdString("background: " + contents));
1290 time_to_next_tally_ms = 100;
1292 http_reply->deleteLater();
1293 http_reply = nullptr;
1295 QTimer::singleShot(time_to_next_tally_ms, this, &MainWindow::start_tally);