From bc4627e957ed8ef8deff9e6413dc932b60d0f918 Mon Sep 17 00:00:00 2001 From: blocksmith314 Date: Wed, 25 Nov 2026 00:04:49 +0800 Subject: [PATCH] feat(seek): asynchronous seek with cached preview Add DecoderService::RequestSeek(frame, generation), which runs in the worker thread, answers cache hits immediately and otherwise emits a preview from the nearest cached frame before decoding and emitting the exact frame. The service now owns the FrameCache. MainWindow requests seeks asynchronously, ignores results whose generation is stale, and moves the display/audio/perf-log side effects to the FrameReady slot. The initial frame after loading stays synchronous so the window shows content before returning. GUI tests wait for the async result. Refs #70 --- decoderservice.cpp | 53 ++++++++++++++ decoderservice.h | 8 +++ framecache.cpp | 14 ++++ framecache.h | 1 + mainwindow.cpp | 167 ++++++++++++++++++++++++--------------------- mainwindow.h | 12 +++- test/test_gui.cpp | 7 +- 7 files changed, 179 insertions(+), 83 deletions(-) diff --git a/decoderservice.cpp b/decoderservice.cpp index 3f1a24d..c16a3e7 100644 --- a/decoderservice.cpp +++ b/decoderservice.cpp @@ -1,5 +1,6 @@ #include "decoderservice.h" +#include #include DecoderService::DecoderService(QObject* parent) : QObject(parent) {} @@ -75,5 +76,57 @@ QVariantMap DecoderService::DecodeNext() { result["ok"] = true; result["image"] = frame.image; result["pts"] = frame.pts_sec; + cache_.Insert(decoder_->CurrentFrameIndex() - 1, frame.image, frame.pts_sec); return result; } + +void DecoderService::RequestSeek(int frame, quint64 generation) { + QVariantMap result; + result["generation"] = generation; + result["target"] = frame; + if (!decoder_) { + result["ok"] = false; + emit SeekFailed(result); + return; + } + + if (const CachedFrame* hit = cache_.Find(frame)) { + result["ok"] = true; + result["from_cache"] = true; + result["image"] = hit->image; + result["pts"] = hit->pts_sec; + emit FrameReady(result); + return; + } + + if (const CachedFrame* nearest = cache_.Nearest(frame)) { + QVariantMap preview; + preview["generation"] = generation; + preview["target"] = frame; + preview["image"] = nearest->image; + preview["from_frame"] = nearest->index; + emit PreviewReady(preview); + } + + if (!decoder_->SeekToFrame(frame)) { + result["ok"] = false; + emit SeekFailed(result); + return; + } + DecodedFrame decoded; + if (!decoder_->DecodeNextFrame(decoded)) { + result["ok"] = false; + emit SeekFailed(result); + return; + } + const FFmpegDecoder::SeekStats stats = decoder_->LastSeekStats(); + cache_.Insert(frame, decoded.image, decoded.pts_sec); + result["ok"] = true; + result["from_cache"] = false; + result["image"] = decoded.image; + result["pts"] = decoded.pts_sec; + result["frames_decoded"] = stats.frames_decoded; + result["seek_io_ms"] = (qint64)stats.seek_io_ms; + result["decode_ms"] = (qint64)stats.decode_ms; + emit FrameReady(result); +} diff --git a/decoderservice.h b/decoderservice.h index b004b62..5bbe7f9 100644 --- a/decoderservice.h +++ b/decoderservice.h @@ -7,6 +7,7 @@ #include #include "decoder.h" +#include "framecache.h" // Owns the FFmpegDecoder and lives in a worker thread. Callers use blocking // invocations for now; asynchronous seek/preview will be layered on top. @@ -21,9 +22,16 @@ class DecoderService : public QObject { QVariantMap Close(); QVariantMap Seek(int frame); QVariantMap DecodeNext(); + void RequestSeek(int frame, quint64 generation); + + signals: + void PreviewReady(QVariantMap result); + void FrameReady(QVariantMap result); + void SeekFailed(QVariantMap result); private: std::unique_ptr decoder_; + FrameCache cache_; }; #endif // DIA_DECODERSERVICE_H_ diff --git a/framecache.cpp b/framecache.cpp index 1949ded..55b7b29 100644 --- a/framecache.cpp +++ b/framecache.cpp @@ -1,5 +1,6 @@ #include "framecache.h" +#include #include FrameCache::FrameCache(std::size_t limit_bytes) : limit_bytes_(limit_bytes) {} @@ -15,6 +16,19 @@ void FrameCache::Clear() { bytes_ = 0; } +const CachedFrame* FrameCache::Nearest(int index) const { + const CachedFrame* best = nullptr; + int best_distance = 0; + for (auto it = entries_.begin(); it != entries_.end(); ++it) { + const int distance = std::abs(it.key() - index); + if (best == nullptr || distance < best_distance) { + best = &it->frame; + best_distance = distance; + } + } + return best; +} + const CachedFrame* FrameCache::Find(int index) { auto it = entries_.find(index); if (it == entries_.end()) { diff --git a/framecache.h b/framecache.h index adc3cd3..df8be36 100644 --- a/framecache.h +++ b/framecache.h @@ -21,6 +21,7 @@ class FrameCache { void SetLimitBytes(std::size_t limit_bytes); void Clear(); const CachedFrame* Find(int index); + const CachedFrame* Nearest(int index) const; void Insert(int index, const QImage& image, double pts_sec); std::size_t CurrentBytes() const { return bytes_; } diff --git a/mainwindow.cpp b/mainwindow.cpp index 4d5d3dc..fd318b3 100644 --- a/mainwindow.cpp +++ b/mainwindow.cpp @@ -81,6 +81,12 @@ MainWindow::MainWindow(QWidget* parent) connect(&decode_thread_, &QThread::finished, decoder_service_, &QObject::deleteLater); decode_thread_.start(); + connect(decoder_service_, &DecoderService::PreviewReady, this, + &MainWindow::OnSeekPreview, Qt::QueuedConnection); + connect(decoder_service_, &DecoderService::FrameReady, this, + &MainWindow::OnSeekFrameReady, Qt::QueuedConnection); + connect(decoder_service_, &DecoderService::SeekFailed, this, + &MainWindow::OnSeekFailed, Qt::QueuedConnection); SetupUi(); } @@ -757,8 +763,6 @@ QVariantMap MainWindow::DecodeFrame() { } void MainWindow::StartPlayer() { - frame_cache_.Clear(); - display_from_cache_ = false; auto& stats = analyzer_.stats(); player_timer_->stop(); is_playing_ = false; @@ -829,7 +833,7 @@ void MainWindow::StartPlayer() { video_size_ = video_label_->size(); current_frame_index_ = -1; - ShowFrameAt(0); + ShowFirstFrameBlocking(); } void MainWindow::ShowFrame(const QImage& image, int frame_idx) { @@ -837,7 +841,6 @@ void MainWindow::ShowFrame(const QImage& image, int frame_idx) { return; } current_image_ = image; - frame_cache_.Insert(frame_idx, image, current_pts_); QSize target = video_size_.isValid() ? video_size_ : video_label_->size(); QImage scaled = image.scaled(target, Qt::KeepAspectRatio, Qt::SmoothTransformation); @@ -906,90 +909,89 @@ void MainWindow::ShowFrameAt(int idx) { return; } - if (!is_playing_) { - if (const CachedFrame* cached = frame_cache_.Find(idx)) { - current_frame_index_ = idx; - current_pts_ = cached->pts_sec; - ShowFrame(cached->image, idx); - display_from_cache_ = true; - if (perf_log_enabled_) { - AppendPerf( - QString("cache %1 frame=%2") - .arg( - QFileInfo(QString::fromStdString(current_path_)).fileName()) - .arg(idx)); - } - return; - } + pending_seek_frame_ = idx; + pending_seek_jump_ = + (idx < current_frame_index_ || idx > current_frame_index_ + 1); + seek_pending_ = true; + const quint64 generation = ++seek_generation_; + if (perf_log_enabled_) { + seek_request_timer_.start(); } + QMetaObject::invokeMethod(decoder_service_, "RequestSeek", + Qt::QueuedConnection, Q_ARG(int, idx), + Q_ARG(quint64, generation)); +} - const bool perf = perf_log_enabled_; - QElapsedTimer perf_timer; - qint64 seek_ms = 0; - qint64 decode_ms = 0; - if (perf) { - perf_timer.start(); +void MainWindow::ShowFirstFrameBlocking() { + if (total_frames_ <= 0 || !decoder_service_) { + return; } - - // Decode sequentially when moving forward by one; otherwise seek. - // If the previous frame came from the cache, the decoder may be at a - // different position; force it to resync before decoding anything new. - const bool resync_needed = display_from_cache_; - display_from_cache_ = false; - - const bool jump = - (idx < current_frame_index_ || idx > current_frame_index_ + 1); - if (resync_needed || jump) { - const QVariantMap seek_result = SeekDecoder(idx); - if (!seek_result.value("ok").toBool()) { - return; - } - last_seek_stats_.used_container = - seek_result.value("used_container").toBool(); - last_seek_stats_.used_raw_keyframe = - seek_result.value("used_raw_keyframe").toBool(); - last_seek_stats_.frames_decoded = - seek_result.value("frames_decoded").toInt(); - last_seek_stats_.seek_io_ms = seek_result.value("seek_io_ms").toLongLong(); - last_seek_stats_.decode_ms = seek_result.value("decode_ms").toLongLong(); - if (perf) { - seek_ms = perf_timer.restart(); - } + const QVariantMap seek_result = SeekDecoder(0); + if (!seek_result.value("ok").toBool()) { + return; } - const QVariantMap decode_result = DecodeFrame(); if (!decode_result.value("ok").toBool()) { - // End of decodable frames (container may have fewer than the NAL count). - player_timer_->stop(); - is_playing_ = false; - play_btn_->setText("Play"); return; } - if (perf) { - decode_ms = perf_timer.restart(); + current_frame_index_ = 0; + current_pts_ = decode_result.value("pts").toDouble(); + ShowFrame(decode_result.value("image").value(), 0); +} + +void MainWindow::OnSeekPreview(const QVariantMap& result) { + if (result.value("generation").toULongLong() != seek_generation_) { + return; } + const QImage image = result.value("image").value(); + if (image.isNull() || !video_label_) { + return; + } + QSize target = video_size_.isValid() ? video_size_ : video_label_->size(); + video_label_->setPixmap(QPixmap::fromImage( + image.scaled(target, Qt::KeepAspectRatio, Qt::SmoothTransformation))); +} + +void MainWindow::OnSeekFrameReady(const QVariantMap& result) { + if (result.value("generation").toULongLong() != seek_generation_) { + return; + } + const int idx = result.value("target").toInt(); + const QImage image = result.value("image").value(); + if (image.isNull()) { + seek_pending_ = false; + return; + } + + const bool from_cache = result.value("from_cache").toBool(); + const qint64 total_ms = + seek_request_timer_.isValid() ? seek_request_timer_.elapsed() : 0; + seek_pending_ = false; current_frame_index_ = idx; - current_pts_ = decode_result.value("pts").toDouble(); - ShowFrame(decode_result.value("image").value(), idx); - if (perf) { - const qint64 display_ms = perf_timer.elapsed(); - const auto seek_stats = - jump ? last_seek_stats_ : FFmpegDecoder::SeekStats{}; - AppendPerf( - QString("%1 %2 frame=%3 total=%4ms seek=%5 decode=%6 display=%7 " - "seek_frames=%8 seek_io=%9ms") - .arg(jump ? "seek " : "step ") - .arg(QFileInfo(QString::fromStdString(current_path_)).fileName()) - .arg(idx) - .arg(seek_ms + decode_ms + display_ms) - .arg(seek_ms) - .arg(decode_ms) - .arg(display_ms) - .arg(seek_stats.frames_decoded) - .arg(seek_stats.seek_io_ms)); + current_pts_ = result.value("pts").toDouble(); + ShowFrame(image, idx); + + if (perf_log_enabled_) { + if (from_cache) { + AppendPerf( + QString("cache %1 frame=%2") + .arg(QFileInfo(QString::fromStdString(current_path_)).fileName()) + .arg(idx)); + } else { + AppendPerf( + QString("%1 %2 frame=%3 total=%4ms seek_io=%5ms seek_decode=%6ms " + "seek_frames=%7") + .arg(pending_seek_jump_ ? "seek " : "step ") + .arg(QFileInfo(QString::fromStdString(current_path_)).fileName()) + .arg(idx) + .arg(total_ms) + .arg(result.value("seek_io_ms").toLongLong()) + .arg(result.value("decode_ms").toLongLong()) + .arg(result.value("frames_decoded").toInt())); + } } - if (jump) { + if (pending_seek_jump_) { has_pending_ = false; clock_start_pts_ = current_pts_; play_clock_.restart(); @@ -1003,6 +1005,16 @@ void MainWindow::ShowFrameAt(int idx) { } } +void MainWindow::OnSeekFailed(const QVariantMap& result) { + if (result.value("generation").toULongLong() != seek_generation_) { + return; + } + seek_pending_ = false; + if (is_playing_) { + StopPlayback(); + } +} + void MainWindow::HighlightFrame(int frame_idx) { nal_model_->SetHighlightedFrame(frame_idx); if (frame_idx < 0) { @@ -1124,6 +1136,9 @@ void MainWindow::OnPlayerTick() { // Raw streams have no container timestamps: fall back to the fixed timer. if (!has_timestamps_) { + if (seek_pending_) { + return; + } if (current_frame_index_ + 1 >= total_frames_) { StopPlayback(); return; diff --git a/mainwindow.h b/mainwindow.h index 5f999ba..3ca49d0 100644 --- a/mainwindow.h +++ b/mainwindow.h @@ -62,7 +62,11 @@ class MainWindow : public QMainWindow { void ShowAbout(); void ShowShortcuts(); void UpdatePositionLabel(); + void ShowFirstFrameBlocking(); void SetPerfLogVisible(bool visible); + void OnSeekPreview(const QVariantMap& result); + void OnSeekFrameReady(const QVariantMap& result); + void OnSeekFailed(const QVariantMap& result); private: enum class ProgressMode { kFrames, kTime }; @@ -103,7 +107,6 @@ class MainWindow : public QMainWindow { QThread decode_thread_; bool has_timestamps_ = false; double duration_sec_ = 0.0; - FFmpegDecoder::SeekStats last_seek_stats_; AudioPlayer* audio_ = nullptr; std::string current_path_; @@ -137,8 +140,11 @@ class MainWindow : public QMainWindow { QPlainTextEdit* perf_log_ = nullptr; QAction* perf_action_ = nullptr; bool perf_log_enabled_ = false; - FrameCache frame_cache_; - bool display_from_cache_ = false; + quint64 seek_generation_ = 0; + int pending_seek_frame_ = -1; + bool pending_seek_jump_ = false; + bool seek_pending_ = false; + QElapsedTimer seek_request_timer_; ProgressMode progress_mode_ = ProgressMode::kFrames; bool is_playing_ = false; diff --git a/test/test_gui.cpp b/test/test_gui.cpp index d24e080..b8800ee 100644 --- a/test/test_gui.cpp +++ b/test/test_gui.cpp @@ -341,11 +341,11 @@ TEST(MainWindowTest, StepForwardUsesSpinBoxValue) { QLabel* label = frameLabel(window); ASSERT_NE(label, nullptr); - EXPECT_EQ(label->text(), "Frame: 4 / 10"); + QTRY_COMPARE(label->text(), QString("Frame: 4 / 10")); auto* slider = window.findChild(); ASSERT_NE(slider, nullptr); - EXPECT_EQ(slider->value(), 3); + QTRY_COMPARE(slider->value(), 3); } TEST(MainWindowTest, SpaceTogglesPlayback) { @@ -487,8 +487,7 @@ TEST(MainWindowTest, CacheServesRevisitedFrames) { auto* log = window.findChild("perfLog"); ASSERT_NE(log, nullptr); - EXPECT_TRUE(log->toPlainText().contains("cache")) - << log->toPlainText().toStdString(); + QTRY_VERIFY(log->toPlainText().contains("cache")); QSettings().setValue("perfLogVisible", false); }