Skip to content

Truly independent web browser

LibMedia: Rework the producers' seek loops to deal with some edge cases

Zaggy10245bbccbb3d849
diff --git a/Libraries/LibMedia/Producers/DecodedAudioProducer.cpp b/Libraries/LibMedia/Producers/DecodedAudioProducer.cpp
index 5636447f07f..562a7970680 100644
--- a/Libraries/LibMedia/Producers/DecodedAudioProducer.cpp
+++ b/Libraries/LibMedia/Producers/DecodedAudioProducer.cpp
@@ -262,10 +262,9 @@ DecoderErrorOr<bool> DecodedAudioProducer::ThreadData::replace_drained_decoder()
return false;
auto frame = m_frame_awaiting_decoder_replacement.release_value();
m_converter->flush();
- if (!frame.new_codec_configuration().has_value()) {
- TRY(m_demuxer->seek_to_most_recent_keyframe(m_track, frame.presentation_timestamp(), DemuxerSeekOptions::Force | DemuxerSeekOptions::NeedCodecConfiguration));
- frame = TRY(m_demuxer->get_next_sample_for_track(m_track));
- }
+ m_decoder.clear();
+ if (!frame.new_codec_configuration().has_value())
+ return DecoderError::with_description(DecoderErrorCategory::NeedsResubmission, "The frame awaiting a new decoder carries no codec configuration"sv);
TRY(create_decoder_for_frame(frame));
TRY(receive_into_decoder(frame));
return true;
@@ -385,7 +384,6 @@ bool DecodedAudioProducer::ThreadData::handle_auto_suspension()
m_queue.clear();
m_decoder.clear();
- m_decoder_needs_codec_configuration_next_seek = true;
m_auto_suspend_requested = false;
m_current_halting_status = PipelineStatus::Suspended;
// The consumer's last peek predates the suspension, so wake it regardless of what it saw.
@@ -496,10 +494,12 @@ bool DecodedAudioProducer::ThreadData::seek_to_replace_decoder_if_it_cannot_deco
void DecodedAudioProducer::ThreadData::seek_to_resubmit_while_locked()
{
- m_decoder_needs_codec_configuration_next_seek = true;
- if (m_last_processed_seek_id == m_seek_id)
- m_seek_timestamp = m_earliest_available_timestamp;
+ m_seek_reason = SeekReason::DecoderResetNeeded;
+ auto seek_is_pending = m_last_processed_seek_id != m_seek_id;
m_seek_id++;
+ // Interrupt the decode loop without hiding the held blocks from peek().
+ if (!seek_is_pending)
+ m_last_processed_seek_id = m_seek_id.load();
m_downstream_needs_wake = true;
}
@@ -508,33 +508,52 @@ void DecodedAudioProducer::ThreadData::handle_seek()
VERIFY(m_decode_thread_id.is_current_thread());
auto seek_id = m_seek_id.load();
- if (m_last_processed_seek_id == seek_id)
+ auto seek_was_externally_requested = seek_id != m_last_processed_seek_id;
+ auto seek_reason = m_seek_reason;
+ if (!seek_was_externally_requested && seek_reason != SeekReason::DecoderResetNeeded)
return;
AK::Duration timestamp;
AudioBlock last_block;
+ auto resolve_handled_seek_while_locked = [&] {
+ resolve_seek(seek_id);
+ if (m_seek_id == seek_id)
+ m_seek_reason = SeekReason::Normal;
+ };
+
auto handle_error = [&](DecoderError&& error) {
auto locker = take_lock();
enter_halting_state(PipelineStatus::Error, move(error));
- resolve_seek(seek_id);
+ resolve_handled_seek_while_locked();
};
while (true) {
{
auto locker = take_lock();
seek_id = m_seek_id;
+ seek_was_externally_requested = seek_id != m_last_processed_seek_id;
+ seek_reason = m_seek_reason;
+
timestamp = m_seek_timestamp;
m_demuxer->reset_blocking_reads_aborted_for_track(m_track);
- m_queue.clear();
- m_earliest_available_timestamp = timestamp;
+
+ if (seek_reason == SeekReason::DecoderResetNeeded && !seek_was_externally_requested) {
+ timestamp = m_earliest_available_timestamp;
+ if (!m_queue.is_empty())
+ timestamp = m_queue.tail().block.media_time_end();
+ } else {
+ m_queue.clear();
+ m_earliest_available_timestamp = timestamp;
+ }
+
m_current_halting_status = PipelineStatus::Pending;
m_frame_awaiting_decoder_replacement.clear();
}
// All of our audio codecs have independently decodable frames, so always moving the demuxer is cheap.
auto seek_options = DemuxerSeekOptions::Force;
- if (m_decoder_needs_codec_configuration_next_seek)
+ if (m_decoder == nullptr)
seek_options |= DemuxerSeekOptions::NeedCodecConfiguration;
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) {
@@ -544,8 +563,6 @@ void DecodedAudioProducer::ThreadData::handle_seek()
return;
}
- m_decoder_needs_codec_configuration_next_seek = false;
-
flush_decoder();
last_block.clear();
@@ -573,7 +590,7 @@ void DecodedAudioProducer::ThreadData::handle_seek()
continue;
auto locker = take_lock();
- resolve_seek(seek_id);
+ resolve_handled_seek_while_locked();
if (!last_block.is_empty())
queue_block(last_block);
return;
@@ -592,14 +609,14 @@ void DecodedAudioProducer::ThreadData::handle_seek()
if (current_block.contains_media_time(timestamp)) {
auto locker = take_lock();
- resolve_seek(seek_id);
+ resolve_handled_seek_while_locked();
queue_block(current_block);
return;
}
if (current_block.media_time_start() > timestamp) {
auto locker = take_lock();
- resolve_seek(seek_id);
+ resolve_handled_seek_while_locked();
if (!last_block.is_empty())
queue_block(last_block);
@@ -621,7 +638,7 @@ void DecodedAudioProducer::ThreadData::handle_seek()
if (category == DecoderErrorCategory::EndOfStream) {
if (m_decoder == nullptr) {
auto locker = take_lock();
- resolve_seek(seek_id);
+ resolve_handled_seek_while_locked();
return;
}
m_decoder->signal_end_of_stream();
diff --git a/Libraries/LibMedia/Producers/DecodedAudioProducer.h b/Libraries/LibMedia/Producers/DecodedAudioProducer.h
index c95191b6bff..a67266ee306 100644
--- a/Libraries/LibMedia/Producers/DecodedAudioProducer.h
+++ b/Libraries/LibMedia/Producers/DecodedAudioProducer.h
@@ -147,7 +147,6 @@ private:
AudioDecoderSelection m_decoder_that_failed_due_to_missing_features;
Optional<CodedFrame> m_frame_awaiting_decoder_replacement;
OwnPtr<AudioDecoder> m_decoder;
- bool m_decoder_needs_codec_configuration_next_seek { true };
NonnullOwnPtr<Audio::AudioConverter> m_converter;
i64 m_last_output_frame { NumericLimits<i64>::min() };
@@ -158,9 +157,15 @@ private:
ReadBlockedChangeHandler m_read_blocked_change_handler;
PipelineStatus m_current_halting_status { PipelineStatus::Pending };
+ enum class SeekReason : u8 {
+ Normal,
+ DecoderResetNeeded,
+ };
+
u32 m_last_processed_seek_id { 0 };
Atomic<u32> m_seek_id { 0 };
AK::Duration m_seek_timestamp;
+ SeekReason m_seek_reason { SeekReason::Normal };
SynchronizedWakeHandler m_wake_handler;
mutable bool m_downstream_needs_wake { true };
diff --git a/Libraries/LibMedia/Producers/DecodedVideoProducer.cpp b/Libraries/LibMedia/Producers/DecodedVideoProducer.cpp
index 146bc5c8269..6a3cd9d73fe 100644
--- a/Libraries/LibMedia/Producers/DecodedVideoProducer.cpp
+++ b/Libraries/LibMedia/Producers/DecodedVideoProducer.cpp
@@ -4,9 +4,9 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <AK/ScopeGuard.h>
#include <LibCore/EventLoop.h>
#include <LibMedia/Demuxer.h>
+#include <LibMedia/PipelineStatus.h>
#include <LibMedia/Sinks/VideoSink.h>
#include <LibMediaCodecs/VideoDecoder.h>
#include <LibMediaCodecs/VideoDecoderRegistry.h>
@@ -225,7 +225,7 @@ DecoderErrorOr<void> DecodedVideoProducer::ThreadData::create_decoder_for_frame(
});
// Output that arrives while the decode thread reads coded data is taken as soon as the read returns.
m_decoder->set_output_arrived_callback([wait_state = m_wait_state, demuxer = m_demuxer, track = m_track] {
- if (wait_state->output_should_interrupt_demuxer_reads.load(AK::MemoryOrder::memory_order_relaxed))
+ if (wait_state->output_should_interrupt_demuxer_reads.load(MemoryOrder::memory_order_relaxed))
demuxer->set_blocking_reads_aborted_for_track(track);
});
m_decoder_codec_id = frame.codec_id();
@@ -238,7 +238,7 @@ bool DecodedVideoProducer::ThreadData::check_if_seek_is_needed_or_allow_demuxer_
if (m_seek_id != seek_id)
return true;
m_demuxer->reset_blocking_reads_aborted_for_track(m_track);
- m_wait_state->output_should_interrupt_demuxer_reads.store(true, AK::MemoryOrder::memory_order_relaxed);
+ m_wait_state->output_should_interrupt_demuxer_reads.store(true, MemoryOrder::memory_order_relaxed);
return false;
}
@@ -262,35 +262,15 @@ DecoderErrorOr<void> DecodedVideoProducer::ThreadData::receive_coded_frame(Coded
return receive_into_decoder(frame, intent);
}
-DecoderErrorOr<bool> DecodedVideoProducer::ThreadData::replace_drained_decoder(u32 seek_id)
+DecoderErrorOr<bool> DecodedVideoProducer::ThreadData::replace_drained_decoder()
{
if (!m_frame_awaiting_decoder_replacement.has_value())
return false;
auto frame = m_frame_awaiting_decoder_replacement.release_value();
auto intent = m_intent_awaiting_decoder_replacement;
m_decoder.clear();
- if (!frame.new_codec_configuration().has_value()) {
- ArmedScopeGuard force_aborting_seek_to_replace_the_drained_decoder_again = [&] {
- m_decoder_needs_keyframe_next_seek = true;
- m_decoder_needs_codec_configuration_next_seek = true;
- };
- if (check_if_seek_is_needed_or_allow_demuxer_reads(seek_id))
- return false;
- auto seek_result = m_demuxer->seek_to_most_recent_keyframe(m_track, frame.presentation_timestamp(), DemuxerSeekOptions::Force | DemuxerSeekOptions::NeedCodecConfiguration);
- if (seek_result.is_error()) {
- if (seek_result.error().category() == DecoderErrorCategory::Aborted)
- return false;
- return seek_result.release_error();
- }
- auto frame_result = m_demuxer->get_next_sample_for_track(m_track);
- if (frame_result.is_error()) {
- if (frame_result.error().category() == DecoderErrorCategory::Aborted)
- return false;
- return frame_result.release_error();
- }
- frame = frame_result.release_value();
- force_aborting_seek_to_replace_the_drained_decoder_again.disarm();
- }
+ if (!frame.new_codec_configuration().has_value())
+ return DecoderError::with_description(DecoderErrorCategory::NeedsResubmission, "The frame awaiting a new decoder carries no codec configuration"sv);
TRY(create_decoder_for_frame(frame));
TRY(receive_into_decoder(frame, intent));
return true;
@@ -381,10 +361,14 @@ void DecodedVideoProducer::ThreadData::seek(AK::Duration timestamp, InvalidateHe
note_consumer_activity_while_locked();
m_downstream_needs_wake = true;
- if (invalidate_held_data == InvalidateHeldData::Yes)
- m_held_frames_are_invalid = true;
+ auto seek_behavior = m_seek_reason.load(MemoryOrder::memory_order_relaxed);
- if (!m_held_frames_are_invalid && is_within_available_range_while_locked(timestamp)) {
+ if (invalidate_held_data == InvalidateHeldData::Yes) {
+ seek_behavior = SeekReason::DataInvalidated;
+ m_seek_reason.store(seek_behavior, MemoryOrder::memory_order_relaxed);
+ }
+
+ if (seek_behavior != SeekReason::DataInvalidated && is_within_available_range_while_locked(timestamp)) {
re_emit_last_frame_if_at_end_of_stream_while_locked();
if (m_last_processed_seek_id != m_seek_id)
resolve_seek(m_seek_id.load());
@@ -448,8 +432,6 @@ bool DecodedVideoProducer::ThreadData::handle_auto_suspension()
m_last_queued_frame = nullptr;
m_latest_available_timestamp = m_earliest_available_timestamp;
m_decoder.clear();
- m_decoder_needs_keyframe_next_seek = true;
- m_decoder_needs_codec_configuration_next_seek = true;
m_auto_suspend_requested = false;
m_current_halting_status = PipelineStatus::Suspended;
// The consumer's last peek predates the suspension, so wake it regardless of what it saw.
@@ -524,12 +506,13 @@ bool DecodedVideoProducer::ThreadData::seek_to_replace_decoder_if_it_cannot_deco
void DecodedVideoProducer::ThreadData::seek_to_resubmit_while_locked()
{
- m_decoder_needs_keyframe_next_seek = true;
- m_decoder_needs_codec_configuration_next_seek = true;
- m_held_frames_are_invalid = true;
- if (m_last_processed_seek_id == m_seek_id)
- m_seek_timestamp = m_earliest_available_timestamp;
+ if (m_seek_reason.load(MemoryOrder::memory_order_relaxed) == SeekReason::Normal)
+ m_seek_reason.store(SeekReason::DecoderResetNeeded, MemoryOrder::memory_order_relaxed);
+ auto seek_is_pending = m_last_processed_seek_id != m_seek_id;
m_seek_id++;
+ // Interrupt the decode loop without hiding the held frames from peek().
+ if (!seek_is_pending)
+ m_last_processed_seek_id = m_seek_id.load();
m_downstream_needs_wake = true;
}
@@ -537,17 +520,26 @@ void DecodedVideoProducer::ThreadData::handle_seek()
{
VERIFY(m_decode_thread_id.is_current_thread());
- auto seek_id = m_seek_id.load(AK::MemoryOrder::memory_order_relaxed);
- if (seek_id == m_last_processed_seek_id.load(AK::MemoryOrder::memory_order_relaxed))
+ auto seek_id = m_seek_id.load(MemoryOrder::memory_order_relaxed);
+ auto seek_was_externally_requested = seek_id != m_last_processed_seek_id.load(MemoryOrder::memory_order_relaxed);
+ auto seek_reason = m_seek_reason.load(MemoryOrder::memory_order_relaxed);
+ if (!seek_was_externally_requested && seek_reason != SeekReason::DecoderResetNeeded)
return;
AK::Duration timestamp;
RefPtr<VideoFrame> last_frame;
+ auto resolve_handled_seek_while_locked = [&] {
+ resolve_seek(seek_id);
+ if (m_seek_id == seek_id)
+ m_seek_reason.store(SeekReason::Normal, MemoryOrder::memory_order_relaxed);
+ };
+
auto handle_error = [&](DecoderError&& error) {
auto locker = take_lock();
+ m_decoder_needs_keyframe_next_seek = true;
enter_halting_state(PipelineStatus::Error, move(error));
- resolve_seek(seek_id);
+ resolve_handled_seek_while_locked();
};
auto has_clamped_target = false;
@@ -555,29 +547,39 @@ void DecodedVideoProducer::ThreadData::handle_seek()
{
auto locker = take_lock();
seek_id = m_seek_id.load(MemoryOrder::memory_order_relaxed);
- if (seek_id == m_last_processed_seek_id.load(MemoryOrder::memory_order_relaxed))
- return;
- seek_id = m_seek_id;
+ seek_was_externally_requested = seek_id != m_last_processed_seek_id;
+ seek_reason = m_seek_reason.load(MemoryOrder::memory_order_relaxed);
+
timestamp = m_seek_timestamp;
m_demuxer->reset_blocking_reads_aborted_for_track(m_track);
- m_wait_state->output_should_interrupt_demuxer_reads.store(false, AK::MemoryOrder::memory_order_relaxed);
+ m_wait_state->output_should_interrupt_demuxer_reads.store(false, MemoryOrder::memory_order_relaxed);
- if (!m_held_frames_are_invalid && is_within_available_range_while_locked(timestamp)) {
- re_emit_last_frame_if_at_end_of_stream_while_locked();
- resolve_seek(seek_id);
- dispatch_wake_if_needed_while_locked();
- return;
+ if (seek_reason == SeekReason::Normal) {
+ if (is_within_available_range_while_locked(timestamp)) {
+ re_emit_last_frame_if_at_end_of_stream_while_locked();
+ resolve_handled_seek_while_locked();
+ dispatch_wake_if_needed_while_locked();
+ return;
+ }
+ } else {
+ m_decoder_needs_keyframe_next_seek = true;
}
- // If the demuxer keeps its position, the decoder won't output this frame again.
- if (!m_held_frames_are_invalid && m_last_queued_frame != nullptr && m_last_queued_frame->timestamp() <= timestamp)
- last_frame = m_last_queued_frame;
+ if (seek_reason == SeekReason::DecoderResetNeeded && !seek_was_externally_requested && !has_clamped_target) {
+ timestamp = m_latest_available_timestamp;
+ if (m_last_queued_frame != nullptr)
+ timestamp = m_last_queued_frame->end();
+ } else {
+ // 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;
+
+ m_queue.clear();
+ m_last_queued_frame = nullptr;
+ m_earliest_available_timestamp = timestamp;
+ m_latest_available_timestamp = timestamp;
+ }
- m_queue.clear();
- m_held_frames_are_invalid = false;
- m_last_queued_frame = nullptr;
- m_earliest_available_timestamp = timestamp;
- m_latest_available_timestamp = timestamp;
m_current_halting_status = PipelineStatus::Pending;
m_frame_awaiting_decoder_replacement.clear();
if (m_decoder != nullptr)
@@ -585,8 +587,8 @@ void DecodedVideoProducer::ThreadData::handle_seek()
}
auto seek_options = DemuxerSeekOptions::None;
- if (m_decoder_needs_codec_configuration_next_seek)
- seek_options |= DemuxerSeekOptions::NeedCodecConfiguration;
+ if (m_decoder == nullptr)
+ seek_options |= DemuxerSeekOptions::NeedCodecConfiguration | DemuxerSeekOptions::Force;
if (m_decoder_needs_keyframe_next_seek)
seek_options |= DemuxerSeekOptions::Force;
auto demuxer_seek_result_or_error = m_demuxer->seek_to_most_recent_keyframe(m_track, timestamp, seek_options);
@@ -597,7 +599,6 @@ void DecodedVideoProducer::ThreadData::handle_seek()
return;
}
- m_decoder_needs_codec_configuration_next_seek = false;
m_decoder_needs_keyframe_next_seek = false;
auto demuxer_seek_result = demuxer_seek_result_or_error.value_or(DemuxerSeekResult::MovedPosition);
@@ -620,7 +621,7 @@ void DecodedVideoProducer::ThreadData::handle_seek()
auto frame_result = m_decoder->take_next_output(m_track.video_data().cicp, timestamp);
if (frame_result.is_error()) {
if (frame_result.error().category() == DecoderErrorCategory::EndOfStream) {
- auto error_or_decoder_was_replaced = replace_drained_decoder(seek_id);
+ auto error_or_decoder_was_replaced = replace_drained_decoder();
if (error_or_decoder_was_replaced.is_error()) {
if (seek_to_resubmit_if_decoder_lost_its_state(error_or_decoder_was_replaced.error())) {
new_seek_id = m_seek_id;
@@ -647,7 +648,7 @@ void DecodedVideoProducer::ThreadData::handle_seek()
}
auto locker = take_lock();
- resolve_seek(seek_id);
+ resolve_handled_seek_while_locked();
if (last_frame != nullptr)
queue_frame(last_frame.release_nonnull());
return;
@@ -686,14 +687,14 @@ void DecodedVideoProducer::ThreadData::handle_seek()
if (current_frame->contains_timestamp(timestamp)) {
auto locker = take_lock();
- resolve_seek(seek_id);
+ resolve_handled_seek_while_locked();
queue_frame(current_frame);
return;
}
if (current_frame->timestamp() > timestamp) {
auto locker = take_lock();
- resolve_seek(seek_id);
+ resolve_handled_seek_while_locked();
if (last_frame != nullptr)
queue_frame(last_frame.release_nonnull());
@@ -710,13 +711,13 @@ void DecodedVideoProducer::ThreadData::handle_seek()
break;
auto coded_frame_result = m_demuxer->get_next_sample_for_track(m_track);
- m_wait_state->output_should_interrupt_demuxer_reads.store(false, AK::MemoryOrder::memory_order_relaxed);
+ m_wait_state->output_should_interrupt_demuxer_reads.store(false, MemoryOrder::memory_order_relaxed);
if (coded_frame_result.is_error()) {
auto category = coded_frame_result.error().category();
if (category == DecoderErrorCategory::EndOfStream) {
if (m_decoder == nullptr) {
auto locker = take_lock();
- resolve_seek(seek_id);
+ resolve_handled_seek_while_locked();
return;
}
m_decoder->signal_end_of_stream();
@@ -778,11 +779,11 @@ void DecodedVideoProducer::ThreadData::push_data_and_decode_some_frames()
return;
}
- if (check_if_seek_is_needed_or_allow_demuxer_reads(m_last_processed_seek_id.load(AK::MemoryOrder::memory_order_relaxed)))
+ if (check_if_seek_is_needed_or_allow_demuxer_reads(m_last_processed_seek_id.load(MemoryOrder::memory_order_relaxed)))
return;
auto seek_is_pending = [&] {
- return m_seek_id.load(AK::MemoryOrder::memory_order_relaxed) != m_last_processed_seek_id.load(AK::MemoryOrder::memory_order_relaxed);
+ return m_seek_id.load(MemoryOrder::memory_order_relaxed) != m_last_processed_seek_id.load(MemoryOrder::memory_order_relaxed);
};
while (m_decoder != nullptr) {
@@ -809,7 +810,7 @@ void DecodedVideoProducer::ThreadData::push_data_and_decode_some_frames()
if (seek_to_replace_decoder_if_it_cannot_decode_the_stream(frame_result.error()))
return;
if (frame_result.error().category() == DecoderErrorCategory::EndOfStream) {
- auto replaced_result = replace_drained_decoder(m_last_processed_seek_id.load(AK::MemoryOrder::memory_order_relaxed));
+ auto replaced_result = replace_drained_decoder();
if (replaced_result.is_error()) {
if (seek_to_resubmit_if_decoder_lost_its_state(replaced_result.error()))
return;
@@ -839,7 +840,7 @@ void DecodedVideoProducer::ThreadData::push_data_and_decode_some_frames()
return;
auto sample_result = m_demuxer->get_next_sample_for_track(m_track);
- m_wait_state->output_should_interrupt_demuxer_reads.store(false, AK::MemoryOrder::memory_order_relaxed);
+ m_wait_state->output_should_interrupt_demuxer_reads.store(false, MemoryOrder::memory_order_relaxed);
if (sample_result.is_error()) {
auto category = sample_result.error().category();
if (category == DecoderErrorCategory::EndOfStream) {
diff --git a/Libraries/LibMedia/Producers/DecodedVideoProducer.h b/Libraries/LibMedia/Producers/DecodedVideoProducer.h
index 3c031b937ad..f1630544575 100644
--- a/Libraries/LibMedia/Producers/DecodedVideoProducer.h
+++ b/Libraries/LibMedia/Producers/DecodedVideoProducer.h
@@ -80,7 +80,7 @@ private:
DecoderErrorOr<void> receive_into_decoder(CodedFrame const&, DecodeIntent);
DecoderErrorOr<void> create_decoder_for_frame(CodedFrame const&);
DecoderErrorOr<void> receive_coded_frame(CodedFrame const&, DecodeIntent);
- DecoderErrorOr<bool> replace_drained_decoder(u32 seek_id);
+ DecoderErrorOr<bool> replace_drained_decoder();
bool check_if_seek_is_needed_or_allow_demuxer_reads(u32 seek_id);
void release_decoder();
void exit();
@@ -159,7 +159,6 @@ private:
OwnPtr<VideoDecoder> m_decoder;
NonReferenceFrameDetector m_non_reference_frame_detector;
bool m_decoder_needs_keyframe_next_seek { false };
- bool m_decoder_needs_codec_configuration_next_seek { true };
FrameQueue m_queue;
RefPtr<VideoFrame> m_last_queued_frame;
@@ -169,11 +168,16 @@ private:
ReadBlockedChangeHandler m_read_blocked_change_handler;
PipelineStatus m_current_halting_status { PipelineStatus::Pending };
+ enum class SeekReason : u8 {
+ Normal,
+ DecoderResetNeeded,
+ DataInvalidated,
+ };
+
Atomic<u32> m_last_processed_seek_id { 0 };
Atomic<u32> m_seek_id { 0 };
AK::Duration m_seek_timestamp;
- // Stays set until a seek discards the queue, so that a later seek cannot resolve from the stale frames.
- bool m_held_frames_are_invalid { false };
+ Atomic<SeekReason> m_seek_reason { SeekReason::Normal };
SynchronizedWakeHandler m_wake_handler;
mutable bool m_downstream_needs_wake { true };
diff --git a/Tests/LibMedia/StateLosingAudioDecoder.h b/Tests/LibMedia/StateLosingAudioDecoder.h
new file mode 100644
index 00000000000..070d8c6c4e2
--- /dev/null
+++ b/Tests/LibMedia/StateLosingAudioDecoder.h
@@ -0,0 +1,154 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/AtomicRefCounted.h>
+#include <AK/ConditionVariable.h>
+#include <AK/Mutex.h>
+#include <AK/NeverDestroyed.h>
+#include <AK/RefPtr.h>
+#include <LibMedia/DecoderRegistrations.h>
+#include <LibMediaCodecs/AudioDecoder.h>
+#include <LibMediaCodecs/AudioDecoderRegistry.h>
+
+// Tells a StateLosingAudioDecoder when to lose its state, and holds the decoding that follows until the test resumes it.
+class AudioDecoderStateLoss final : public AtomicRefCounted<AudioDecoderStateLoss> {
+public:
+ explicit AudioDecoderStateLoss(size_t block_index_that_loses_state)
+ : m_block_index_that_loses_state(block_index_that_loses_state)
+ {
+ }
+
+ bool wait_until_decoding_is_held_after_the_loss(AK::Duration timeout)
+ {
+ auto deadline = MonotonicTime::now() + timeout;
+ MutexLocker locker { m_mutex };
+ while (!m_decoding_is_held) {
+ auto now = MonotonicTime::now();
+ if (now >= deadline)
+ return false;
+ m_state_changed.wait_for(deadline - now);
+ }
+ return true;
+ }
+
+ void resume_decoding()
+ {
+ MutexLocker locker { m_mutex };
+ m_holds_decoding = false;
+ m_state_changed.broadcast();
+ }
+
+private:
+ friend class StateLosingAudioDecoder;
+
+ Mutex m_mutex;
+ ConditionVariable m_state_changed { m_mutex };
+ size_t const m_block_index_that_loses_state;
+ size_t m_written_block_count { 0 };
+ bool m_state_was_lost { false };
+ bool m_holds_decoding { true };
+ bool m_decoding_is_held { false };
+};
+
+// Decodes with the first installed decoder that accepts the codec, but reports that it lost its state once, instead of
+// writing the block at the chosen index.
+class StateLosingAudioDecoder final : public Media::AudioDecoder {
+public:
+ AK_ALLOC_WITH_KMALLOC;
+
+ // Decoders created while this is set lose their state there; the installed registration is skipped otherwise.
+ static void set_state_loss_for_new_decoders(RefPtr<AudioDecoderStateLoss> state_loss)
+ {
+ MutexLocker locker { *s_state_loss_mutex };
+ *s_state_loss_for_new_decoders = move(state_loss);
+ }
+
+ static ReadonlySpan<Media::AudioDecoderRegistration> registrations()
+ {
+ static constexpr Array registrations {
+ Media::AudioDecoderRegistration { capabilities, create },
+ };
+ return registrations.span();
+ }
+
+ virtual Media::DecoderErrorOr<void> receive_coded_data(Media::CodedFrame const& coded_frame) override
+ {
+ {
+ MutexLocker locker { m_state_loss->m_mutex };
+ while (m_state_loss->m_state_was_lost && m_state_loss->m_holds_decoding) {
+ m_state_loss->m_decoding_is_held = true;
+ m_state_loss->m_state_changed.broadcast();
+ m_state_loss->m_state_changed.wait();
+ }
+ }
+ return m_inner->receive_coded_data(coded_frame);
+ }
+
+ virtual void signal_end_of_stream() override { m_inner->signal_end_of_stream(); }
+
+ virtual Media::DecoderErrorOr<void> write_next_block(Media::AudioBlock& block) override
+ {
+ {
+ MutexLocker locker { m_state_loss->m_mutex };
+ if (!m_state_loss->m_state_was_lost && m_state_loss->m_written_block_count == m_state_loss->m_block_index_that_loses_state) {
+ m_state_loss->m_state_was_lost = true;
+ return Media::DecoderError::with_description(Media::DecoderErrorCategory::NeedsResubmission, "The decoder lost its state"sv);
+ }
+ }
+ TRY(m_inner->write_next_block(block));
+ MutexLocker locker { m_state_loss->m_mutex };
+ m_state_loss->m_written_block_count++;
+ return {};
+ }
+
+ virtual void flush() override { m_inner->flush(); }
+
+private:
+ static Optional<Media::DecoderCapabilities> capabilities(Media::ParsedCodec const& codec)
+ {
+ {
+ MutexLocker locker { *s_state_loss_mutex };
+ if (*s_state_loss_for_new_decoders == nullptr)
+ return {};
+ }
+ for (auto const& registration : Media::audio_decoders()) {
+ if (auto capabilities = registration.capabilities(codec); capabilities.has_value())
+ return capabilities;
+ }
+ return {};
+ }
+
+ static Media::DecoderErrorOr<NonnullOwnPtr<Media::AudioDecoder>> create(Media::CodecID codec_id, Audio::SampleSpecification const& sample_specification, ReadonlyBytes codec_initialization_data)
+ {
+ RefPtr<AudioDecoderStateLoss> state_loss;
+ {
+ MutexLocker locker { *s_state_loss_mutex };
+ state_loss = *s_state_loss_for_new_decoders;
+ }
+ if (state_loss == nullptr)
+ return Media::DecoderError::with_description(Media::DecoderErrorCategory::NotImplemented, "No test is losing decoder state"sv);
+ for (auto const& registration : Media::audio_decoders()) {
+ auto inner = registration.create(codec_id, sample_specification, codec_initialization_data);
+ if (!inner.is_error())
+ return NonnullOwnPtr<Media::AudioDecoder> { adopt_own(*new StateLosingAudioDecoder(state_loss.release_nonnull(), inner.release_value())) };
+ }
+ return Media::DecoderError::with_description(Media::DecoderErrorCategory::NotImplemented, "No installed decoder accepts the codec"sv);
+ }
+
+ StateLosingAudioDecoder(NonnullRefPtr<AudioDecoderStateLoss> state_loss, NonnullOwnPtr<Media::AudioDecoder> inner)
+ : m_state_loss(move(state_loss))
+ , m_inner(move(inner))
+ {
+ }
+
+ static inline NeverDestroyed<Mutex> s_state_loss_mutex;
+ static inline NeverDestroyed<RefPtr<AudioDecoderStateLoss>> s_state_loss_for_new_decoders;
+
+ NonnullRefPtr<AudioDecoderStateLoss> m_state_loss;
+ NonnullOwnPtr<Media::AudioDecoder> m_inner;
+};
diff --git a/Tests/LibMedia/TestDecodedAudioProducer.cpp b/Tests/LibMedia/TestDecodedAudioProducer.cpp
index b04a6849e99..5973340a689 100644
--- a/Tests/LibMedia/TestDecodedAudioProducer.cpp
+++ b/Tests/LibMedia/TestDecodedAudioProducer.cpp
@@ -4,13 +4,15 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+#include <AK/ScopeGuard.h>
#include <LibMedia/DecoderRegistrations.h>
+#include <Tests/LibMedia/StateLosingAudioDecoder.h>
#include <Tests/LibMedia/TestMediaCommon.h>
TEST_SETUP
{
Media::install_video_decoders({ Media::hardware_video_decoders(), Media::ffmpeg_video_decoders() });
- Media::install_audio_decoders({ Media::audio_decoders() });
+ Media::install_audio_decoders({ StateLosingAudioDecoder::registrations(), Media::audio_decoders() });
}
TEST_CASE(xiph_lacing)
@@ -31,3 +33,117 @@ TEST_CASE(converted_blocks_split_to_fit_the_block_capacity)
decode_audio("test-webm-xiph-lacing.mka"sv, 192'000, 2, (578038 + 530) * 4, {},
Audio::SampleSpecification(192'000, Audio::ChannelMap::stereo()));
}
+
+static NonnullRefPtr<Media::DecodedAudioProducer> create_started_audio_producer(Core::EventLoop& loop, StringView path)
+{
+ auto file = MUST(Core::File::open(path, Core::File::OpenMode::Read));
+ auto stream = Media::IncrementallyPopulatedStream::create_from_buffer(MUST(file->read_until_eof()));
+ auto demuxer = MUST(Media::create_demuxer(stream));
+ auto tracks = MUST(demuxer->get_tracks_for_type(Media::TrackType::Audio));
+ VERIFY(!tracks.is_empty());
+ auto producer = MUST(Media::DecodedAudioProducer::try_create(loop, demuxer, tracks[0]));
+ producer->set_error_handler([](Media::DecoderError&& error) {
+ FAIL(ByteString::formatted("An error occurred while decoding: {}", error.description()));
+ });
+ producer->start();
+ return producer;
+}
+
+struct BlockFrameRange {
+ i64 first_frame_index;
+ i64 end_frame_index;
+};
+
+static Optional<Vector<BlockFrameRange>> take_blocks_to_the_end_of_stream(Media::AudioProducer& producer, Core::EventLoop& loop, AK::Duration time_limit)
+{
+ Vector<BlockFrameRange> ranges;
+ auto deadline = MonotonicTime::now_coarse() + time_limit;
+ while (true) {
+ auto output = producer.peek();
+ if (output.status == Media::PipelineStatus::HaveData) {
+ ranges.append({ output.block->first_frame_index(), output.block->end_frame_index() });
+ producer.consume();
+ continue;
+ }
+ if (output.status == Media::PipelineStatus::EndOfStream)
+ return ranges;
+ if (MonotonicTime::now_coarse() >= deadline)
+ return {};
+ loop.pump(Core::EventLoop::WaitMode::PollForEvents);
+ }
+}
+
+// The blocks a decoder produced before it lost its state are still good, so they stay available while decoding
+// restarts, and decoding continues after them.
+TEST_CASE(blocks_held_when_the_decoder_loses_its_state_stay_available)
+{
+ auto& loop = never_destroyed_event_loop();
+ auto time_limit = AK::Duration::from_seconds(5);
+ auto uninterrupted_ranges = take_blocks_to_the_end_of_stream(create_started_audio_producer(loop, "test-webm-xiph-lacing.mka"sv), loop, time_limit);
+ if (!uninterrupted_ranges.has_value()) {
+ FAIL("Timed out decoding to the end of the stream without losing the decoder state");
+ return;
+ }
+
+ size_t const blocks_before_the_loss = 3;
+ VERIFY(uninterrupted_ranges->size() > blocks_before_the_loss);
+ auto state_loss = make_ref_counted<AudioDecoderStateLoss>(blocks_before_the_loss);
+ StateLosingAudioDecoder::set_state_loss_for_new_decoders(state_loss);
+ ScopeGuard stop_losing_state = [] { StateLosingAudioDecoder::set_state_loss_for_new_decoders(nullptr); };
+ auto producer = create_started_audio_producer(loop, "test-webm-xiph-lacing.mka"sv);
+ ScopeGuard release_held_decoding = [&] { state_loss->resume_decoding(); };
+
+ if (!state_loss->wait_until_decoding_is_held_after_the_loss(time_limit)) {
+ FAIL("Timed out waiting for decoding to restart after the decoder lost its state");
+ return;
+ }
+ auto output = producer->peek();
+ EXPECT_EQ(output.status, Media::PipelineStatus::HaveData);
+ state_loss->resume_decoding();
+
+ auto ranges = take_blocks_to_the_end_of_stream(producer, loop, time_limit);
+ if (!ranges.has_value()) {
+ FAIL("Timed out decoding to the end of the stream after losing the decoder state");
+ return;
+ }
+ VERIFY(ranges->size() > blocks_before_the_loss);
+ for (size_t block_index = 0; block_index < blocks_before_the_loss; block_index++) {
+ EXPECT_EQ(ranges->at(block_index).first_frame_index, uninterrupted_ranges->at(block_index).first_frame_index);
+ EXPECT_EQ(ranges->at(block_index).end_frame_index, uninterrupted_ranges->at(block_index).end_frame_index);
+ }
+ // Decoding restarts on a coded frame boundary, so the first block after the held ones may overlap them.
+ EXPECT(ranges->at(blocks_before_the_loss).first_frame_index <= ranges->at(blocks_before_the_loss - 1).end_frame_index);
+ EXPECT(ranges->at(blocks_before_the_loss).end_frame_index > ranges->at(blocks_before_the_loss - 1).end_frame_index);
+ EXPECT_EQ(ranges->last().end_frame_index, uninterrupted_ranges->last().end_frame_index);
+}
+
+TEST_CASE(a_seek_during_a_restart_lands_on_its_own_target)
+{
+ auto& loop = never_destroyed_event_loop();
+ auto state_loss = make_ref_counted<AudioDecoderStateLoss>(3);
+ StateLosingAudioDecoder::set_state_loss_for_new_decoders(state_loss);
+ ScopeGuard stop_losing_state = [] { StateLosingAudioDecoder::set_state_loss_for_new_decoders(nullptr); };
+ auto producer = create_started_audio_producer(loop, "test-webm-xiph-lacing.mka"sv);
+ ScopeGuard release_held_decoding = [&] { state_loss->resume_decoding(); };
+
+ auto time_limit = AK::Duration::from_seconds(5);
+ if (!state_loss->wait_until_decoding_is_held_after_the_loss(time_limit)) {
+ FAIL("Timed out waiting for decoding to restart after the decoder lost its state");
+ return;
+ }
+ auto target = AK::Duration::from_seconds(5);
+ producer->seek(target);
+ state_loss->resume_decoding();
+
+ auto deadline = MonotonicTime::now_coarse() + time_limit;
+ auto output = producer->peek();
+ while (output.status != Media::PipelineStatus::HaveData) {
+ if (MonotonicTime::now_coarse() >= deadline) {
+ FAIL("Timed out waiting for the seek to resolve");
+ return;
+ }
+ loop.pump(Core::EventLoop::WaitMode::PollForEvents);
+ output = producer->peek();
+ }
+ EXPECT(output.block->contains_media_time(target));
+}
diff --git a/Tests/LibMedia/TestDecodedVideoProducer.cpp b/Tests/LibMedia/TestDecodedVideoProducer.cpp
index 99b9e5a509f..143eb597b29 100644
--- a/Tests/LibMedia/TestDecodedVideoProducer.cpp
+++ b/Tests/LibMedia/TestDecodedVideoProducer.cpp
@@ -63,6 +63,8 @@ public:
{
m_seek_is_expected.store(false);
m_seek_count++;
+ if (has_flag(options, Media::DemuxerSeekOptions::Force))
+ m_forced_seek_count++;
return m_inner->seek_to_most_recent_keyframe(track, timestamp, options);
}
virtual Media::DecoderErrorOr<AK::Duration> duration_of_track(Media::Track const& track) override { return m_inner->duration_of_track(track); }
@@ -109,7 +111,13 @@ public:
m_state_changed.broadcast();
}
+ size_t samples_served()
+ {
+ MutexLocker locker { m_mutex };
+ return m_samples_served;
+ }
size_t seek_count() const { return m_seek_count; }
+ size_t forced_seek_count() const { return m_forced_seek_count; }
void expect_seek() { m_seek_is_expected.store(true); }
size_t reads_before_the_expected_seek() const { return m_reads_before_the_expected_seek; }
@@ -131,6 +139,7 @@ private:
bool m_reads_are_aborted { false };
bool m_read_is_blocked { false };
Atomic<size_t> m_seek_count { 0 };
+ Atomic<size_t> m_forced_seek_count { 0 };
Atomic<bool> m_seek_is_expected { false };
Atomic<size_t> m_reads_before_the_expected_seek { 0 };
};
@@ -686,6 +695,55 @@ TEST_CASE(no_further_sample_is_read_once_a_seek_is_requested)
EXPECT_EQ(demuxer->reads_before_the_expected_seek(), 0u);
}
+// Output can finish after a seek is requested but before the decode thread handles it. If that output covers the target,
+// the seek resolves on it without moving the demuxer.
+TEST_CASE(a_seek_resolves_on_output_queued_before_the_decode_thread_handles_it)
+{
+ auto& loop = never_destroyed_event_loop();
+ auto withheld_outputs = make_ref_counted<WithheldOutputs>();
+ WithholdingVideoDecoder::set_withheld_outputs_for_new_decoders(withheld_outputs);
+ ScopeGuard stop_withholding = [] { WithholdingVideoDecoder::set_withheld_outputs_for_new_decoders(nullptr); };
+
+ auto sample_timestamps = presentation_timestamps_of_first_samples("./vp9_in_webm.webm"sv, 1);
+ VERIFY(sample_timestamps.size() == 1);
+ auto [inner_demuxer, track] = demuxer_and_video_track_for("./vp9_in_webm.webm"sv);
+ auto demuxer = BlockingDemuxer::create(inner_demuxer, NumericLimits<size_t>::max());
+ 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->start();
+
+ auto time_limit = AK::Duration::from_seconds(5);
+ if (!withheld_outputs->wait_until_the_caller_waits_for_output(time_limit)) {
+ FAIL("Timed out waiting for the decode thread to wait for output");
+ return;
+ }
+
+ // Nothing is queued yet, so the seek can't resolve when it is requested.
+ producer->seek(sample_timestamps[0]);
+ EXPECT_EQ(producer->peek().status, Media::PipelineStatus::Pending);
+
+ // The decode thread is waiting in the decoder, so it queues this output before it handles the seek.
+ EXPECT(withheld_outputs->release_next());
+
+ auto deadline = MonotonicTime::now_coarse() + time_limit;
+ RefPtr<Media::VideoFrame> frame;
+ while (frame == nullptr && demuxer->seek_count() == 0 && MonotonicTime::now_coarse() < deadline) {
+ auto output = producer->peek();
+ if (output.status == Media::PipelineStatus::HaveData)
+ frame = output.frame;
+ else
+ loop.pump(Core::EventLoop::WaitMode::PollForEvents);
+ }
+ EXPECT_EQ(demuxer->seek_count(), 0u);
+ if (frame == nullptr) {
+ FAIL("The seek did not resolve on the queued output");
+ return;
+ }
+ EXPECT_EQ(frame->timestamp(), sample_timestamps[0]);
+}
+
// A decoder finishing output on its own threads wakes the decode thread at arbitrary points of its loops. Seeking back
// and forth through such a decoder must land on the frame covering each target every time, and never report the end
// of the stream or stop answering.
@@ -807,6 +865,308 @@ TEST_CASE(a_seek_back_within_the_last_decoded_frame_lands_on_it)
// 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
+// position even when the target is ahead of it.
+TEST_CASE(a_seek_that_invalidates_held_data_moves_the_demuxer)
+{
+ auto& loop = never_destroyed_event_loop();
+ auto sample_timestamps = presentation_timestamps_of_first_samples("./vp9_in_webm.webm"sv, 4);
+ VERIFY(sample_timestamps.size() == 4);
+
+ auto [inner_demuxer, track] = demuxer_and_video_track_for("./vp9_in_webm.webm"sv);
+ auto demuxer = BlockingDemuxer::create(inner_demuxer, 3);
+ 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->start();
+
+ auto time_limit = AK::Duration::from_seconds(5);
+ if (!demuxer->wait_until_a_read_blocks(time_limit)) {
+ FAIL("Timed out waiting for the demuxer to block");
+ return;
+ }
+
+ auto forced_seek_count_before_invalidation = demuxer->forced_seek_count();
+ producer->seek(sample_timestamps[3], Media::InvalidateHeldData::Yes);
+ demuxer->stop_blocking_reads();
+ auto frame = take_frame_within_time_limit(*producer, loop, time_limit);
+ if (frame == nullptr) {
+ FAIL("Timed out waiting for the seek to resolve");
+ return;
+ }
+ EXPECT_EQ(frame->timestamp(), sample_timestamps[3]);
+ EXPECT_EQ(demuxer->forced_seek_count(), forced_seek_count_before_invalidation + 1);
+}
+
+// A suspended producer has released its decoder, so the decoder it creates to resume has to start from a keyframe, even
+// when the demuxer could otherwise keep its position for the target.
+TEST_CASE(resuming_from_suspension_partway_into_a_group_of_pictures_moves_the_demuxer)
+{
+ auto& loop = never_destroyed_event_loop();
+
+ struct Sample {
+ AK::Duration timestamp;
+ bool is_keyframe;
+ };
+ Vector<Sample> samples;
+ {
+ auto [demuxer, track] = demuxer_and_video_track_for("./big_buck_bunny_5s.webm"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;
+ samples.append({ sample.value().presentation_timestamp(), sample.value().is_keyframe() });
+ }
+ }
+
+ auto [inner_demuxer, track] = demuxer_and_video_track_for("./big_buck_bunny_5s.webm"sv);
+ auto demuxer = BlockingDemuxer::create(inner_demuxer, NumericLimits<size_t>::max());
+ auto producer = TRY_OR_FAIL(Media::DecodedVideoProducer::try_create(loop, demuxer, track, AK::Duration::from_milliseconds(20)));
+ producer->set_error_handler([&](Media::DecoderError&& error) {
+ FAIL(ByteString::formatted("An error occurred while decoding: {}", error.description()));
+ });
+ auto woken = false;
+ producer->set_wake_handler([&] { woken = true; });
+ // A wake can still be queued on the shared event loop once this test returns.
+ ScopeGuard stop_handling_wakes = [&] { producer->set_wake_handler({}); };
+ producer->start();
+
+ // Left idle with its frame storage full, the producer suspends and wakes the consumer. Peeking counts as activity,
+ // so only peek when woken.
+ auto time_limit = AK::Duration::from_seconds(5);
+ auto deadline = MonotonicTime::now_coarse() + time_limit;
+ while (true) {
+ while (!woken) {
+ if (MonotonicTime::now_coarse() >= deadline) {
+ FAIL("Timed out waiting for the producer to suspend");
+ return;
+ }
+ loop.pump(Core::EventLoop::WaitMode::PollForEvents);
+ }
+ woken = false;
+ if (producer->peek().status == Media::PipelineStatus::Suspended)
+ break;
+ }
+
+ // Seek into the last sample of the group of pictures that the demuxer is partway into. Aim for the middle of it, since
+ // the millisecond timestamps let the frame before it claim its first moment.
+ auto next_sample_index = demuxer->samples_served();
+ if (next_sample_index >= samples.size() || samples[next_sample_index].is_keyframe) {
+ FAIL(ByteString::formatted("The producer suspended at sample {}, which doesn't continue a group of pictures", next_sample_index));
+ return;
+ }
+ auto target_index = next_sample_index;
+ while (target_index + 1 < samples.size() && !samples[target_index + 1].is_keyframe)
+ target_index++;
+ VERIFY(target_index + 1 < samples.size());
+ auto target_sample_start = samples[target_index].timestamp.to_microseconds();
+ auto target_sample_end = samples[target_index + 1].timestamp.to_microseconds();
+ auto target = AK::Duration::from_microseconds((target_sample_start + target_sample_end) / 2);
+
+ auto forced_seek_count_before_resuming = demuxer->forced_seek_count();
+ producer->seek(target);
+ auto frame = take_frame_within_time_limit(*producer, loop, time_limit);
+ if (frame == nullptr) {
+ FAIL("Timed out waiting for the seek to resolve");
+ return;
+ }
+ EXPECT_EQ(frame->timestamp(), samples[target_index].timestamp);
+ EXPECT_EQ(demuxer->forced_seek_count(), forced_seek_count_before_resuming + 1);
+}
+
+// The frames a decoder produced before it lost its state are still good, so they stay available while decoding
+// restarts from a keyframe, and decoding continues right after them.
+TEST_CASE(frames_held_when_the_decoder_loses_its_state_stay_available)
+{
+ auto& loop = never_destroyed_event_loop();
+ auto withheld_outputs = make_ref_counted<WithheldOutputs>();
+ WithholdingVideoDecoder::set_withheld_outputs_for_new_decoders(withheld_outputs);
+ ScopeGuard stop_withholding = [] { WithholdingVideoDecoder::set_withheld_outputs_for_new_decoders(nullptr); };
+
+ auto sample_timestamps = presentation_timestamps_of_first_samples("./vp9_in_webm.webm"sv, 6);
+ VERIFY(sample_timestamps.size() == 6);
+ size_t const samples_before_the_loss = 3;
+ withheld_outputs->lose_state_instead_of_handing_out_output(samples_before_the_loss);
+
+ auto [inner_demuxer, track] = demuxer_and_video_track_for("./vp9_in_webm.webm"sv);
+ auto demuxer = BlockingDemuxer::create(inner_demuxer, samples_before_the_loss);
+ 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->start();
+ AsynchronousOutputReleaser releaser { withheld_outputs };
+
+ // The output that loses the state can't arrive until the demuxer has more to read.
+ auto time_limit = AK::Duration::from_seconds(5);
+ RefPtr<Media::VideoFrame> first_held_frame;
+ auto start_time = MonotonicTime::now_coarse();
+ while (MonotonicTime::now_coarse() - start_time < time_limit) {
+ auto output = producer->peek();
+ if (output.status == Media::PipelineStatus::HaveData) {
+ first_held_frame = output.frame;
+ break;
+ }
+ loop.pump(Core::EventLoop::WaitMode::PollForEvents);
+ }
+ if (first_held_frame == nullptr) {
+ FAIL("Timed out waiting for the first frame");
+ return;
+ }
+ demuxer->stop_blocking_reads();
+ start_time = MonotonicTime::now_coarse();
+ while (!withheld_outputs->state_was_lost()) {
+ if (MonotonicTime::now_coarse() - start_time >= time_limit) {
+ FAIL("Timed out waiting for the decoder to lose its state");
+ return;
+ }
+ loop.pump(Core::EventLoop::WaitMode::PollForEvents);
+ }
+
+ for (size_t frame_index = 0; frame_index < sample_timestamps.size(); frame_index++) {
+ auto frame = take_frame_within_time_limit(*producer, loop, time_limit);
+ if (frame == nullptr) {
+ FAIL(ByteString::formatted("Timed out waiting for frame {}", frame_index));
+ return;
+ }
+ if (frame_index == 0)
+ EXPECT(frame.ptr() == first_held_frame.ptr());
+ EXPECT_EQ(frame->timestamp(), sample_timestamps[frame_index]);
+ }
+}
+
+// When the decoder loses its state during a seek past the end, the seek is retried. Once the retry reaches the end
+// without any output, the seek still has to clamp to the last frame.
+TEST_CASE(a_seek_past_the_end_lands_on_the_last_frame_when_the_decoder_loses_its_state)
+{
+ auto& loop = never_destroyed_event_loop();
+ auto withheld_outputs = make_ref_counted<WithheldOutputs>();
+ WithholdingVideoDecoder::set_withheld_outputs_for_new_decoders(withheld_outputs);
+ ScopeGuard stop_withholding = [] { WithholdingVideoDecoder::set_withheld_outputs_for_new_decoders(nullptr); };
+ withheld_outputs->lose_state_at_end_of_stream();
+
+ auto sample_timestamps = presentation_timestamps_of_first_samples("./vp9_in_webm.webm"sv, NumericLimits<size_t>::max());
+ VERIFY(!sample_timestamps.is_empty());
+ auto [demuxer, track] = demuxer_and_video_track_for("./vp9_in_webm.webm"sv);
+ 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(sample_timestamps.last() + AK::Duration::from_seconds(10));
+ producer->start();
+ AsynchronousOutputReleaser releaser { withheld_outputs };
+
+ auto time_limit = AK::Duration::from_seconds(5);
+ auto deadline = MonotonicTime::now_coarse() + time_limit;
+ auto output = producer->peek();
+ while (output.status != Media::PipelineStatus::HaveData && output.status != Media::PipelineStatus::EndOfStream) {
+ if (MonotonicTime::now_coarse() >= deadline) {
+ FAIL("Timed out waiting for the seek past the end to resolve");
+ return;
+ }
+ loop.pump(Core::EventLoop::WaitMode::PollForEvents);
+ output = producer->peek();
+ }
+ EXPECT(withheld_outputs->state_was_lost());
+ EXPECT_EQ(output.status, Media::PipelineStatus::HaveData);
+ if (output.frame != nullptr)
+ EXPECT_EQ(output.frame->timestamp(), sample_timestamps.last());
+}
+
+// Leaves the producer holding the first frame while it restarts decoding after the decoder loses its state. The
+// restart waits in the decoder until an output is released, which a seek can't interrupt.
+static bool hold_the_first_frame_through_a_restart(WithheldOutputs& withheld_outputs, AK::Duration time_limit)
+{
+ withheld_outputs.lose_state_instead_of_handing_out_output(1);
+ if (!withheld_outputs.wait_until_the_caller_waits_for_output(time_limit))
+ return false;
+ EXPECT(withheld_outputs.release_next());
+ if (!withheld_outputs.wait_until_withheld_count_reaches(WithholdingVideoDecoder::MAXIMUM_WITHHELD_OUTPUTS, time_limit))
+ return false;
+ if (!withheld_outputs.wait_until_the_caller_waits_for_output(time_limit))
+ return false;
+
+ // The restart's keyframe seek flushes the decoder, which then fills back up.
+ EXPECT(withheld_outputs.release_next());
+ if (!withheld_outputs.wait_until_withheld_count_reaches(WithholdingVideoDecoder::MAXIMUM_WITHHELD_OUTPUTS, time_limit))
+ return false;
+ if (!withheld_outputs.wait_until_the_caller_waits_for_output(time_limit))
+ return false;
+ return withheld_outputs.state_was_lost();
+}
+
+TEST_CASE(a_seek_during_a_restart_lands_on_its_own_target)
+{
+ auto& loop = never_destroyed_event_loop();
+ auto withheld_outputs = make_ref_counted<WithheldOutputs>();
+ WithholdingVideoDecoder::set_withheld_outputs_for_new_decoders(withheld_outputs);
+ ScopeGuard stop_withholding = [] { WithholdingVideoDecoder::set_withheld_outputs_for_new_decoders(nullptr); };
+
+ auto sample_timestamps = presentation_timestamps_of_first_samples("./vp9_in_webm.webm"sv, 11);
+ VERIFY(sample_timestamps.size() == 11);
+ auto producer = create_started_producer(loop, "./vp9_in_webm.webm"sv);
+
+ auto time_limit = AK::Duration::from_seconds(5);
+ if (!hold_the_first_frame_through_a_restart(withheld_outputs, time_limit)) {
+ FAIL("Timed out waiting for a restart to wait in the decoder");
+ return;
+ }
+ auto output = producer->peek();
+ EXPECT_EQ(output.status, Media::PipelineStatus::HaveData);
+ if (output.frame != nullptr)
+ EXPECT_EQ(output.frame->timestamp(), sample_timestamps[0]);
+
+ producer->seek(sample_timestamps[10]);
+ AsynchronousOutputReleaser releaser { withheld_outputs };
+ auto frame = take_frame_within_time_limit(*producer, loop, time_limit);
+ if (frame == nullptr) {
+ FAIL("Timed out waiting for the seek to resolve");
+ return;
+ }
+ EXPECT_EQ(frame->timestamp(), sample_timestamps[10]);
+}
+
+// A seek that the main thread resolves from the held frames must not cancel a restart that the decoder still needs.
+TEST_CASE(a_seek_resolved_from_held_frames_keeps_a_pending_restart)
+{
+ auto& loop = never_destroyed_event_loop();
+ auto withheld_outputs = make_ref_counted<WithheldOutputs>();
+ WithholdingVideoDecoder::set_withheld_outputs_for_new_decoders(withheld_outputs);
+ ScopeGuard stop_withholding = [] { WithholdingVideoDecoder::set_withheld_outputs_for_new_decoders(nullptr); };
+
+ auto sample_timestamps = presentation_timestamps_of_first_samples("./vp9_in_webm.webm"sv, 11);
+ VERIFY(sample_timestamps.size() == 11);
+ auto producer = create_started_producer(loop, "./vp9_in_webm.webm"sv);
+
+ auto time_limit = AK::Duration::from_seconds(5);
+ if (!hold_the_first_frame_through_a_restart(withheld_outputs, time_limit)) {
+ FAIL("Timed out waiting for a restart to wait in the decoder");
+ return;
+ }
+
+ // The first seek can't resolve from the held frames, so it's pending when the second one resolves from them.
+ producer->seek(sample_timestamps[10]);
+ producer->seek(sample_timestamps[0]);
+ auto frame = take_frame_within_time_limit(*producer, loop, time_limit);
+ if (frame == nullptr) {
+ FAIL("Timed out waiting for the held frame");
+ return;
+ }
+ EXPECT_EQ(frame->timestamp(), sample_timestamps[0]);
+
+ AsynchronousOutputReleaser releaser { withheld_outputs };
+ for (size_t frame_index = 1; frame_index < 4; frame_index++) {
+ frame = take_frame_within_time_limit(*producer, loop, time_limit);
+ if (frame == nullptr) {
+ FAIL(ByteString::formatted("Timed out waiting for frame {}", frame_index));
+ return;
+ }
+ EXPECT_EQ(frame->timestamp(), sample_timestamps[frame_index]);
+ }
+}
+
TEST_CASE(samples_that_follow_a_transient_end_of_stream_are_ignored)
{
auto& loop = never_destroyed_event_loop();
diff --git a/Tests/LibMedia/WithholdingVideoDecoder.h b/Tests/LibMedia/WithholdingVideoDecoder.h
index beac0bb581c..7bb1e423cf3 100644
--- a/Tests/LibMedia/WithholdingVideoDecoder.h
+++ b/Tests/LibMedia/WithholdingVideoDecoder.h
@@ -40,6 +40,26 @@ public:
return true;
}
+ // The decoder reports that it lost its state once, instead of handing out the output at this index.
+ void lose_state_instead_of_handing_out_output(size_t output_index)
+ {
+ MutexLocker locker { m_mutex };
+ m_output_index_that_loses_state = output_index;
+ }
+
+ // The decoder reports that it lost its state once, instead of reporting the end of the stream.
+ void lose_state_at_end_of_stream()
+ {
+ MutexLocker locker { m_mutex };
+ m_loses_state_at_end_of_stream = true;
+ }
+
+ bool state_was_lost() const
+ {
+ MutexLocker locker { m_mutex };
+ return m_state_was_lost;
+ }
+
size_t withheld_count() const
{
MutexLocker locker { m_mutex };
@@ -83,6 +103,10 @@ private:
Vector<Output> m_released;
Function<void()> m_output_arrived_callback;
bool m_caller_is_waiting_for_output { false };
+ size_t m_handed_out_count { 0 };
+ Optional<size_t> m_output_index_that_loses_state;
+ bool m_loses_state_at_end_of_stream { false };
+ bool m_state_was_lost { false };
};
// Produces a blank frame for every coded frame it is given, and withholds each one until the test releases it.
@@ -157,11 +181,22 @@ public:
m_withheld_outputs->m_caller_is_waiting_for_output = false;
}
if (m_withheld_outputs->m_released.is_empty()) {
- if (m_reached_end_of_stream)
+ if (m_reached_end_of_stream) {
+ if (exchange(m_withheld_outputs->m_loses_state_at_end_of_stream, false)) {
+ m_withheld_outputs->m_state_was_lost = true;
+ return Media::DecoderError::with_description(Media::DecoderErrorCategory::NeedsResubmission, "The decoder lost its state"sv);
+ }
return Media::DecoderError::with_description(Media::DecoderErrorCategory::EndOfStream, "Every withheld output has been taken"sv);
+ }
return Media::DecoderError::with_description(Media::DecoderErrorCategory::NeedsMoreInput, "No withheld output has been released"sv);
}
+ if (m_withheld_outputs->m_output_index_that_loses_state == m_withheld_outputs->m_handed_out_count) {
+ m_withheld_outputs->m_output_index_that_loses_state.clear();
+ m_withheld_outputs->m_state_was_lost = true;
+ return Media::DecoderError::with_description(Media::DecoderErrorCategory::NeedsResubmission, "The decoder lost its state"sv);
+ }
+
auto byte_count = FRAME_SIZE.width() * FRAME_SIZE.height() * 3 / 2;
auto acquired_slot = m_frame_pool->try_acquire(byte_count);
if (!acquired_slot.has_value())
@@ -171,6 +206,7 @@ public:
return Media::DecoderError::with_description(Media::DecoderErrorCategory::Memory, "Failed to adopt a pooled frame slot"sv);
auto output = m_withheld_outputs->m_released.take_first();
+ m_withheld_outputs->m_handed_out_count++;
return make_ref_counted<Media::VideoFrame>(output.timestamp, output.duration, FRAME_SIZE, 8, Media::Subsampling::yuv420(), container_cicp, pool_slot.release_value());
}