]> git.sesse.net Git - nageru/blobdiff - futatabi/mainwindow.cpp
Make cue in/out highlight the right cell. More logical, and also helps with jogging.
[nageru] / futatabi / mainwindow.cpp
index 81ef10b3a4bb1e8ab1a4cd3e72502e3cfce65558..77a3ba35e35bebfdf31c5df258052c75dcffb1e7 100644 (file)
@@ -1,18 +1,21 @@
 #include "mainwindow.h"
 
-#include "shared/aboutdialog.h"
 #include "clip_list.h"
-#include "shared/disk_space_estimator.h"
+#include "export.h"
 #include "flags.h"
 #include "frame_on_disk.h"
 #include "player.h"
+#include "shared/aboutdialog.h"
+#include "shared/disk_space_estimator.h"
 #include "shared/post_to_main_thread.h"
 #include "shared/timebase.h"
 #include "ui_mainwindow.h"
 
 #include <QDesktopServices>
+#include <QFileDialog>
 #include <QMessageBox>
 #include <QMouseEvent>
+#include <QNetworkReply>
 #include <QShortcut>
 #include <QTimer>
 #include <QWheelEvent>
@@ -37,10 +40,83 @@ MainWindow::MainWindow()
        global_mainwindow = this;
        ui->setupUi(this);
 
+       // Load settings from database.
+       SettingsProto settings = db.get_settings();
+       if (!global_flags.interpolation_quality_set) {
+               if (settings.interpolation_quality() != 0) {
+                       global_flags.interpolation_quality = settings.interpolation_quality() - 1;
+               }
+       }
+       if (!global_flags.cue_point_padding_set) {
+               global_flags.cue_point_padding_seconds = settings.cue_point_padding_seconds();  // Default 0 is fine.
+       }
+       if (global_flags.interpolation_quality == 0) {
+               // Allocate something just for simplicity; we won't be using it
+               // unless the user changes runtime, in which case 1 is fine.
+               flow_initialized_interpolation_quality = 1;
+       } else {
+               flow_initialized_interpolation_quality = global_flags.interpolation_quality;
+       }
+       save_settings();
+
        // The menus.
        connect(ui->exit_action, &QAction::triggered, this, &MainWindow::exit_triggered);
+       connect(ui->export_cliplist_clip_multitrack_action, &QAction::triggered, this, &MainWindow::export_cliplist_clip_multitrack_triggered);
+       connect(ui->export_playlist_clip_interpolated_action, &QAction::triggered, this, &MainWindow::export_playlist_clip_interpolated_triggered);
        connect(ui->manual_action, &QAction::triggered, this, &MainWindow::manual_triggered);
        connect(ui->about_action, &QAction::triggered, this, &MainWindow::about_triggered);
+       connect(ui->undo_action, &QAction::triggered, this, &MainWindow::undo_triggered);
+       connect(ui->redo_action, &QAction::triggered, this, &MainWindow::redo_triggered);
+       ui->undo_action->setEnabled(false);
+       ui->redo_action->setEnabled(false);
+
+       // The quality group.
+       QActionGroup *quality_group = new QActionGroup(ui->interpolation_menu);
+       quality_group->addAction(ui->quality_0_action);
+       quality_group->addAction(ui->quality_1_action);
+       quality_group->addAction(ui->quality_2_action);
+       quality_group->addAction(ui->quality_3_action);
+       quality_group->addAction(ui->quality_4_action);
+       if (global_flags.interpolation_quality == 0) {
+               ui->quality_0_action->setChecked(true);
+       } else if (global_flags.interpolation_quality == 1) {
+               ui->quality_1_action->setChecked(true);
+       } else if (global_flags.interpolation_quality == 2) {
+               ui->quality_2_action->setChecked(true);
+       } else if (global_flags.interpolation_quality == 3) {
+               ui->quality_3_action->setChecked(true);
+       } else if (global_flags.interpolation_quality == 4) {
+               ui->quality_4_action->setChecked(true);
+       } else {
+               assert(false);
+       }
+       connect(ui->quality_0_action, &QAction::toggled, bind(&MainWindow::quality_toggled, this, 0, _1));
+       connect(ui->quality_1_action, &QAction::toggled, bind(&MainWindow::quality_toggled, this, 1, _1));
+       connect(ui->quality_2_action, &QAction::toggled, bind(&MainWindow::quality_toggled, this, 2, _1));
+       connect(ui->quality_3_action, &QAction::toggled, bind(&MainWindow::quality_toggled, this, 3, _1));
+       connect(ui->quality_4_action, &QAction::toggled, bind(&MainWindow::quality_toggled, this, 4, _1));
+
+       // The cue point padding group.
+       QActionGroup *padding_group = new QActionGroup(ui->interpolation_menu);
+       padding_group->addAction(ui->padding_0_action);
+       padding_group->addAction(ui->padding_1_action);
+       padding_group->addAction(ui->padding_2_action);
+       padding_group->addAction(ui->padding_5_action);
+       if (global_flags.cue_point_padding_seconds <= 1e-3) {
+               ui->padding_0_action->setChecked(true);
+       } else if (fabs(global_flags.cue_point_padding_seconds - 1.0) < 1e-3) {
+               ui->padding_1_action->setChecked(true);
+       } else if (fabs(global_flags.cue_point_padding_seconds - 2.0) < 1e-3) {
+               ui->padding_2_action->setChecked(true);
+       } else if (fabs(global_flags.cue_point_padding_seconds - 5.0) < 1e-3) {
+               ui->padding_5_action->setChecked(true);
+       } else {
+               // Nothing to check, which is fine.
+       }
+       connect(ui->padding_0_action, &QAction::toggled, bind(&MainWindow::padding_toggled, this, 0.0, _1));
+       connect(ui->padding_1_action, &QAction::toggled, bind(&MainWindow::padding_toggled, this, 1.0, _1));
+       connect(ui->padding_2_action, &QAction::toggled, bind(&MainWindow::padding_toggled, this, 2.0, _1));
+       connect(ui->padding_5_action, &QAction::toggled, bind(&MainWindow::padding_toggled, this, 5.0, _1));
 
        global_disk_space_estimator = new DiskSpaceEstimator(bind(&MainWindow::report_disk_space, this, _1, _2));
        disk_free_label = new QLabel(this);
