From b38ed0bf4e1e982686363f5c0f347bc000ebec28 Mon Sep 17 00:00:00 2001 From: blocksmith314 Date: Tue, 17 Nov 2026 22:12:18 +0800 Subject: [PATCH] perf(seek): keyframe-aware forward decoding and seek stats Build a presentation-order frame index with keyframe flags from container packets. A seek now compares decoding forward from the current position with seeking to the nearest keyframe and picks the cheaper path, instead of seeking on every jump larger than one frame. The index is built lazily only when a seek is already likely, and forward decoding keeps the decoder state (no av_seek_frame, no flush); the target frame is still decoded by ShowFrameAt. Expose SeekStats (used_container, frames_decoded, seek_io_ms, decode_ms) and add seek_frames/seek_io to the performance log. Fixes #66 --- ffmpeg/decoder.cpp | 144 ++++++++++++++++++++++++++++++++++-------- ffmpeg/decoder.h | 12 +++- mainwindow.cpp | 9 ++- test/test_decoder.cpp | 43 +++++++++++++ 4 files changed, 180 insertions(+), 28 deletions(-) diff --git a/ffmpeg/decoder.cpp b/ffmpeg/decoder.cpp index 2705daf..2bd9fb4 100644 --- a/ffmpeg/decoder.cpp +++ b/ffmpeg/decoder.cpp @@ -2,6 +2,9 @@ #include #include +#include +#include +#include #include #include @@ -24,8 +27,13 @@ struct FFmpegDecoder::Impl { DecodedFrame pending; int pending_index = 0; AVFrame* last_frame = nullptr; // reference to the last decoded frame - std::vector frame_pts; // per-frame PTS in seconds (containers) - bool frame_pts_tried = false; + struct FrameEntry { + double pts = 0.0; + bool key = false; + }; + std::vector frame_index; // presentation order + std::vector keyframes; // indices into frame_index + bool frame_index_tried = false; }; FFmpegDecoder::FFmpegDecoder() : impl_(new Impl()) {} @@ -133,8 +141,9 @@ bool FFmpegDecoder::OpenFile(const std::string& path, CodecType codec) { : ""; impl_->is_raw = (std::strcmp(fmtName, "h264") == 0 || std::strcmp(fmtName, "hevc") == 0); - impl_->frame_pts.clear(); - impl_->frame_pts_tried = false; + impl_->frame_index.clear(); + impl_->keyframes.clear(); + impl_->frame_index_tried = false; path_ = path; codec_ = codec; @@ -316,6 +325,7 @@ void FFmpegDecoder::reset() { } bool FFmpegDecoder::SeekToFrame(int target_index) { + last_seek_stats_ = SeekStats(); if (!impl_ || !impl_->codecCtx || !impl_->fmtCtx) { return false; } @@ -328,12 +338,54 @@ bool FFmpegDecoder::SeekToFrame(int target_index) { return true; } + const int gap = target_index - current_frame_; + constexpr int kBlindForwardFrames = 30; + constexpr int kSeekOverheadFrames = 2; + bool seek_attempted = false; - if (!impl_->is_raw && - (target_index < current_frame_ || target_index > current_frame_ + 1)) { - seek_attempted = true; - if (SeekByContainer(target_index)) { - return true; + bool index_rebuilt = false; + + if (!impl_->is_raw) { + if (impl_->frame_index.empty() && !impl_->frame_index_tried) { + // Building the index demuxes the whole file and resets the decoder, so + // only do it when a seek is the likely outcome anyway. + if (gap <= 0 || gap > kBlindForwardFrames) { + const auto t0 = std::chrono::steady_clock::now(); + BuildFrameIndex(); + last_seek_stats_.seek_io_ms = + std::chrono::duration_cast( + std::chrono::steady_clock::now() - t0) + .count(); + index_rebuilt = true; + } + } + + bool use_seek = index_rebuilt; + if (!use_seek && !impl_->frame_index.empty() && + (size_t)target_index < impl_->frame_index.size()) { + int kf = -1; + for (int index : impl_->keyframes) { + if (index <= target_index) { + kf = index; + } else { + break; + } + } + const int cost_forward = gap > 0 ? gap : INT_MAX; + const int cost_seek = + kf >= 0 ? target_index - kf + kSeekOverheadFrames : INT_MAX; + use_seek = cost_forward > cost_seek; + } else if (!use_seek && impl_->frame_index.empty() && + (gap <= 0 || gap > kBlindForwardFrames)) { + use_seek = true; + } + + if (use_seek) { + seek_attempted = true; + if (SeekByContainer(target_index)) { + return true; + } + last_seek_stats_ = SeekStats(); } } @@ -341,47 +393,73 @@ bool FFmpegDecoder::SeekToFrame(int target_index) { reset(); current_frame_ = 0; } + + // Decode the frames before the target; ShowFrameAt decodes and converts the + // requested frame itself (current_frame_ counts decoded outputs, so the next + // decode is exactly the requested frame). DecodedFrame dummy; + const auto start_time = std::chrono::steady_clock::now(); while (current_frame_ < target_index) { if (!DecodeNextFrame(dummy, false)) { return false; } + last_seek_stats_.frames_decoded++; + } + last_seek_stats_.decode_ms = + std::chrono::duration_cast( + std::chrono::steady_clock::now() - start_time) + .count(); + if (gap > 0) { + last_seek_stats_.frames_decoded = gap; } return true; } -bool FFmpegDecoder::BuildFramePts() { +bool FFmpegDecoder::BuildFrameIndex() { if (!impl_ || impl_->is_raw || impl_->video_stream_idx < 0) { return false; } - impl_->frame_pts_tried = true; + impl_->frame_index_tried = true; AVStream* st = impl_->fmtCtx->streams[impl_->video_stream_idx]; if (!st) { return false; } - std::vector pts; + std::vector entries; AVPacket* pkt = av_packet_alloc(); while (av_read_frame(impl_->fmtCtx, pkt) >= 0) { if (pkt->stream_index == impl_->video_stream_idx && pkt->pts != AV_NOPTS_VALUE) { - pts.push_back(pkt->pts * av_q2d(st->time_base)); + Impl::FrameEntry entry; + entry.pts = pkt->pts * av_q2d(st->time_base); + entry.key = (pkt->flags & AV_PKT_FLAG_KEY) != 0; + entries.push_back(entry); } av_packet_unref(pkt); } av_packet_free(&pkt); - // The demuxer is now at EOF; rewind for the following seek. + // Rewind; building the index invalidates the decoder position. av_seek_frame(impl_->fmtCtx, impl_->video_stream_idx, 0, AVSEEK_FLAG_BACKWARD); avcodec_flush_buffers(impl_->codecCtx); - impl_->frame_pts = std::move(pts); - return !impl_->frame_pts.empty(); + + std::sort(entries.begin(), entries.end(), + [](const Impl::FrameEntry& a, const Impl::FrameEntry& b) { + return a.pts < b.pts; + }); + impl_->keyframes.clear(); + for (size_t i = 0; i < entries.size(); i++) { + if (entries[i].key) { + impl_->keyframes.push_back((int)i); + } + } + impl_->frame_index = std::move(entries); + return !impl_->frame_index.empty(); } bool FFmpegDecoder::SeekByContainer(int target_index) { - if (!impl_ || !impl_->fmtCtx || impl_->video_stream_idx < 0 || - frame_rate_ <= 0.0) { + if (!impl_ || !impl_->fmtCtx || impl_->video_stream_idx < 0) { return false; } AVStream* st = impl_->fmtCtx->streams[impl_->video_stream_idx]; @@ -389,19 +467,24 @@ bool FFmpegDecoder::SeekByContainer(int target_index) { return false; } - int64_t target_pts = 0; - if (impl_->frame_pts.empty() && !impl_->frame_pts_tried) { - BuildFramePts(); + if (impl_->frame_index.empty() && !impl_->frame_index_tried) { + BuildFrameIndex(); } - if ((size_t)target_index < impl_->frame_pts.size()) { - target_pts = (int64_t)std::llround(impl_->frame_pts[(size_t)target_index] / - av_q2d(st->time_base)); + + int64_t target_pts = 0; + if ((size_t)target_index < impl_->frame_index.size()) { + target_pts = (int64_t)std::llround( + impl_->frame_index[(size_t)target_index].pts / av_q2d(st->time_base)); } else { + if (frame_rate_ <= 0.0) { + return false; + } target_pts = (int64_t)std::llround((double)target_index * st->time_base.den / (frame_rate_ * st->time_base.num)); } + const auto seek_start = std::chrono::steady_clock::now(); const int seek_ret = av_seek_frame(impl_->fmtCtx, impl_->video_stream_idx, target_pts, AVSEEK_FLAG_BACKWARD); if (seek_ret < 0) { @@ -409,7 +492,6 @@ bool FFmpegDecoder::SeekByContainer(int target_index) { } avcodec_flush_buffers(impl_->codecCtx); - // Drop any frames that were decoded but not consumed before the seek. AVFrame* stale = av_frame_alloc(); while (avcodec_receive_frame(impl_->codecCtx, stale) >= 0) { av_frame_unref(stale); @@ -417,8 +499,15 @@ bool FFmpegDecoder::SeekByContainer(int target_index) { av_frame_free(&stale); current_frame_ = 0; + const auto decode_start = std::chrono::steady_clock::now(); + last_seek_stats_.seek_io_ms = + std::chrono::duration_cast(decode_start - + seek_start) + .count(); + DecodedFrame f; while (DecodeNextFrame(f, false)) { + last_seek_stats_.frames_decoded++; if (f.pts == AV_NOPTS_VALUE) { return false; } // no container timestamps @@ -428,6 +517,11 @@ bool FFmpegDecoder::SeekByContainer(int target_index) { impl_->pending_index = target_index; impl_->has_pending = true; current_frame_ = target_index; + last_seek_stats_.used_container = true; + last_seek_stats_.decode_ms = + std::chrono::duration_cast( + std::chrono::steady_clock::now() - decode_start) + .count(); return true; } } diff --git a/ffmpeg/decoder.h b/ffmpeg/decoder.h index 3565096..b1ba869 100644 --- a/ffmpeg/decoder.h +++ b/ffmpeg/decoder.h @@ -39,6 +39,15 @@ class FFmpegDecoder { bool DecodeKeyframes(std::vector& out, int max_frames = 10); + struct SeekStats { + bool used_container = false; + int frames_decoded = 0; + qint64 seek_io_ms = 0; + qint64 decode_ms = 0; + }; + + const SeekStats& LastSeekStats() const { return last_seek_stats_; } + bool HasTimestamps() const; int FrameCount() const { return frame_count_; } int width() const { return width_; } @@ -50,7 +59,7 @@ class FFmpegDecoder { private: bool ConvertFrame(const AVFrame* frame, DecodedFrame& out); - bool BuildFramePts(); + bool BuildFrameIndex(); struct Impl; Impl* impl_ = nullptr; @@ -58,6 +67,7 @@ class FFmpegDecoder { int width_ = 0; int height_ = 0; int current_frame_ = 0; + SeekStats last_seek_stats_; double frame_rate_ = 30.0; double duration_sec_ = 0.0; std::string path_; diff --git a/mainwindow.cpp b/mainwindow.cpp index 53bb63d..c74ef09 100644 --- a/mainwindow.cpp +++ b/mainwindow.cpp @@ -876,15 +876,20 @@ void MainWindow::ShowFrameAt(int idx) { ShowFrame(frame.image, idx); if (perf) { const qint64 display_ms = perf_timer.elapsed(); + const auto seek_stats = + jump ? player_decoder_.LastSeekStats() : FFmpegDecoder::SeekStats{}; AppendPerf( - QString("%1 %2 frame=%3 total=%4ms seek=%5 decode=%6 display=%7") + 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(display_ms) + .arg(seek_stats.frames_decoded) + .arg(seek_stats.seek_io_ms)); } if (jump) { diff --git a/test/test_decoder.cpp b/test/test_decoder.cpp index e39963f..af0a3b1 100644 --- a/test/test_decoder.cpp +++ b/test/test_decoder.cpp @@ -83,3 +83,46 @@ TEST(DecoderTest, RawStreamHasNoTimestamps) { EXPECT_EQ(frame.image.width(), 352); EXPECT_EQ(frame.image.height(), 288); } + +TEST(DecoderTest, ForwardSmallSeekDecodesOnlyTheGap) { + if (!exists(data_path("sample_720p.mp4"))) { + GTEST_SKIP() << "MP4 fixture missing"; + } + + FFmpegDecoder decoder; + ASSERT_TRUE(decoder.OpenFile(data_path("sample_720p.mp4"), CodecType::kH264)) + << decoder.LastError(); + + DecodedFrame first; + ASSERT_TRUE(decoder.DecodeNextFrame(first)); + + ASSERT_TRUE(decoder.SeekToFrame(5)); + const auto stats = decoder.LastSeekStats(); + EXPECT_FALSE(stats.used_container); + EXPECT_EQ(stats.frames_decoded, 4); + + DecodedFrame frame; + ASSERT_TRUE(decoder.DecodeNextFrame(frame)); + EXPECT_NEAR(frame.pts_sec, 0.5, 0.01); // 10 fps +} + +TEST(DecoderTest, BackwardSeekUsesContainerSeek) { + if (!exists(data_path("sample_720p.mp4"))) { + GTEST_SKIP() << "MP4 fixture missing"; + } + + FFmpegDecoder decoder; + ASSERT_TRUE(decoder.OpenFile(data_path("sample_720p.mp4"), CodecType::kH264)) + << decoder.LastError(); + + DecodedFrame frame; + for (int i = 0; i < 6; i++) { + ASSERT_TRUE(decoder.DecodeNextFrame(frame)); + } + + ASSERT_TRUE(decoder.SeekToFrame(2)); + EXPECT_TRUE(decoder.LastSeekStats().used_container); + + ASSERT_TRUE(decoder.DecodeNextFrame(frame)); + EXPECT_NEAR(frame.pts_sec, 0.2, 0.01); +}