Truly independent web browser
LibMedia: Force a re-decode when seeking backwards in reordered codecs
Zaggy1024c251d38926c0
diff --git a/Libraries/LibMedia/Producers/DecodedVideoProducer.cpp b/Libraries/LibMedia/Producers/DecodedVideoProducer.cppindex 42d51c5c1aa..bef8e85e170 100644--- a/Libraries/LibMedia/Producers/DecodedVideoProducer.cpp+++ b/Libraries/LibMedia/Producers/DecodedVideoProducer.cpp@@ -486,6 +486,22 @@ void DecodedVideoProducer::ThreadData::re_emit_last_frame_if_at_end_of_stream_whqueue_frame(*m_last_queued_frame);}+void DecodedVideoProducer::ThreadData::note_frame_passed_by_decoder(AK::Duration timestamp, AK::Duration earliest_target_reachable_without_moving_demuxer)+{+ VERIFY(m_decode_thread_id.is_current_thread());+ if (m_latest_frame_passed_by_decoder.has_value() && timestamp < m_latest_frame_passed_by_decoder->timestamp)+ return;+ m_latest_frame_passed_by_decoder = FramePassedByDecoder { timestamp, earliest_target_reachable_without_moving_demuxer };+}++bool DecodedVideoProducer::ThreadData::decoder_has_passed_a_frame_needed_for(AK::Duration target) const+{+ VERIFY(m_decode_thread_id.is_current_thread());+ if (!m_latest_frame_passed_by_decoder.has_value())+ return false;+ return target < m_latest_frame_passed_by_decoder->earliest_target_reachable_without_moving_demuxer;+}+void DecodedVideoProducer::ThreadData::resolve_seek(u32 seek_id){m_last_processed_seek_id = seek_id;@@ -553,6 +569,7 @@ void DecodedVideoProducer::ThreadData::handle_seek()auto has_clamped_target = false;while (true) {+ auto decoder_has_passed_the_target = false;{auto locker = take_lock();seek_id = m_seek_id.load(MemoryOrder::memory_order_relaxed);@@ -580,6 +597,7 @@ void DecodedVideoProducer::ThreadData::handle_seek()if (m_last_queued_frame != nullptr)timestamp = m_last_queued_frame->end();} else {+ decoder_has_passed_the_target = decoder_has_passed_a_frame_needed_for(timestamp);// If the demuxer keeps its position, the decoder won't output this frame again.if (!m_decoder_needs_keyframe_next_seek && m_last_queued_frame != nullptr && m_last_queued_frame->timestamp() <= timestamp)last_frame = m_last_queued_frame;@@ -598,7 +616,7 @@ void DecodedVideoProducer::ThreadData::handle_seek()auto seek_options = DemuxerSeekOptions::None;if (m_decoder == nullptr)seek_options |= DemuxerSeekOptions::NeedCodecConfiguration | DemuxerSeekOptions::Force;- if (m_decoder_needs_keyframe_next_seek)+ if (m_decoder_needs_keyframe_next_seek || decoder_has_passed_the_target)seek_options |= DemuxerSeekOptions::Force;auto demuxer_seek_result_or_error = m_demuxer->seek_to_most_recent_keyframe(m_track, timestamp, seek_options);if (demuxer_seek_result_or_error.is_error() && demuxer_seek_result_or_error.error().category() != DecoderErrorCategory::EndOfStream) {@@ -619,6 +637,7 @@ void DecodedVideoProducer::ThreadData::handle_seek()if (demuxer_seek_result == DemuxerSeekResult::MovedPosition) {if (m_decoder != nullptr)m_decoder->flush();+ m_latest_frame_passed_by_decoder.clear();last_frame.clear();}@@ -701,6 +720,7 @@ void DecodedVideoProducer::ThreadData::handle_seek()}auto current_frame = frame_result.release_value();+ note_frame_passed_by_decoder(current_frame->timestamp(), current_frame->timestamp());if (current_frame->contains_timestamp(timestamp)) {auto locker = take_lock();@@ -760,6 +780,9 @@ void DecodedVideoProducer::ThreadData::handle_seek()auto conservative_end_of_coded_frame = VideoFrame::conservative_end_of(coded_frame.presentation_timestamp(), coded_frame.duration());if (conservative_end_of_coded_frame >= timestamp)decoding_for_output = true;+ // Frames decoded for reference aren't output, so we need to ensure that we re-decode when seeking back into them.+ if (!decoding_for_output)+ note_frame_passed_by_decoder(coded_frame.presentation_timestamp(), conservative_end_of_coded_frame);greatest_coded_timestamp = max(greatest_coded_timestamp, coded_frame.presentation_timestamp());auto decode_result = receive_coded_frame(coded_frame, decoding_for_output ? DecodeIntent::Output : DecodeIntent::Reference);@@ -855,6 +878,7 @@ void DecodedVideoProducer::ThreadData::push_data_and_decode_some_frames()return;}auto frame = frame_result.release_value();+ note_frame_passed_by_decoder(frame->timestamp(), frame->timestamp());auto locker = take_lock();queue_frame(frame);diff --git a/Libraries/LibMedia/Producers/DecodedVideoProducer.h b/Libraries/LibMedia/Producers/DecodedVideoProducer.hindex f0360ae5f27..6c752ee586e 100644--- a/Libraries/LibMedia/Producers/DecodedVideoProducer.h+++ b/Libraries/LibMedia/Producers/DecodedVideoProducer.h@@ -111,6 +111,8 @@ private:void seek_to_resubmit_while_locked();bool is_within_available_range_while_locked(AK::Duration) const;void re_emit_last_frame_if_at_end_of_stream_while_locked();+ void note_frame_passed_by_decoder(AK::Duration timestamp, AK::Duration earliest_target_reachable_without_moving_demuxer);+ bool decoder_has_passed_a_frame_needed_for(AK::Duration target) const;void push_data_and_decode_some_frames();void enter_halting_state(PipelineStatus, Optional<DecoderError>);@@ -161,6 +163,11 @@ private:NonReferenceFrameDetector m_non_reference_frame_detector;bool m_decoder_needs_keyframe_next_seek { false };bool m_decoder_is_draining_before_unavailable_data { false };+ struct FramePassedByDecoder {+ AK::Duration timestamp;+ AK::Duration earliest_target_reachable_without_moving_demuxer;+ };+ Optional<FramePassedByDecoder> m_latest_frame_passed_by_decoder;FrameQueue m_queue;RefPtr<VideoFrame> m_last_queued_frame;diff --git a/Tests/LibMedia/TestDecodedVideoProducer.cpp b/Tests/LibMedia/TestDecodedVideoProducer.cppindex 0cc3f2d6ee3..57df6be6893 100644--- a/Tests/LibMedia/TestDecodedVideoProducer.cpp+++ b/Tests/LibMedia/TestDecodedVideoProducer.cpp@@ -373,6 +373,28 @@ private:RefPtr<Threading::Thread> m_thread;};+bool has_h264_decoder()+{+ if (Media::select_video_decoder(Media::ParsedCodec { Media::CodecID::H264 }).has_value())+ return true;+ warnln("No decoder for H.264, skipping");+ return false;+}++RefPtr<Media::VideoFrame> peek_frame_within_time_limit(Media::VideoProducer& producer, Core::EventLoop& loop, AK::Duration time_limit)+{+ auto start_time = MonotonicTime::now_coarse();+ while (MonotonicTime::now_coarse() - start_time < time_limit) {+ auto output = producer.peek();+ if (output.status == Media::PipelineStatus::HaveData)+ return output.frame;+ if (output.status == Media::PipelineStatus::EndOfStream)+ return nullptr;+ loop.pump(Core::EventLoop::WaitMode::PollForEvents);+ }+ return nullptr;+}+RefPtr<Media::VideoFrame> take_frame_within_time_limit(Media::VideoProducer& producer, Core::EventLoop& loop, AK::Duration time_limit){auto start_time = MonotonicTime::now_coarse();@@ -931,6 +953,89 @@ TEST_CASE(a_seek_back_within_the_last_decoded_frame_lands_on_it)EXPECT_EQ(frame->timestamp(), last_read_sample_timestamp);}+// The last sample of a reordered stream precedes its last frame, so after draining the decoder at the end, the+// demuxer's position is still before a seek back into the frame between them. The decoder already output that frame.+TEST_CASE(a_seek_back_into_a_frame_output_after_the_last_sample_lands_on_it)+{+ if (!has_h264_decoder())+ return;+ auto& loop = never_destroyed_event_loop();++ AK::Duration last_sample_timestamp;+ {+ auto [demuxer, track] = demuxer_and_video_track_for("./avc.mp4"sv);+ TRY_OR_FAIL(demuxer->create_context_for_track(track));+ while (true) {+ auto sample = demuxer->get_next_sample_for_track(track);+ if (sample.is_error())+ break;+ last_sample_timestamp = sample.value().presentation_timestamp();+ }+ }++ auto producer = create_started_producer(loop, "./avc.mp4"sv);+ auto time_limit = AK::Duration::from_seconds(10);+ auto start_time = MonotonicTime::now_coarse();+ RefPtr<Media::VideoFrame> last_frame;+ while (true) {+ auto output = producer->peek();+ if (output.status == Media::PipelineStatus::HaveData) {+ last_frame = output.frame;+ producer->consume();+ } else if (output.status == Media::PipelineStatus::EndOfStream) {+ break;+ }+ if (MonotonicTime::now_coarse() - start_time >= time_limit) {+ FAIL("Timed out decoding to the end of the stream");+ return;+ }+ loop.pump(Core::EventLoop::WaitMode::PollForEvents);+ }+ VERIFY(last_frame != nullptr);+ VERIFY(last_frame->timestamp() > last_sample_timestamp);++ producer->seek(last_sample_timestamp + AK::Duration::from_milliseconds(10));+ auto frame = peek_frame_within_time_limit(*producer, loop, time_limit);+ if (frame == nullptr)+ FAIL("The seek did not resolve with a frame");+ else+ EXPECT_EQ(frame->timestamp(), last_sample_timestamp);+}++// A seek decodes the samples before its target only as references, so the decoder outputs none of them, and it skips+// those that nothing references. The demuxer's position is still before a second seek back to one of them.+TEST_CASE(a_seek_back_into_a_frame_decoded_only_as_a_reference_lands_on_it)+{+ if (!has_h264_decoder())+ return;+ auto& loop = never_destroyed_event_loop();++ // The first five samples in decode order are at 0, 160, 80, 40 and 120 ms, and those at 40 and 120 are not+ // referenced.+ auto [inner_demuxer, track] = demuxer_and_video_track_for("./avc.mp4"sv);+ auto demuxer = BlockingDemuxer::create(inner_demuxer, 5);+ auto producer = TRY_OR_FAIL(Media::DecodedVideoProducer::try_create(loop, demuxer, track));+ producer->set_error_handler([&](Media::DecoderError&& error) {+ FAIL(ByteString::formatted("An error occurred while decoding: {}", error.description()));+ });+ producer->seek(AK::Duration::from_milliseconds(330));+ producer->start();++ auto time_limit = AK::Duration::from_seconds(5);+ if (!demuxer->wait_until_a_read_blocks(time_limit)) {+ FAIL("Timed out waiting for the decode thread to block on the demuxer");+ return;+ }++ producer->seek(AK::Duration::from_milliseconds(130));+ demuxer->stop_blocking_reads();+ auto frame = peek_frame_within_time_limit(*producer, loop, time_limit);+ if (frame == nullptr)+ FAIL("The seek did not resolve with a frame");+ else+ EXPECT_EQ(frame->timestamp(), AK::Duration::from_milliseconds(120));+}+// A stream can grow after the demuxer reported its end, by which point the decoder was drained on that report.// Nothing can be decoded from the samples that follow, so they are ignored rather than ending playback in an error.// The decoder's references were made from the data that a seek invalidates, so it cannot continue from the demuxer's