@@ -48,6 +124,7 @@ MainWindow::MainWindow()
        ui->menuBar->setCornerWidget(disk_free_label);
 
        StateProto state = db.get_state();
+       undo_stack.push_back(state);  // The undo stack always has the current state on top.
 
        cliplist_clips = new ClipList(state.clip_list());
        ui->clip_list->setModel(cliplist_clips);
@@ -84,29 +161,8 @@ MainWindow::MainWindow()
        connect(play, &QShortcut::activated, ui->play_btn, &QPushButton::click);
        connect(ui->play_btn, &QPushButton::clicked, this, &MainWindow::play_clicked);
 
-       QShortcut *preview_1 = new QShortcut(QKeySequence(Qt::Key_1), this);
-       connect(preview_1, &QShortcut::activated, ui->preview_1_btn, &QPushButton::click);
-       connect(ui->input1_display, &JPEGFrameView::clicked, ui->preview_1_btn, &QPushButton::click);
-       connect(ui->preview_1_btn, &QPushButton::clicked, [this]{ preview_angle_clicked(0); });
-       ui->input1_display->set_overlay("1");
-
-       QShortcut *preview_2 = new QShortcut(QKeySequence(Qt::Key_2), this);
-       connect(preview_2, &QShortcut::activated, ui->preview_2_btn, &QPushButton::click);
-       connect(ui->input2_display, &JPEGFrameView::clicked, ui->preview_2_btn, &QPushButton::click);
-       connect(ui->preview_2_btn, &QPushButton::clicked, [this]{ preview_angle_clicked(1); });
-       ui->input2_display->set_overlay("2");
-
-       QShortcut *preview_3 = new QShortcut(QKeySequence(Qt::Key_3), this);
-       connect(preview_3, &QShortcut::activated, ui->preview_3_btn, &QPushButton::click);
-       connect(ui->input3_display, &JPEGFrameView::clicked, ui->preview_3_btn, &QPushButton::click);
-       connect(ui->preview_3_btn, &QPushButton::clicked, [this]{ preview_angle_clicked(2); });
-       ui->input3_display->set_overlay("3");
-
-       QShortcut *preview_4 = new QShortcut(QKeySequence(Qt::Key_4), this);
-       connect(preview_4, &QShortcut::activated, ui->preview_4_btn, &QPushButton::click);
-       connect(ui->input4_display, &JPEGFrameView::clicked, ui->preview_4_btn, &QPushButton::click);
-       connect(ui->preview_4_btn, &QPushButton::clicked, [this]{ preview_angle_clicked(3); });
-       ui->input4_display->set_overlay("4");
+       connect(ui->stop_btn, &QPushButton::clicked, this, &MainWindow::stop_clicked);
+       ui->stop_btn->setEnabled(false);
 
        connect(ui->playlist_duplicate_btn, &QPushButton::clicked, this, &MainWindow::playlist_duplicate);
 
@@ -119,24 +175,23 @@ MainWindow::MainWindow()
        });
 
        // TODO: support drag-and-drop.
-       connect(ui->playlist_move_up_btn, &QPushButton::clicked, [this]{ playlist_move(-1); });
-       connect(ui->playlist_move_down_btn, &QPushButton::clicked, [this]{ playlist_move(1); });
+       connect(ui->playlist_move_up_btn, &QPushButton::clicked, [this] { playlist_move(-1); });
+       connect(ui->playlist_move_down_btn, &QPushButton::clicked, [this] { playlist_move(1); });
 
        connect(ui->playlist->selectionModel(), &QItemSelectionModel::selectionChanged,
-               this, &MainWindow::playlist_selection_changed);
+               this, &MainWindow::playlist_selection_changed);
        playlist_selection_changed();  // First time set-up.
 
-       preview_player = new Player(ui->preview_display, /*also_output_to_stream=*/false);
-       live_player = new Player(ui->live_display, /*also_output_to_stream=*/true);
-       live_player->set_done_callback([this]{
-               post_to_main_thread([this]{
-                       live_player_clip_done();
+       preview_player.reset(new Player(ui->preview_display, Player::NO_STREAM_OUTPUT));
+       live_player.reset(new Player(ui->live_display, Player::HTTPD_STREAM_OUTPUT));
+       live_player->set_done_callback([this] {
+               post_to_main_thread([this] {
+                       live_player_done();
                });
        });
-       live_player->set_next_clip_callback(bind(&MainWindow::live_player_get_next_clip, this));
-       live_player->set_progress_callback([this](const map<size_t, double> &progress) {
-               post_to_main_thread([this, progress] {
-                       live_player_clip_progress(progress);
+       live_player->set_progress_callback([this](const map<uint64_t, double> &progress, double time_remaining) {
+               post_to_main_thread([this, progress, time_remaining] {
+                       live_player_clip_progress(progress, time_remaining);
                });
        });
        set_output_status("paused");
@@ -144,29 +199,107 @@ MainWindow::MainWindow()
        defer_timeout = new QTimer(this);
        defer_timeout->setSingleShot(true);
        connect(defer_timeout, &QTimer::timeout, this, &MainWindow::defer_timer_expired);
+       ui->undo_action->setEnabled(true);
 
        connect(ui->clip_list->selectionModel(), &QItemSelectionModel::currentChanged,
-               this, &MainWindow::clip_list_selection_changed);
+               this, &MainWindow::clip_list_selection_changed);
+
+       // Find out how many cameras we have in the existing frames;
+       // if none, we start with two cameras.
+       num_cameras = 2;
+       {
+               lock_guard<mutex> lock(frame_mu);
+               for (size_t stream_idx = 2; stream_idx < MAX_STREAMS; ++stream_idx) {
+                       if (!frames[stream_idx].empty()) {
+                               num_cameras = stream_idx + 1;
+                       }
+               }
+       }
+       change_num_cameras();
+
+       if (!global_flags.tally_url.empty()) {
+               start_tally();
+       }
+}
+
+void MainWindow::change_num_cameras()
+{
+       assert(num_cameras >= displays.size());  // We only add, never remove.
+
+       // Make new display rows.
+       unsigned display_rows = (num_cameras + 1) / 2;
+       ui->video_displays->setStretch(1, display_rows);
+       for (unsigned i = displays.size(); i < num_cameras; ++i) {
+               QFrame *frame = new QFrame(this);
+               frame->setAutoFillBackground(true);
+
+               QLayout *layout = new QGridLayout(frame);
+               frame->setLayout(layout);
+               layout->setContentsMargins(3, 3, 3, 3);
+
+               JPEGFrameView *display = new JPEGFrameView(frame);
+               display->setAutoFillBackground(true);
+               layout->addWidget(display);
+
+               ui->input_displays->addWidget(frame, i / 2, i % 2);
+               display->set_overlay(to_string(i + 1));
+
+               QPushButton *preview_btn = new QPushButton(this);
+               preview_btn->setMaximumSize(20, 17);
+               preview_btn->setText(QString::fromStdString(to_string(i + 1)));
+               ui->preview_layout->addWidget(preview_btn);
+
+               displays.emplace_back(FrameAndDisplay{ frame, display, preview_btn });
+
+               connect(display, &JPEGFrameView::clicked, preview_btn, &QPushButton::click);
+               QShortcut *shortcut = new QShortcut(QKeySequence(Qt::Key_1 + i), this);
+               connect(shortcut, &QShortcut::activated, preview_btn, &QPushButton::click);
+
+               connect(preview_btn, &QPushButton::clicked, [this, i] { preview_angle_clicked(i); });
+       }
+
+       cliplist_clips->change_num_cameras(num_cameras);
+       playlist_clips->change_num_cameras(num_cameras);
+
+       QMetaObject::invokeMethod(this, "relayout", Qt::QueuedConnection);
+}
+
+MainWindow::~MainWindow()
+{
+       // Empty so that we can forward-declare Player in the .h file.
 }
 
 void MainWindow::cue_in_clicked()
 {
        if (!cliplist_clips->empty() && cliplist_clips->back()->pts_out < 0) {
                cliplist_clips->mutable_back()->pts_in = current_pts;
-               return;
+       } else {
+               Clip clip;
+               clip.pts_in = max<int64_t>(current_pts - lrint(global_flags.cue_point_padding_seconds * TIMEBASE), 0);
+               cliplist_clips->add_clip(clip);
+               playlist_selection_changed();
        }
-       Clip clip;
-       clip.pts_in = current_pts;
-       cliplist_clips->add_clip(clip);
-       playlist_selection_changed();
+
+       // Select the item so that we can jog it.
+       ui->clip_list->setFocus();
+       QModelIndex index = cliplist_clips->index(cliplist_clips->size() - 1, int(ClipList::Column::IN));
+       ui->clip_list->selectionModel()->setCurrentIndex(index, QItemSelectionModel::ClearAndSelect);
+       ui->clip_list->scrollToBottom();
 }
 
 void MainWindow::cue_out_clicked()
 {
-       if (!cliplist_clips->empty()) {
-               cliplist_clips->mutable_back()->pts_out = current_pts;
-               // TODO: select the row in the clip list?
+       if (cliplist_clips->empty()) {
+               return;
        }
+
+       cliplist_clips->mutable_back()->pts_out = current_pts + lrint(global_flags.cue_point_padding_seconds * TIMEBASE);
+
+       // Select the item so that we can jog it.
+       ui->clip_list->setFocus();
+       QModelIndex index = cliplist_clips->index(cliplist_clips->size() - 1, int(ClipList::Column::OUT));
+       ui->clip_list->selectionModel()->setCurrentIndex(index, QItemSelectionModel::ClearAndSelect);
+       ui->clip_list->scrollToBottom();
 }
 
 void MainWindow::queue_clicked()
@@ -182,14 +315,14 @@ void MainWindow::queue_clicked()
                if (clip.pts_out != -1) {
                        playlist_clips->add_clip(clip);
                        playlist_selection_changed();
+                       ui->playlist->scrollToBottom();
                }
                return;
        }
 
        QModelIndex index = selected->currentIndex();
        Clip clip = *cliplist_clips->clip(index.row());
-       if (index.column() >= int(ClipList::Column::CAMERA_1) &&
-           index.column() <= int(ClipList::Column::CAMERA_4)) {
+       if (cliplist_clips->is_camera_column(index.column())) {
                clip.stream_idx = index.column() - int(ClipList::Column::CAMERA_1);
        } else {
                clip.stream_idx = ui->preview_display->get_stream_idx();
@@ -198,6 +331,12 @@ void MainWindow::queue_clicked()
        if (clip.pts_out != -1) {
                playlist_clips->add_clip(clip);
                playlist_selection_changed();
+               ui->playlist->scrollToBottom();
+               if (!ui->playlist->selectionModel()->hasSelection()) {
+                       // TODO: Figure out why this doesn't always seem to actually select the row.
+                       QModelIndex bottom = playlist_clips->index(playlist_clips->size() - 1, 0);
+                       ui->playlist->setCurrentIndex(bottom);
+               }
        }
 }
 
@@ -209,7 +348,7 @@ void MainWindow::preview_clicked()
                if (selected->hasSelection()) {
                        QModelIndex index = selected->currentIndex();
                        const Clip &clip = *playlist_clips->clip(index.row());
-                       preview_player->play_clip(clip, index.row(), clip.stream_idx);
+                       preview_player->play(clip);
                        return;
                }
        }
@@ -219,19 +358,18 @@ void MainWindow::preview_clicked()
 
        QItemSelectionModel *selected = ui->clip_list->selectionModel();
        if (!selected->hasSelection()) {
-               preview_player->play_clip(*cliplist_clips->back(), cliplist_clips->size() - 1, 0);
+               preview_player->play(*cliplist_clips->back());
                return;
        }
 
        QModelIndex index = selected->currentIndex();
-       unsigned stream_idx;
-       if (index.column() >= int(ClipList::Column::CAMERA_1) &&
-           index.column() <= int(ClipList::Column::CAMERA_4)) {
-               stream_idx = index.column() - int(ClipList::Column::CAMERA_1);
+       Clip clip = *cliplist_clips->clip(index.row());
+       if (cliplist_clips->is_camera_column(index.column())) {
+               clip.stream_idx = index.column() - int(ClipList::Column::CAMERA_1);
        } else {
-               stream_idx = ui->preview_display->get_stream_idx();
+               clip.stream_idx = ui->preview_display->get_stream_idx();
        }
-       preview_player->play_clip(*cliplist_clips->clip(index.row()), index.row(), stream_idx);
+       preview_player->play(clip);
 }
 
 void MainWindow::preview_angle_clicked(unsigned stream_idx)
@@ -305,6 +443,14 @@ void MainWindow::defer_timer_expired()
 
 void MainWindow::content_changed()
 {
+       // If we are playing, update the part of the playlist that's not playing yet.
+       vector<ClipWithID> clips;
+       for (unsigned row = 0; row < playlist_clips->size(); ++row) {
+               clips.emplace_back(*playlist_clips->clip_with_id(row));
+       }
+       live_player->splice_play(clips);
+
+       // Serialize the state.
        if (defer_timeout->isActive() &&
            (!currently_deferring_model_changes || deferred_change_id != current_change_id)) {
                // There's some deferred event waiting, but this event is unrelated.
@@ -327,6 +473,25 @@ void MainWindow::content_changed()
 void MainWindow::state_changed(const StateProto &state)
 {
        db.store_state(state);
+
+       redo_stack.clear();
+       ui->redo_action->setEnabled(false);
+
+       undo_stack.push_back(state);
+       ui->undo_action->setEnabled(undo_stack.size() > 1);
+
+       // Make sure it doesn't grow without bounds.
+       while (undo_stack.size() >= 100) {
+               undo_stack.pop_front();
+       }
+}
+
+void MainWindow::save_settings()
+{
+       SettingsProto settings;
+       settings.set_interpolation_quality(global_flags.interpolation_quality + 1);
+       settings.set_cue_point_padding_seconds(global_flags.cue_point_padding_seconds);
+       db.store_settings(settings);
 }
 
 void MainWindow::play_clicked()
@@ -335,89 +500,46 @@ void MainWindow::play_clicked()
                return;
 
        QItemSelectionModel *selected = ui->playlist->selectionModel();
-       int row;
+       unsigned start_row;
        if (!selected->hasSelection()) {
-               row = 0;
+               start_row = 0;
        } else {
-               row = selected->selectedRows(0)[0].row();
+               start_row = selected->selectedRows(0)[0].row();
        }
 
-       const Clip &clip = *playlist_clips->clip(row);
-       live_player->play_clip(clip, row, clip.stream_idx);
-       playlist_clips->set_progress({{ row, 0.0f }});
-       playlist_clips->set_currently_playing(row, 0.0f);
+       vector<ClipWithID> clips;
+       for (unsigned row = start_row; row < playlist_clips->size(); ++row) {
+               clips.emplace_back(*playlist_clips->clip_with_id(row));
+       }
+       live_player->play(clips);
+       playlist_clips->set_progress({ { start_row, 0.0f } });
+       ui->playlist->selectionModel()->clear();
        playlist_selection_changed();
-}
 
-void MainWindow::live_player_clip_done()
-{
-       int row = playlist_clips->get_currently_playing();
-       if (row == -1 || row == int(playlist_clips->size()) - 1) {
-               set_output_status("paused");
-               playlist_clips->set_progress({});
-               playlist_clips->set_currently_playing(-1, 0.0f);
-       } else {
-               playlist_clips->set_progress({{ row + 1, 0.0f }});
-               playlist_clips->set_currently_playing(row + 1, 0.0f);
-       }
+       ui->stop_btn->setEnabled(true);
 }
 
-pair<Clip, size_t> MainWindow::live_player_get_next_clip()
+void MainWindow::stop_clicked()
 {
-       // playlist_clips can only be accessed on the main thread.
-       // Hopefully, we won't have to wait too long for this to come back.
-       promise<pair<Clip, size_t>> clip_promise;
-       future<pair<Clip, size_t>> clip = clip_promise.get_future();
-       post_to_main_thread([this, &clip_promise] {
-               int row = playlist_clips->get_currently_playing();
-               if (row != -1 && row < int(playlist_clips->size()) - 1) {
-                       clip_promise.set_value(make_pair(*playlist_clips->clip(row + 1), row + 1));
-               } else {
-                       clip_promise.set_value(make_pair(Clip(), 0));
-               }
-       });
-       return clip.get();
+       Clip fake_clip;
+       fake_clip.pts_in = 0;
+       fake_clip.pts_out = 0;
+       playlist_clips->set_progress({});
+       live_player->play(fake_clip);
+       ui->stop_btn->setEnabled(false);
 }
 
-static string format_duration(double t)
+void MainWindow::live_player_done()
 {
-       int t_ms = lrint(t * 1e3);
-
-       int ms = t_ms % 1000;
-       t_ms /= 1000;
-       int s = t_ms % 60;
-       t_ms /= 60;
-       int m = t_ms;
-
-       char buf[256];
-       snprintf(buf, sizeof(buf), "%d:%02d.%03d", m, s, ms);
-       return buf;
+       playlist_selection_changed();
+       playlist_clips->set_progress({});
+       ui->stop_btn->setEnabled(false);
 }
 
-void MainWindow::live_player_clip_progress(const map<size_t, double> &progress)
+void MainWindow::live_player_clip_progress(const map<uint64_t, double> &progress, double time_remaining)
 {
        playlist_clips->set_progress(progress);
-
-       // Look at the last clip and then start counting from there.
-       assert(!progress.empty());
-       auto last_it = progress.end();
-       --last_it;
-       double remaining = 0.0;
-       double last_fade_time_seconds = 0.0;
-       for (size_t row = last_it->first; row < playlist_clips->size(); ++row) {
-               const Clip clip = *playlist_clips->clip(row);
-               double clip_length = double(clip.pts_out - clip.pts_in) / TIMEBASE / 0.5;  // FIXME: stop hardcoding speed.
-               if (row == last_it->first) {
-                       // A clip we're playing: Subtract the part we've already played.
-                       remaining = clip_length * (1.0 - last_it->second);
-               } else {
-                       // A clip we haven't played yet: Subtract the part that's overlapping
-                       // with a previous clip (due to fade).
-                       remaining += max(clip_length - last_fade_time_seconds, 0.0);
-               }
-               last_fade_time_seconds = min(clip_length, clip.fade_time_seconds);
-       }
-       set_output_status(format_duration(remaining) + " left");
+       set_output_status(format_duration(time_remaining) + " left");
 }
 
 void MainWindow::resizeEvent(QResizeEvent *event)
@@ -449,9 +571,9 @@ void set_pts_in(int64_t pts, int64_t current_pts, ClipProxy &clip)
 bool MainWindow::eventFilter(QObject *watched, QEvent *event)
 {
        constexpr int dead_zone_pixels = 3;  // To avoid that simple clicks get misinterpreted.
-       constexpr int scrub_sensitivity = 100;  // pts units per pixel.
-       constexpr int wheel_sensitivity = 100;  // pts units per degree.
        constexpr int camera_degrees_per_pixel = 15;  // One click of most mice.
+       int scrub_sensitivity = 100;  // pts units per pixel.
+       int wheel_sensitivity = 100;  // pts units per degree.
 
        unsigned stream_idx = ui->preview_display->get_stream_idx();
 
@@ -514,8 +636,16 @@ bool MainWindow::eventFilter(QObject *watched, QEvent *event)
                scrub_x_origin = mouse->x();
                scrub_type = type;
        } else if (event->type() == QEvent::MouseMove) {
+               QMouseEvent *mouse = (QMouseEvent *)event;
+               if (mouse->modifiers() & Qt::KeyboardModifier::ShiftModifier) {
+                       scrub_sensitivity *= 10;
+                       wheel_sensitivity *= 10;
+               }
+               if (mouse->modifiers() & Qt::KeyboardModifier::AltModifier) {  // Note: Shift + Alt cancel each other out.
+                       scrub_sensitivity /= 10;
+                       wheel_sensitivity /= 10;
+               }
                if (scrubbing) {
-                       QMouseEvent *mouse = (QMouseEvent *)event;
                        int offset = mouse->x() - scrub_x_origin;
                        int adjusted_offset;
                        if (offset >= dead_zone_pixels) {
@@ -561,6 +691,16 @@ bool MainWindow::eventFilter(QObject *watched, QEvent *event)
                }
        } else if (event->type() == QEvent::Wheel) {
                QWheelEvent *wheel = (QWheelEvent *)event;
+               int angle_delta = wheel->angleDelta().y();
+               if (wheel->modifiers() & Qt::KeyboardModifier::ShiftModifier) {
+                       scrub_sensitivity *= 10;
+                       wheel_sensitivity *= 10;
+               }
+               if (wheel->modifiers() & Qt::KeyboardModifier::AltModifier) {  // Note: Shift + Alt cancel each other out.
+                       scrub_sensitivity /= 10;
+                       wheel_sensitivity /= 10;
+                       angle_delta = wheel->angleDelta().x();  // Qt ickiness.
+               }
 
                QTableView *destination;
                int in_column, out_column, camera_column;
@@ -581,7 +721,8 @@ bool MainWindow::eventFilter(QObject *watched, QEvent *event)
                }
                int column = destination->columnAt(wheel->x());
                int row = destination->rowAt(wheel->y());
-               if (column == -1 || row == -1) return false;
+               if (column == -1 || row == -1)
+                       return false;
 
                // Only adjust pts with the wheel if the given row is selected.
                if (!destination->hasFocus() ||
@@ -592,8 +733,7 @@ bool MainWindow::eventFilter(QObject *watched, QEvent *event)
                currently_deferring_model_changes = true;
                {
                        current_change_id = (watched == ui->clip_list->viewport()) ? "cliplist:" : "playlist:";
-                       ClipProxy clip = (watched == ui->clip_list->viewport()) ?
-                               cliplist_clips->mutable_clip(row) : playlist_clips->mutable_clip(row);
+                       ClipProxy clip = (watched == ui->clip_list->viewport()) ? cliplist_clips->mutable_clip(row) : playlist_clips->mutable_clip(row);
                        if (watched == ui->playlist->viewport()) {
                                stream_idx = clip->stream_idx;
                        }
@@ -603,26 +743,26 @@ bool MainWindow::eventFilter(QObject *watched, QEvent *event)
                        }
                        if (column == in_column) {
                                current_change_id += "in:" + to_string(row);
-                               int64_t pts = clip->pts_in + wheel->angleDelta().y() * wheel_sensitivity;
+                               int64_t pts = clip->pts_in + angle_delta * wheel_sensitivity;
                                set_pts_in(pts, current_pts, clip);
                                preview_single_frame(pts, stream_idx, FIRST_AT_OR_AFTER);
                        } else if (column == out_column) {
                                current_change_id += "out:" + to_string(row);
-                               int64_t pts = clip->pts_out + wheel->angleDelta().y() * wheel_sensitivity;
+                               int64_t pts = clip->pts_out + angle_delta * wheel_sensitivity;
                                pts = std::max(pts, clip->pts_in);
                                pts = std::min(pts, current_pts);
                                clip->pts_out = pts;
                                preview_single_frame(pts, stream_idx, LAST_BEFORE);
                        } else if (column == camera_column) {
                                current_change_id += "camera:" + to_string(row);
-                               int angle_degrees = wheel->angleDelta().y();
+                               int angle_degrees = angle_delta;
                                if (last_mousewheel_camera_row == row) {
                                        angle_degrees += leftover_angle_degrees;
                                }
 
                                int stream_idx = clip->stream_idx + angle_degrees / camera_degrees_per_pixel;
                                stream_idx = std::max(stream_idx, 0);
-                               stream_idx = std::min(stream_idx, NUM_CAMERAS - 1);
+                               stream_idx = std::min<int>(stream_idx, num_cameras - 1);
                                clip->stream_idx = stream_idx;
 
                                last_mousewheel_camera_row = row;
@@ -645,8 +785,7 @@ void MainWindow::preview_single_frame(int64_t pts, unsigned stream_idx, MainWind
                lock_guard<mutex> lock(frame_mu);
                if (frames[stream_idx].empty())
                        return;
-               auto it = lower_bound(frames[stream_idx].begin(), frames[stream_idx].end(), pts,
-                       [](const FrameOnDisk &frame, int64_t pts) { return frame.pts < pts; });
+               auto it = find_last_frame_before(frames[stream_idx], pts);
                if (it != frames[stream_idx].end()) {
                        pts = it->pts;
                }
@@ -655,8 +794,7 @@ void MainWindow::preview_single_frame(int64_t pts, unsigned stream_idx, MainWind
                lock_guard<mutex> lock(frame_mu);
                if (frames[stream_idx].empty())
                        return;
-               auto it = upper_bound(frames[stream_idx].begin(), frames[stream_idx].end(), pts - 1,
-                       [](int64_t pts, const FrameOnDisk &frame) { return pts < frame.pts; });
+               auto it = find_first_frame_at_or_after(frames[stream_idx], pts);
                if (it != frames[stream_idx].end()) {
                        pts = it->pts;
                }
@@ -665,7 +803,7 @@ void MainWindow::preview_single_frame(int64_t pts, unsigned stream_idx, MainWind
        Clip fake_clip;
        fake_clip.pts_in = pts;
        fake_clip.pts_out = pts + 1;
-       preview_player->play_clip(fake_clip, 0, stream_idx);
+       preview_player->play(fake_clip);
 }
 
 void MainWindow::playlist_selection_changed()
@@ -683,11 +821,11 @@ void MainWindow::playlist_selection_changed()
        if (!any_selected) {
                set_output_status("paused");
        } else {
-               double remaining = 0.0;
-               for (int row = selected->selectedRows().front().row(); row < int(playlist_clips->size()); ++row) {
-                       const Clip clip = *playlist_clips->clip(row);
-                       remaining += double(clip.pts_out - clip.pts_in) / TIMEBASE / 0.5;  // FIXME: stop hardcoding speed.
+               vector<ClipWithID> clips;
+               for (size_t row = selected->selectedRows().front().row(); row < playlist_clips->size(); ++row) {
+                       clips.emplace_back(*playlist_clips->clip_with_id(row));
                }
+               double remaining = compute_total_time(clips);
                set_output_status(format_duration(remaining) + " ready");
        }
 }
@@ -695,8 +833,7 @@ void MainWindow::playlist_selection_changed()
 void MainWindow::clip_list_selection_changed(const QModelIndex &current, const QModelIndex &)
 {
        int camera_selected = -1;
-       if (current.column() >= int(ClipList::Column::CAMERA_1) &&
-           current.column() <= int(ClipList::Column::CAMERA_4)) {
+       if (cliplist_clips->is_camera_column(current.column())) {
                camera_selected = current.column() - int(ClipList::Column::CAMERA_1);
        }
        highlight_camera_input(camera_selected);
@@ -740,6 +877,58 @@ void MainWindow::exit_triggered()
        close();
 }
 
+void MainWindow::export_cliplist_clip_multitrack_triggered()
+{
+       QItemSelectionModel *selected = ui->clip_list->selectionModel();
+       if (!selected->hasSelection()) {
+               QMessageBox msgbox;
+               msgbox.setText("No clip selected in the clip list. Select one and try exporting again.");
+               msgbox.exec();
+               return;
+       }
+
+       QModelIndex index = selected->currentIndex();
+       Clip clip = *cliplist_clips->clip(index.row());
+       QString filename = QFileDialog::getSaveFileName(this,
+               "Export multitrack clip", QString(), tr("Matroska video files (*.mkv)"));
+       if (filename.isNull()) {
+               // Cancel.
+               return;
+       }
+       if (!filename.endsWith(".mkv")) {
+               filename += ".mkv";
+       }
+       export_multitrack_clip(filename.toStdString(), clip);
+}
+
+void MainWindow::export_playlist_clip_interpolated_triggered()
+{
+       QItemSelectionModel *selected = ui->playlist->selectionModel();
+       if (!selected->hasSelection()) {
+               QMessageBox msgbox;
+               msgbox.setText("No clip selected in the playlist. Select one and try exporting again.");
+               msgbox.exec();
+               return;
+       }
+
+       QString filename = QFileDialog::getSaveFileName(this,
+               "Export interpolated clip", QString(), tr("Matroska video files (*.mkv)"));
+       if (filename.isNull()) {
+               // Cancel.
+               return;
+       }
+       if (!filename.endsWith(".mkv")) {
+               filename += ".mkv";
+       }
+
+       vector<Clip> clips;
+       QModelIndexList rows = selected->selectedRows();
+       for (QModelIndex index : rows) {
+               clips.push_back(*playlist_clips->clip(index.row()));
+       }
+       export_interpolated_clip(filename.toStdString(), clips);
+}
+
 void MainWindow::manual_triggered()
 {
        if (!QDesktopServices::openUrl(QUrl("https://nageru.sesse.net/doc/"))) {
@@ -754,39 +943,157 @@ void MainWindow::about_triggered()
        AboutDialog("Futatabi", "Multicamera slow motion video server").exec();
 }
 
-void MainWindow::highlight_camera_input(int stream_idx)
+void MainWindow::undo_triggered()
 {
-       if (stream_idx == 0) {
-               ui->input1_frame->setStyleSheet("background: rgb(0,255,0)");
-       } else {
-               ui->input1_frame->setStyleSheet("");
+       // Finish any deferred action.
+       if (defer_timeout->isActive()) {
+               defer_timeout->stop();
+               state_changed(deferred_state);
        }
-       if (stream_idx == 1) {
-               ui->input2_frame->setStyleSheet("background: rgb(0,255,0)");
-       } else {
-               ui->input2_frame->setStyleSheet("");
+
+       StateProto redo_state;
+       *redo_state.mutable_clip_list() = cliplist_clips->serialize();
+       *redo_state.mutable_play_list() = playlist_clips->serialize();
+       redo_stack.push_back(std::move(redo_state));
+       ui->redo_action->setEnabled(true);
+
+       assert(undo_stack.size() > 1);
+
+       // Pop off the current state, which is always at the top of the stack.
+       undo_stack.pop_back();
+
+       StateProto state = undo_stack.back();
+       ui->undo_action->setEnabled(undo_stack.size() > 1);
+
+       replace_model(ui->clip_list, &cliplist_clips, new ClipList(state.clip_list()));
+       replace_model(ui->playlist, &playlist_clips, new PlayList(state.play_list()));
+
+       db.store_state(state);
+}
+
+void MainWindow::redo_triggered()
+{
+       assert(!redo_stack.empty());
+
+       ui->undo_action->setEnabled(true);
+       ui->redo_action->setEnabled(true);
+
+       undo_stack.push_back(std::move(redo_stack.back()));
+       redo_stack.pop_back();
+       ui->undo_action->setEnabled(true);
+       ui->redo_action->setEnabled(!redo_stack.empty());
+
+       const StateProto &state = undo_stack.back();
+       replace_model(ui->clip_list, &cliplist_clips, new ClipList(state.clip_list()));
+       replace_model(ui->playlist, &playlist_clips, new PlayList(state.play_list()));
+
+       db.store_state(state);
+}
+
+void MainWindow::quality_toggled(int quality, bool checked)
+{
+       if (!checked) {
+               return;
        }
-       if (stream_idx == 2) {
-               ui->input3_frame->setStyleSheet("background: rgb(0,255,0)");
-       } else {
-               ui->input3_frame->setStyleSheet("");
+       global_flags.interpolation_quality = quality;
+       if (quality != 0 &&  // Turning interpolation off is always possible.
+           quality != flow_initialized_interpolation_quality) {
+               QMessageBox msgbox;
+               msgbox.setText(QString::fromStdString(
+                       "The interpolation quality for the main output cannot be changed at runtime, "
+                       "except being turned completely off; it will take effect for exported files "
+                       "only until next restart. The live output quality thus remains at " +
+                       to_string(flow_initialized_interpolation_quality) + "."));
+               msgbox.exec();
        }
-       if (stream_idx == 3) {
-               ui->input4_frame->setStyleSheet("background: rgb(0,255,0)");
-       } else {
-               ui->input4_frame->setStyleSheet("");
+
+       save_settings();
+}
+
+void MainWindow::padding_toggled(double seconds, bool checked)
+{
+       if (!checked) {
+               return;
+       }
+       global_flags.cue_point_padding_seconds = seconds;
+       save_settings();
+}
+
+void MainWindow::highlight_camera_input(int stream_idx)
+{
+       for (unsigned i = 0; i < num_cameras; ++i) {
+               if (unsigned(stream_idx) == i) {
+                       displays[i].frame->setStyleSheet("background: rgb(0,255,0)");
+               } else {
+                       displays[i].frame->setStyleSheet("");
+               }
        }
 }
 
 void MainWindow::set_output_status(const string &status)
 {
        ui->live_label->setText(QString::fromStdString("Current output (" + status + ")"));
+       if (live_player != nullptr) {
+               live_player->set_pause_status(status);
+       }
 
        lock_guard<mutex> lock(queue_status_mu);
        queue_status = status;
 }
 
-pair<string, string> MainWindow::get_queue_status() const {
+pair<string, string> MainWindow::get_queue_status() const
+{
        lock_guard<mutex> lock(queue_status_mu);
-       return {queue_status, "text/plain"};
+       return { queue_status, "text/plain" };
+}
+
+void MainWindow::display_frame(unsigned stream_idx, const FrameOnDisk &frame)
+{
+       if (stream_idx >= MAX_STREAMS) {
+               fprintf(stderr, "WARNING: Ignoring too-high stream index %u.\n", stream_idx);
+               return;
+       }
+       if (stream_idx >= num_cameras) {
+               post_to_main_thread_and_wait([this, stream_idx] {
+                       num_cameras = stream_idx + 1;
+                       change_num_cameras();
+               });
+       }
+       displays[stream_idx].display->setFrame(stream_idx, frame);
+}
+
+template<class Model>
+void MainWindow::replace_model(QTableView *view, Model **model, Model *new_model)
+{
+       QItemSelectionModel *old_selection_model = view->selectionModel();
+       view->setModel(new_model);
+       delete *model;
+       delete old_selection_model;
+       *model = new_model;
+       connect(new_model, &Model::any_content_changed, this, &MainWindow::content_changed);
+}
+
+void MainWindow::start_tally()
+{
+       http_reply = http.get(QNetworkRequest(QString::fromStdString(global_flags.tally_url)));
+       connect(http_reply, &QNetworkReply::finished, this, &MainWindow::tally_received);
+}
+
+void MainWindow::tally_received()
+{
+       unsigned time_to_next_tally_ms;
+       if (http_reply->error()) {
+               fprintf(stderr, "HTTP get of '%s' failed: %s\n", global_flags.tally_url.c_str(),
+                       http_reply->errorString().toStdString().c_str());
+               ui->live_frame->setStyleSheet("");
+               time_to_next_tally_ms = 1000;
+       } else {
+               string contents = http_reply->readAll().toStdString();
+               ui->live_frame->setStyleSheet(QString::fromStdString("background: " + contents));
+               time_to_next_tally_ms = 100;
+       }
+       http_reply->deleteLater();
+       http_reply = nullptr;
+
+       QTimer::singleShot(time_to_next_tally_ms, this, &MainWindow::start_tally);
 }