Truly independent web browser
LibMedia+LibMediaCodecs: Let decoders wake the producer for output
Zaggy10247b1a73fada33
diff --git a/Libraries/LibMedia/FFmpeg/FFmpegVideoDecoder.h b/Libraries/LibMedia/FFmpeg/FFmpegVideoDecoder.hindex 7c36c9ecad1..aaf0f89cf12 100644--- a/Libraries/LibMedia/FFmpeg/FFmpegVideoDecoder.h+++ b/Libraries/LibMedia/FFmpeg/FFmpegVideoDecoder.h@@ -30,6 +30,7 @@ public:virtual ~FFmpegVideoDecoder() override;virtual void set_storage_freed_callback(Function<void()> callback) override { m_frame_pool->set_slot_freed_callback(move(callback)); }+ virtual void set_output_arrived_callback(Function<void()>) override { }virtual DecoderErrorOr<void> receive_coded_data(CodedFrame const&, DecodeIntent) override;virtual void signal_end_of_stream() override;diff --git a/Libraries/LibMedia/Producers/DecodedAudioProducer.cpp b/Libraries/LibMedia/Producers/DecodedAudioProducer.cppindex 878a117a0cb..839bf3974a4 100644--- a/Libraries/LibMedia/Producers/DecodedAudioProducer.cpp+++ b/Libraries/LibMedia/Producers/DecodedAudioProducer.cpp@@ -270,6 +270,15 @@ DecoderErrorOr<bool> DecodedAudioProducer::ThreadData::replace_drained_decoder()return true;}+bool DecodedAudioProducer::ThreadData::check_if_seek_is_needed_or_allow_demuxer_reads(u32 seek_id)+{+ auto locker = take_lock();+ if (m_seek_id != seek_id)+ return true;+ m_demuxer->reset_blocking_reads_aborted_for_track(m_track);+ return false;+}+void DecodedAudioProducer::ThreadData::release_decoder(){VERIFY(m_decode_thread_id.is_current_thread());@@ -519,33 +528,10 @@ bool DecodedAudioProducer::ThreadData::handle_seek()auto new_seek_id = m_seek_id.load();while (new_seek_id == seek_id) {- auto coded_frame_result = m_demuxer->get_next_sample_for_track(m_track);- if (coded_frame_result.is_error()) {- if (coded_frame_result.error().category() == DecoderErrorCategory::EndOfStream) {- if (m_decoder == nullptr) {- auto locker = take_lock();- resolve_seek(seek_id);- return true;- }- m_decoder->signal_end_of_stream();- } else if (coded_frame_result.error().category() == DecoderErrorCategory::Aborted) {- break;- } else {- handle_error(coded_frame_result.release_error());- return true;- }- } else {- auto coded_frame = coded_frame_result.release_value();- auto decode_result = receive_coded_frame(coded_frame);- if (decode_result.is_error()) {- handle_error(decode_result.release_error());- return true;- }- }-- VERIFY(m_decoder);+ if (check_if_seek_is_needed_or_allow_demuxer_reads(seek_id))+ break;- while (new_seek_id == seek_id) {+ while (m_decoder != nullptr && new_seek_id == seek_id) {AudioBlock current_block;auto block_result = retrieve_next_block(current_block);if (block_result.is_error()) {@@ -594,6 +580,34 @@ bool DecodedAudioProducer::ThreadData::handle_seek()new_seek_id = m_seek_id;}+ if (new_seek_id != seek_id)+ break;++ auto coded_frame_result = m_demuxer->get_next_sample_for_track(m_track);+ 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);+ return true;+ }+ m_decoder->signal_end_of_stream();+ } else if (category != DecoderErrorCategory::Aborted) {+ handle_error(coded_frame_result.release_error());+ return true;+ }+ continue;+ }++ auto coded_frame = coded_frame_result.release_value();+ auto decode_result = receive_coded_frame(coded_frame);+ if (decode_result.is_error()) {+ handle_error(decode_result.release_error());+ return true;+ }++ new_seek_id = m_seek_id;}}}@@ -621,37 +635,10 @@ void DecodedAudioProducer::ThreadData::push_data_and_decode_a_block()return;}- // A seek can resolve while the decoder drains for a replacement, so the frame awaiting the new decoder is still- // pending. Only draining further gets it decoded.- auto decoder_is_draining_for_replacement = m_frame_awaiting_decoder_replacement.has_value();- if (!decoder_is_draining_for_replacement) {- auto sample_result = m_demuxer->get_next_sample_for_track(m_track);- if (sample_result.is_error()) {- if (sample_result.error().category() == DecoderErrorCategory::EndOfStream) {- if (m_decoder == nullptr) {- set_halting_status_and_wait_for_seek(PipelineStatus::EndOfStream, {});- return;- }- m_decoder->signal_end_of_stream();- } else if (sample_result.error().category() == DecoderErrorCategory::Aborted) {- return;- } else {- set_halting_status_and_wait_for_seek(PipelineStatus::Error, sample_result.release_error());- return;- }- } else {- auto coded_frame = sample_result.release_value();- auto decode_result = receive_coded_frame(coded_frame);- if (decode_result.is_error()) {- set_halting_status_and_wait_for_seek(PipelineStatus::Error, decode_result.release_error());- return;- }- }- }-- VERIFY(m_decoder);+ if (check_if_seek_is_needed_or_allow_demuxer_reads(m_last_processed_seek_id))+ return;- while (true) {+ while (m_decoder != nullptr) {auto queue_size = [&] {auto locker = take_lock();return m_queue.size();@@ -685,19 +672,45 @@ void DecodedAudioProducer::ThreadData::push_data_and_decode_a_block()auto replaced_result = replace_drained_decoder();if (replaced_result.is_error()) {set_halting_status_and_wait_for_seek(PipelineStatus::Error, replaced_result.release_error());- break;+ return;}if (replaced_result.value())continue;set_halting_status_and_wait_for_seek(PipelineStatus::EndOfStream, {});- } else- set_halting_status_and_wait_for_seek(PipelineStatus::Error, block_result.release_error());- break;+ return;+ }+ set_halting_status_and_wait_for_seek(PipelineStatus::Error, block_result.release_error());+ return;}auto locker = take_lock();queue_block(block);}++ // A seek can resolve while the decoder drains for a replacement, so the frame awaiting the new decoder is still+ // pending. Only draining further gets it decoded.+ if (m_frame_awaiting_decoder_replacement.has_value())+ return;++ auto sample_result = m_demuxer->get_next_sample_for_track(m_track);+ if (sample_result.is_error()) {+ auto category = sample_result.error().category();+ if (category == DecoderErrorCategory::EndOfStream) {+ if (m_decoder == nullptr) {+ set_halting_status_and_wait_for_seek(PipelineStatus::EndOfStream, {});+ return;+ }+ m_decoder->signal_end_of_stream();+ } else if (category != DecoderErrorCategory::Aborted) {+ set_halting_status_and_wait_for_seek(PipelineStatus::Error, sample_result.release_error());+ }+ return;+ }++ auto coded_frame = sample_result.release_value();+ auto decode_result = receive_coded_frame(coded_frame);+ if (decode_result.is_error())+ set_halting_status_and_wait_for_seek(PipelineStatus::Error, decode_result.release_error());}}diff --git a/Libraries/LibMedia/Producers/DecodedAudioProducer.h b/Libraries/LibMedia/Producers/DecodedAudioProducer.hindex db521a2f107..dd272c8f7b0 100644--- a/Libraries/LibMedia/Producers/DecodedAudioProducer.h+++ b/Libraries/LibMedia/Producers/DecodedAudioProducer.h@@ -81,6 +81,7 @@ private:DecoderErrorOr<void> receive_into_decoder(CodedFrame const&);DecoderErrorOr<void> receive_coded_frame(CodedFrame const&);DecoderErrorOr<bool> replace_drained_decoder();+ bool check_if_seek_is_needed_or_allow_demuxer_reads(u32 seek_id);void release_decoder();void exit();diff --git a/Libraries/LibMedia/Producers/DecodedVideoProducer.cpp b/Libraries/LibMedia/Producers/DecodedVideoProducer.cppindex 3d40e68e9f0..bb7b8b1fe9d 100644--- a/Libraries/LibMedia/Producers/DecodedVideoProducer.cpp+++ b/Libraries/LibMedia/Producers/DecodedVideoProducer.cpp@@ -4,6 +4,7 @@* SPDX-License-Identifier: BSD-2-Clause*/+#include <AK/ScopeGuard.h>#include <LibCore/EventLoop.h>#include <LibMedia/Demuxer.h>#include <LibMedia/Sinks/VideoSink.h>@@ -219,10 +220,25 @@ DecoderErrorOr<void> DecodedVideoProducer::ThreadData::create_decoder_for_frame(wait_state->frame_storage_was_freed = true;wait_state->condition.broadcast();});+ // 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))+ demuxer->set_blocking_reads_aborted_for_track(track);+ });m_decoder_codec_id = frame.codec_id();return {};}+bool DecodedVideoProducer::ThreadData::check_if_seek_is_needed_or_allow_demuxer_reads(u32 seek_id)+{+ auto locker = take_lock();+ 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);+ return false;+}+DecoderErrorOr<void> DecodedVideoProducer::ThreadData::receive_coded_frame(CodedFrame const& frame, DecodeIntent intent){VERIFY(!m_frame_awaiting_decoder_replacement.has_value());@@ -243,15 +259,34 @@ DecoderErrorOr<void> DecodedVideoProducer::ThreadData::receive_coded_frame(Codedreturn receive_into_decoder(frame, intent);}-DecoderErrorOr<bool> DecodedVideoProducer::ThreadData::replace_drained_decoder()+DecoderErrorOr<bool> DecodedVideoProducer::ThreadData::replace_drained_decoder(u32 seek_id){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()) {- 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));+ 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();}TRY(create_decoder_for_frame(frame));TRY(receive_into_decoder(frame, intent));@@ -347,10 +382,8 @@ void DecodedVideoProducer::ThreadData::seek(AK::Duration timestamp, InvalidateHeif (!m_held_frames_are_invalid && 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) {+ if (m_last_processed_seek_id != m_seek_id)resolve_seek(m_seek_id.load());- m_demuxer->reset_blocking_reads_aborted_for_track(m_track);- }dispatch_wake_if_needed_while_locked();return;}@@ -493,6 +526,7 @@ bool DecodedVideoProducer::ThreadData::handle_seek()seek_id = m_seek_id;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);if (!m_held_frames_are_invalid && is_within_available_range_while_locked(timestamp)) {re_emit_last_frame_if_at_end_of_stream_while_locked();@@ -540,45 +574,14 @@ bool DecodedVideoProducer::ThreadData::handle_seek()auto greatest_coded_timestamp = AK::Duration::zero();while (new_seek_id == seek_id) {- auto coded_frame_result = m_demuxer->get_next_sample_for_track(m_track);- if (coded_frame_result.is_error()) {- if (coded_frame_result.error().category() == DecoderErrorCategory::EndOfStream) {- if (m_decoder == nullptr) {- auto locker = take_lock();- resolve_seek(seek_id);- return true;- }- m_decoder->signal_end_of_stream();- } else if (coded_frame_result.error().category() == DecoderErrorCategory::Aborted) {- break;- } else {- handle_error(coded_frame_result.release_error());- return true;- }- } else {- auto coded_frame = coded_frame_result.release_value();-- // Request output for any frames that end after the seek target, indicating that they will need to- // be displayed (eventually, in reordered codecs).- 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;- 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);- if (decode_result.is_error()) {- handle_error(decode_result.release_error());- return true;- }- }-- VERIFY(m_decoder);+ if (check_if_seek_is_needed_or_allow_demuxer_reads(seek_id))+ break;- while (new_seek_id == seek_id) {+ while (m_decoder != nullptr && new_seek_id == seek_id) {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();+ auto error_or_decoder_was_replaced = replace_drained_decoder(seek_id);if (error_or_decoder_was_replaced.is_error()) {handle_error(error_or_decoder_was_replaced.release_error());return true;@@ -595,6 +598,7 @@ bool DecodedVideoProducer::ThreadData::handle_seek()m_seek_timestamp = greatest_coded_timestamp;m_seek_id++;m_decoder_needs_keyframe_next_seek = true;+ new_seek_id = m_seek_id;break;}}@@ -651,6 +655,43 @@ bool DecodedVideoProducer::ThreadData::handle_seek()new_seek_id = m_seek_id;}+ if (new_seek_id != seek_id)+ 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);+ 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);+ return true;+ }+ m_decoder->signal_end_of_stream();+ } else if (category != DecoderErrorCategory::Aborted) {+ handle_error(coded_frame_result.release_error());+ return true;+ }+ continue;+ }++ auto coded_frame = coded_frame_result.release_value();++ // Request output for any frames that end after the seek target, indicating that they will need to+ // be displayed (eventually, in reordered codecs).+ 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;+ 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);+ if (decode_result.is_error()) {+ handle_error(decode_result.release_error());+ return true;+ }++ new_seek_id = m_seek_id;}}}@@ -682,35 +723,10 @@ void DecodedVideoProducer::ThreadData::push_data_and_decode_some_frames()return;}- auto decoder_is_draining_for_replacement = m_frame_awaiting_decoder_replacement.has_value();- if (!decoder_is_draining_for_replacement) {- auto sample_result = m_demuxer->get_next_sample_for_track(m_track);- if (sample_result.is_error()) {- if (sample_result.error().category() == DecoderErrorCategory::EndOfStream) {- if (m_decoder == nullptr) {- set_halting_status_and_wait_for_seek(PipelineStatus::EndOfStream, {});- return;- }- m_decoder->signal_end_of_stream();- } else if (sample_result.error().category() == DecoderErrorCategory::Aborted) {- return;- } else {- set_halting_status_and_wait_for_seek(PipelineStatus::Error, sample_result.release_error());- return;- }- } else {- auto coded_frame = sample_result.release_value();- auto decode_result = receive_coded_frame(coded_frame, DecodeIntent::Output);- if (decode_result.is_error()) {- set_halting_status_and_wait_for_seek(PipelineStatus::Error, decode_result.release_error());- return;- }- }- }-- VERIFY(m_decoder);+ if (check_if_seek_is_needed_or_allow_demuxer_reads(m_last_processed_seek_id.load(AK::MemoryOrder::memory_order_relaxed)))+ return;- while (true) {+ while (m_decoder != nullptr) {auto frame_result = m_decoder->take_next_output(m_track.video_data().cicp);if (frame_result.is_error()) {if (frame_result.error().category() == DecoderErrorCategory::NeedsMoreInput)@@ -731,23 +747,50 @@ void DecodedVideoProducer::ThreadData::push_data_and_decode_some_frames()continue;}if (frame_result.error().category() == DecoderErrorCategory::EndOfStream) {- auto replaced_result = replace_drained_decoder();+ auto replaced_result = replace_drained_decoder(m_last_processed_seek_id.load(AK::MemoryOrder::memory_order_relaxed));if (replaced_result.is_error()) {set_halting_status_and_wait_for_seek(PipelineStatus::Error, replaced_result.release_error());- break;+ return;}if (replaced_result.value())continue;set_halting_status_and_wait_for_seek(PipelineStatus::EndOfStream, {});- } else- set_halting_status_and_wait_for_seek(PipelineStatus::Error, frame_result.release_error());- break;+ return;+ }+ set_halting_status_and_wait_for_seek(PipelineStatus::Error, frame_result.release_error());+ return;}auto frame = frame_result.release_value();auto locker = take_lock();queue_frame(frame);}++ // A seek can resolve while the decoder drains for a replacement, so the frame awaiting the new decoder is still+ // pending. Only draining further gets it decoded.+ if (m_frame_awaiting_decoder_replacement.has_value())+ 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);+ if (sample_result.is_error()) {+ auto category = sample_result.error().category();+ if (category == DecoderErrorCategory::EndOfStream) {+ if (m_decoder == nullptr) {+ set_halting_status_and_wait_for_seek(PipelineStatus::EndOfStream, {});+ return;+ }+ m_decoder->signal_end_of_stream();+ } else if (category != DecoderErrorCategory::Aborted) {+ set_halting_status_and_wait_for_seek(PipelineStatus::Error, sample_result.release_error());+ }+ return;+ }++ auto coded_frame = sample_result.release_value();+ auto decode_result = receive_coded_frame(coded_frame, DecodeIntent::Output);+ if (decode_result.is_error())+ set_halting_status_and_wait_for_seek(PipelineStatus::Error, decode_result.release_error());}}diff --git a/Libraries/LibMedia/Producers/DecodedVideoProducer.h b/Libraries/LibMedia/Producers/DecodedVideoProducer.hindex 9ceb30d15e8..8843ada2032 100644--- a/Libraries/LibMedia/Producers/DecodedVideoProducer.h+++ b/Libraries/LibMedia/Producers/DecodedVideoProducer.h@@ -79,7 +79,8 @@ 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();+ DecoderErrorOr<bool> replace_drained_decoder(u32 seek_id);+ bool check_if_seek_is_needed_or_allow_demuxer_reads(u32 seek_id);void release_decoder();void exit();@@ -134,6 +135,7 @@ private:Mutex mutex;ConditionVariable condition { mutex };bool frame_storage_was_freed { false };+ Atomic<bool> output_should_interrupt_demuxer_reads { false };};NonnullRefPtr<WaitState> m_wait_state { make_ref_counted<WaitState>() };RequestedState m_requested_state { RequestedState::None };diff --git a/Libraries/LibMedia/VideoToolbox/VideoToolboxVideoDecoder.h b/Libraries/LibMedia/VideoToolbox/VideoToolboxVideoDecoder.hindex 3d28c7d4d03..f551c2e3b2a 100644--- a/Libraries/LibMedia/VideoToolbox/VideoToolboxVideoDecoder.h+++ b/Libraries/LibMedia/VideoToolbox/VideoToolboxVideoDecoder.h@@ -39,6 +39,7 @@ public:virtual ~VideoToolboxVideoDecoder() override;virtual void set_storage_freed_callback(Function<void()> callback) override { m_surface_pool->set_slot_freed_callback(move(callback)); }+ virtual void set_output_arrived_callback(Function<void()> callback) override { m_output_arrived_callback = move(callback); }virtual DecoderErrorOr<void> receive_coded_data(CodedFrame const&, DecodeIntent) override;virtual void signal_end_of_stream() override;@@ -87,6 +88,8 @@ private:// The media engine decodes on its own threads, so outputs arrive from outside this decoder's caller.mutable Mutex m_output_mutex;ConditionVariable m_output_arrived { m_output_mutex };+ bool m_caller_is_waiting_for_output { false };+ Function<void()> m_output_arrived_callback;Vector<DecodedOutput> m_outputs;u8 m_reorder_frame_count { 0 };Optional<DecoderError> m_decode_failure;diff --git a/Libraries/LibMedia/VideoToolbox/VideoToolboxVideoDecoder.mm b/Libraries/LibMedia/VideoToolbox/VideoToolboxVideoDecoder.mmindex 30ddd79aa6f..2ce91e2f822 100644--- a/Libraries/LibMedia/VideoToolbox/VideoToolboxVideoDecoder.mm+++ b/Libraries/LibMedia/VideoToolbox/VideoToolboxVideoDecoder.mm@@ -793,16 +793,24 @@ DecoderErrorOr<void> VideoToolboxVideoDecoder::ensure_session_for_frame(CodedFravoid VideoToolboxVideoDecoder::note_decode_completed(CodingIndependentCodePoints const& cicp, u64 generation, i32 status, void* image_buffer, AK::Duration timestamp, AK::Duration duration){- MutexLocker locker { m_output_mutex };+ auto caller_needs_waking = false;+ {+ MutexLocker locker { m_output_mutex };++ if (generation == m_generation.load(AK::MemoryOrder::memory_order_relaxed)) {+ if (status != noErr)+ note_decode_failure_while_locked(status);+ else if (image_buffer != nullptr)+ enqueue_decoded_output_while_locked(cicp, image_buffer, timestamp, duration);+ auto frame_was_decoded_for_reference_only = status == noErr && image_buffer == nullptr;+ caller_needs_waking = !frame_was_decoded_for_reference_only && !m_caller_is_waiting_for_output;+ }- if (generation == m_generation.load(AK::MemoryOrder::memory_order_relaxed)) {- if (status != noErr)- note_decode_failure_while_locked(status);- else if (image_buffer != nullptr)- enqueue_decoded_output_while_locked(cicp, image_buffer, timestamp, duration);+ note_frame_left_the_media_engine_while_locked();}- note_frame_left_the_media_engine_while_locked();+ if (caller_needs_waking && m_output_arrived_callback)+ m_output_arrived_callback();}void VideoToolboxVideoDecoder::note_frame_left_the_media_engine_while_locked()@@ -908,9 +916,17 @@ DecoderErrorOr<void> VideoToolboxVideoDecoder::receive_coded_data(CodedFrame conif (intent == DecodeIntent::Reference)flags |= kVTDecodeFrame_DoNotOutputFrame;- if (m_frames_in_flight.load(AK::MemoryOrder::memory_order_relaxed) >= MAXIMUM_FRAMES_IN_FLIGHT)- return DecoderError::with_description(DecoderErrorCategory::TryAgain, "VideoToolbox is holding as many frames as it may"sv);- m_frames_in_flight.fetch_add(1, AK::MemoryOrder::memory_order_relaxed);+ // The media engine keeps decoding the frames a flush discarded until it hands them back, so a submission+ // that finds it full waits for one to leave, as taking output does.+ {+ MutexLocker locker { m_output_mutex };+ while (m_frames_in_flight.load(AK::MemoryOrder::memory_order_relaxed) >= MAXIMUM_FRAMES_IN_FLIGHT) {+ m_caller_is_waiting_for_output = true;+ m_output_arrived.wait();+ m_caller_is_waiting_for_output = false;+ }+ m_frames_in_flight.fetch_add(1, AK::MemoryOrder::memory_order_relaxed);+ }auto generation = m_generation.load(AK::MemoryOrder::memory_order_relaxed);VTDecodeInfoFlags info_flags = 0;@@ -972,7 +988,9 @@ DecoderErrorOr<NonnullRefPtr<VideoFrame>> VideoToolboxVideoDecoder::take_next_ouif (m_frames_in_flight < MAXIMUM_FRAMES_IN_FLIGHT)return DecoderError::with_description(DecoderErrorCategory::NeedsMoreInput, "VideoToolbox has no frame that later ones cannot precede"sv);+ m_caller_is_waiting_for_output = true;m_output_arrived.wait();+ m_caller_is_waiting_for_output = false;}auto frame = TRY(adopt_output_while_locked(container_cicp, 0));diff --git a/Libraries/LibMediaCodecs/VideoDecoder.h b/Libraries/LibMediaCodecs/VideoDecoder.hindex e975a61443c..bd3098c4e5d 100644--- a/Libraries/LibMediaCodecs/VideoDecoder.h+++ b/Libraries/LibMediaCodecs/VideoDecoder.h@@ -24,7 +24,13 @@ class VideoDecoder {public:virtual ~VideoDecoder() { }+ // Both callbacks are installed before any coded data is received, and run on whichever thread frees the storage+ // or finishes the output, without the decoder's locks held.virtual void set_storage_freed_callback(Function<void()>) = 0;+ // Called when output becomes available while no take_next_output() call is waiting for it, so that a caller+ // blocked elsewhere knows to come back. Decoders whose output is complete by the time receive_coded_data()+ // returns never call it.+ virtual void set_output_arrived_callback(Function<void()>) = 0;virtual DecoderErrorOr<void> receive_coded_data(CodedFrame const&, DecodeIntent) = 0;virtual void signal_end_of_stream() = 0;diff --git a/Tests/LibMedia/CMakeLists.txt b/Tests/LibMedia/CMakeLists.txtindex 67b75364e13..b2306ee32b7 100644--- a/Tests/LibMedia/CMakeLists.txt+++ b/Tests/LibMedia/CMakeLists.txt@@ -62,6 +62,7 @@ endforeach()target_link_libraries(TestAudioBlockTimingRing PRIVATE LibThreading)target_link_libraries(TestDecodedAudioProducer PRIVATE LibGfx)+target_link_libraries(TestDecodedVideoProducer PRIVATE LibThreading)target_link_libraries(TestDisplayingVideoSink PRIVATE LibGfx)target_link_libraries(TestVP9Decode PRIVATE LibGfx)target_link_libraries(TestADTSDemuxer PRIVATE LibThreading)diff --git a/Tests/LibMedia/TestDecodedVideoProducer.cpp b/Tests/LibMedia/TestDecodedVideoProducer.cppindex 75bc3074e95..a4c7f6b1f41 100644--- a/Tests/LibMedia/TestDecodedVideoProducer.cpp+++ b/Tests/LibMedia/TestDecodedVideoProducer.cpp@@ -5,19 +5,128 @@*/#include <AK/Atomic.h>+#include <AK/ConditionVariable.h>+#include <AK/Mutex.h>+#include <AK/Random.h>+#include <AK/ScopeGuard.h>+#include <LibCore/System.h>#include <LibMedia/DecoderRegistrations.h>#include <LibMedia/Producers/DecodedVideoProducer.h>#include <LibMediaCodecs/VideoFramePool.h>+#include <LibThreading/Thread.h>#include <Tests/LibMedia/TestMediaCommon.h>+#include <Tests/LibMedia/WithholdingVideoDecoder.h>TEST_SETUP{- Media::install_video_decoders({ Media::hardware_video_decoders(), Media::ffmpeg_video_decoders() });+ Media::install_video_decoders({ WithholdingVideoDecoder::registrations(), Media::hardware_video_decoders(), Media::ffmpeg_video_decoders() });Media::install_audio_decoders({ Media::audio_decoders() });}namespace {+// Serves a number of a demuxer's samples and then blocks every read until it is aborted, like a stream that has run+// out of data to read.+class BlockingDemuxer final : public Media::Demuxer {+public:+ static NonnullRefPtr<BlockingDemuxer> create(NonnullRefPtr<Media::Demuxer> inner, size_t samples_before_blocking)+ {+ return adopt_ref(*new BlockingDemuxer(move(inner), samples_before_blocking));+ }++ virtual Media::DecoderErrorOr<void> create_context_for_track(Media::Track const& track) override { return m_inner->create_context_for_track(track); }+ virtual Media::DecoderErrorOr<Vector<Media::Track>> get_tracks_for_type(Media::TrackType type) override { return m_inner->get_tracks_for_type(type); }+ virtual Media::DecoderErrorOr<Optional<Media::Track>> get_preferred_track_for_type(Media::TrackType type) override { return m_inner->get_preferred_track_for_type(type); }++ virtual Media::DecoderErrorOr<Media::CodedFrame> get_next_sample_for_track(Media::Track const& track) override+ {+ {+ MutexLocker locker { m_mutex };+ if (m_samples_served >= m_samples_before_blocking) {+ m_read_is_blocked = true;+ m_state_changed.broadcast();+ while (m_blocks_reads && !m_reads_are_aborted)+ m_state_changed.wait();+ m_read_is_blocked = false;+ if (m_reads_are_aborted)+ return Media::DecoderError::with_description(Media::DecoderErrorCategory::Aborted, "Blocking read was aborted"sv);+ }+ m_samples_served++;+ }+ return m_inner->get_next_sample_for_track(track);+ }++ virtual AK::Duration select_fast_seek_target_for_track(Media::Track const& track, AK::Duration target, Media::SeekMode mode) override { return m_inner->select_fast_seek_target_for_track(track, target, mode); }+ virtual Media::DecoderErrorOr<Media::DemuxerSeekResult> seek_to_most_recent_keyframe(Media::Track const& track, AK::Duration timestamp, Media::DemuxerSeekOptions options) override+ {+ m_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); }+ virtual Media::DecoderErrorOr<AK::Duration> total_duration() override { return m_inner->total_duration(); }+ virtual Media::DemuxerScanState const& scan_state() const LIFETIME_BOUND override { return m_inner->scan_state(); }+ virtual void set_scan_state_change_handler(ScanStateChangeHandler handler) override { m_inner->set_scan_state_change_handler(move(handler)); }++ virtual void set_blocking_reads_aborted_for_track(Media::Track const& track) override+ {+ {+ MutexLocker locker { m_mutex };+ m_reads_are_aborted = true;+ m_state_changed.broadcast();+ }+ m_inner->set_blocking_reads_aborted_for_track(track);+ }+ virtual void reset_blocking_reads_aborted_for_track(Media::Track const& track) override+ {+ {+ MutexLocker locker { m_mutex };+ m_reads_are_aborted = false;+ }+ m_inner->reset_blocking_reads_aborted_for_track(track);+ }+ virtual void set_read_blocked_change_handler_for_track(Media::Track const& track, Media::ReadBlockedChangeHandler handler) override { m_inner->set_read_blocked_change_handler_for_track(track, move(handler)); }++ bool wait_until_a_read_blocks(AK::Duration time_limit)+ {+ auto deadline = MonotonicTime::now() + time_limit;+ MutexLocker locker { m_mutex };+ while (!m_read_is_blocked) {+ auto now = MonotonicTime::now();+ if (now >= deadline)+ return false;+ m_state_changed.wait_for(deadline - now);+ }+ return true;+ }++ void stop_blocking_reads()+ {+ MutexLocker locker { m_mutex };+ m_blocks_reads = false;+ m_state_changed.broadcast();+ }++ size_t seek_count() const { return m_seek_count; }++private:+ BlockingDemuxer(NonnullRefPtr<Media::Demuxer> inner, size_t samples_before_blocking)+ : m_inner(move(inner))+ , m_samples_before_blocking(samples_before_blocking)+ {+ }++ NonnullRefPtr<Media::Demuxer> m_inner;+ size_t const m_samples_before_blocking { 0 };++ Mutex m_mutex;+ ConditionVariable m_state_changed { m_mutex };+ size_t m_samples_served { 0 };+ bool m_blocks_reads { true };+ bool m_reads_are_aborted { false };+ bool m_read_is_blocked { false };+ Atomic<size_t> m_seek_count { 0 };+};+// Presents one track whose coded frames come from one demuxer and then another, so that the codec of a track's// frames changes partway through as it does when a new initialization segment selects a different one.class SwitchingDemuxer final : public Media::Demuxer {@@ -192,6 +301,49 @@ NonnullRefPtr<Media::DecodedVideoProducer> create_started_producer(Core::EventLoreturn producer;}+Vector<AK::Duration> presentation_timestamps_of_first_samples(StringView path, size_t sample_count)+{+ auto [demuxer, track] = demuxer_and_video_track_for(path);+ MUST(demuxer->create_context_for_track(track));+ Vector<AK::Duration> timestamps;+ for (size_t sample_index = 0; sample_index < sample_count; sample_index++) {+ auto sample = demuxer->get_next_sample_for_track(track);+ if (sample.is_error())+ break;+ timestamps.append(sample.value().presentation_timestamp());+ }+ return timestamps;+}++// Releases withheld outputs from another thread a few milliseconds after they arrive, the way a media engine finishes+// frames on threads of its own.+class AsynchronousOutputReleaser {+public:+ explicit AsynchronousOutputReleaser(NonnullRefPtr<WithheldOutputs> withheld_outputs)+ : m_withheld_outputs(move(withheld_outputs))+ {+ m_thread = MUST(Threading::Thread::try_create("Release"sv, [this]() -> intptr_t {+ while (!m_stop.load()) {+ MUST(Core::System::sleep_ms(get_random_uniform(4)));+ m_withheld_outputs->release_next();+ }+ return 0;+ }));+ m_thread->start();+ }++ ~AsynchronousOutputReleaser()+ {+ m_stop.store(true);+ (void)m_thread->join();+ }++private:+ NonnullRefPtr<WithheldOutputs> m_withheld_outputs;+ Atomic<bool> m_stop { false };+ RefPtr<Threading::Thread> m_thread;+};+RefPtr<Media::VideoFrame> take_frame_within_time_limit(Media::VideoProducer& producer, Core::EventLoop& loop, AK::Duration time_limit){auto start_time = MonotonicTime::now_coarse();@@ -406,6 +558,151 @@ TEST_CASE(a_decoder_that_cannot_decode_a_later_format_is_replaced)}}+// A decoder that finishes its output on threads of its own can do so while the decode thread waits for the demuxer,+// as it does at the end of the data appended so far. That output has to reach the queue without another coded frame.+TEST_CASE(output_that_arrives_while_the_demuxer_blocks_is_delivered)+{+ 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, 3);+ auto [inner_demuxer, track] = demuxer_and_video_track_for("./vp9_in_webm.webm"sv);+ auto demuxer = BlockingDemuxer::create(inner_demuxer, sample_timestamps.size());+ 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 decode thread to block on the demuxer");+ return;+ }+ EXPECT_EQ(withheld_outputs->withheld_count(), sample_timestamps.size());+ EXPECT_NE(producer->peek().status, Media::PipelineStatus::HaveData);++ EXPECT(withheld_outputs->release_next());+ auto frame = take_frame_within_time_limit(*producer, loop, time_limit);+ if (frame == nullptr)+ FAIL("The output that arrived while the demuxer blocked was not delivered");+ else+ EXPECT_EQ(frame->timestamp(), sample_timestamps[0]);++ demuxer->stop_blocking_reads();+}++// The frame a seek resolves on can arrive the same way, and must resolve the seek without decoding from its keyframe+// again.+TEST_CASE(a_seek_resolves_on_output_that_arrives_while_the_demuxer_blocks)+{+ 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, 3);+ auto target_sample_timestamp = sample_timestamps.last();+ auto [inner_demuxer, track] = demuxer_and_video_track_for("./vp9_in_webm.webm"sv);+ auto demuxer = BlockingDemuxer::create(inner_demuxer, sample_timestamps.size());+ 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(target_sample_timestamp + AK::Duration::from_milliseconds(1));+ 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;+ }+ EXPECT_EQ(producer->peek().status, Media::PipelineStatus::Pending);++ // The samples before the block cover the target, so releasing their outputs is all the seek needs.+ auto deadline = MonotonicTime::now_coarse() + time_limit;+ RefPtr<Media::VideoFrame> frame;+ while (frame == nullptr && MonotonicTime::now_coarse() < deadline) {+ auto output = producer->peek();+ if (output.status == Media::PipelineStatus::HaveData) {+ frame = output.frame;+ break;+ }+ if (!withheld_outputs->release_next())+ loop.pump(Core::EventLoop::WaitMode::PollForEvents);+ }+ if (frame == nullptr)+ FAIL("The seek did not resolve on the output that arrived while the demuxer blocked");+ else+ EXPECT_EQ(frame->timestamp(), target_sample_timestamp);+ EXPECT_EQ(demuxer->seek_count(), 1u);++ demuxer->stop_blocking_reads();+}++// 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.+TEST_CASE(seeks_land_on_the_right_frame_while_output_arrives_asynchronously)+{+ 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, NumericLimits<size_t>::max());+ VERIFY(sample_timestamps.size() > 10);+ auto expected_frame_timestamp_for = [&](AK::Duration target) {+ auto expected = sample_timestamps.first();+ for (auto timestamp : sample_timestamps) {+ if (timestamp <= target)+ expected = timestamp;+ }+ return expected;+ };++ auto producer = create_started_producer(loop, "./vp9_in_webm.webm"sv);+ AsynchronousOutputReleaser releaser { withheld_outputs };++ auto time_limit = AK::Duration::from_seconds(5);+ auto first_timestamp = sample_timestamps.first();+ auto last_timestamp = sample_timestamps.last();+ for (size_t seek_index = 0; seek_index < 300; seek_index++) {+ auto target = first_timestamp + AK::Duration::from_milliseconds(get_random_uniform((last_timestamp - first_timestamp).to_milliseconds()));+ producer->seek(target);++ // Like a sink, consume the frames that end before the target and show the first that does not.+ auto deadline = MonotonicTime::now_coarse() + time_limit;+ RefPtr<Media::VideoFrame> frame;+ while (MonotonicTime::now_coarse() < deadline) {+ auto output = producer->peek();+ if (output.status == Media::PipelineStatus::HaveData) {+ if (output.frame->end() > target) {+ frame = output.frame;+ break;+ }+ producer->consume();+ continue;+ }+ if (output.status == Media::PipelineStatus::Error) {+ FAIL(ByteString::formatted("Seek {} to {}ms ended in an error", seek_index, target.to_milliseconds()));+ return;+ }+ loop.pump(Core::EventLoop::WaitMode::PollForEvents);+ }+ if (frame == nullptr) {+ FAIL(ByteString::formatted("Seek {} to {}ms did not resolve", seek_index, target.to_milliseconds()));+ return;+ }+ if (frame->timestamp() != expected_frame_timestamp_for(target)) {+ FAIL(ByteString::formatted("Seek {} to {}ms resolved on the frame at {}ms instead of {}ms", seek_index, target.to_milliseconds(), frame->timestamp().to_milliseconds(), expected_frame_timestamp_for(target).to_milliseconds()));+ return;+ }+ }+}+// 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.TEST_CASE(samples_that_follow_a_transient_end_of_stream_are_ignored)diff --git a/Tests/LibMedia/WithholdingVideoDecoder.h b/Tests/LibMedia/WithholdingVideoDecoder.hnew file mode 100644index 00000000000..efd23bd01a5--- /dev/null+++ b/Tests/LibMedia/WithholdingVideoDecoder.h@@ -0,0 +1,192 @@+/*+ * 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/Function.h>+#include <AK/Mutex.h>+#include <AK/NeverDestroyed.h>+#include <AK/Vector.h>+#include <LibMediaCodecs/CodecID.h>+#include <LibMediaCodecs/CodedFrame.h>+#include <LibMediaCodecs/VideoDecoder.h>+#include <LibMediaCodecs/VideoDecoderRegistry.h>+#include <LibMediaCodecs/VideoFrame.h>+#include <LibMediaCodecs/VideoFramePool.h>++// The outputs that a WithholdingVideoDecoder has finished but not handed out yet. A test releases them one at a time,+// from whichever thread it likes, the way a decoder running on threads of its own finishes frames.+class WithheldOutputs final : public AtomicRefCounted<WithheldOutputs> {+public:+ struct Output {+ AK::Duration timestamp;+ AK::Duration duration;+ };++ bool release_next()+ {+ MutexLocker locker { m_mutex };+ if (m_withheld.is_empty())+ return false;+ m_released.append(m_withheld.take_first());+ m_released_changed.broadcast();+ if (m_output_arrived_callback && !m_caller_is_waiting_for_output)+ m_output_arrived_callback();+ return true;+ }++ size_t withheld_count() const+ {+ MutexLocker locker { m_mutex };+ return m_withheld.size();+ }++private:+ friend class WithholdingVideoDecoder;++ mutable Mutex m_mutex;+ ConditionVariable m_released_changed { m_mutex };+ Vector<Output> m_withheld;+ Vector<Output> m_released;+ Function<void()> m_output_arrived_callback;+ bool m_caller_is_waiting_for_output { false };+};++// Produces a blank frame for every coded frame it is given, and withholds each one until the test releases it.+class WithholdingVideoDecoder final : public Media::VideoDecoder {+public:+ AK_ALLOC_WITH_KMALLOC;++ static constexpr Gfx::Size<u32> FRAME_SIZE { 16, 16 };+ static constexpr size_t MAXIMUM_WITHHELD_OUTPUTS = 4;++ // Decoders created while this is set withhold their outputs there; the installed registration is skipped otherwise.+ static void set_withheld_outputs_for_new_decoders(RefPtr<WithheldOutputs> withheld_outputs)+ {+ MutexLocker locker { *s_withheld_outputs_mutex };+ *s_withheld_outputs_for_new_decoders = move(withheld_outputs);+ }++ static ReadonlySpan<Media::VideoDecoderRegistration> registrations()+ {+ static constexpr Array registrations {+ Media::VideoDecoderRegistration { capabilities, create },+ };+ return registrations.span();+ }++ virtual ~WithholdingVideoDecoder() override+ {+ MutexLocker locker { m_withheld_outputs->m_mutex };+ m_withheld_outputs->m_output_arrived_callback = nullptr;+ }++ virtual void set_storage_freed_callback(Function<void()> callback) override { m_frame_pool->set_slot_freed_callback(move(callback)); }+ virtual void set_output_arrived_callback(Function<void()> callback) override+ {+ MutexLocker locker { m_withheld_outputs->m_mutex };+ m_withheld_outputs->m_output_arrived_callback = move(callback);+ }++ virtual Media::DecoderErrorOr<void> receive_coded_data(Media::CodedFrame const& coded_frame, Media::DecodeIntent intent) override+ {+ if (intent == Media::DecodeIntent::Reference)+ return {};+ MutexLocker locker { m_withheld_outputs->m_mutex };+ // A device decoding as many frames as it can at once takes the next one only when one of them finishes.+ while (m_withheld_outputs->m_withheld.size() >= MAXIMUM_WITHHELD_OUTPUTS) {+ m_withheld_outputs->m_caller_is_waiting_for_output = true;+ m_withheld_outputs->m_released_changed.wait();+ m_withheld_outputs->m_caller_is_waiting_for_output = false;+ }+ m_withheld_outputs->m_withheld.append({ coded_frame.presentation_timestamp(), coded_frame.duration() });+ return {};+ }++ virtual void signal_end_of_stream() override { m_reached_end_of_stream = true; }++ virtual Media::DecoderErrorOr<NonnullRefPtr<Media::VideoFrame>> take_next_output(Media::CodingIndependentCodePoints const& container_cicp, Optional<AK::Duration>) override+ {+ MutexLocker locker { m_withheld_outputs->m_mutex };+ // Draining waits for the withheld outputs, as a decoder waits for its device to finish them, and so does+ // holding as many as a device would decode at once.+ auto must_wait_for_a_release = [&] {+ if (!m_withheld_outputs->m_released.is_empty() || m_withheld_outputs->m_withheld.is_empty())+ return false;+ return m_reached_end_of_stream || m_withheld_outputs->m_withheld.size() >= MAXIMUM_WITHHELD_OUTPUTS;+ };+ while (must_wait_for_a_release()) {+ m_withheld_outputs->m_caller_is_waiting_for_output = true;+ m_withheld_outputs->m_released_changed.wait();+ m_withheld_outputs->m_caller_is_waiting_for_output = false;+ }+ if (m_withheld_outputs->m_released.is_empty()) {+ if (m_reached_end_of_stream)+ 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);+ }++ 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())+ return Media::DecoderError::with_description(Media::DecoderErrorCategory::TryAgain, "Every video frame slot is held elsewhere"sv);+ auto pool_slot = m_frame_pool->try_adopt_acquired_slot(*acquired_slot);+ if (pool_slot.is_error())+ 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();+ return make_ref_counted<Media::VideoFrame>(output.timestamp, output.duration, FRAME_SIZE, 8, Media::Subsampling::yuv420(), container_cicp, pool_slot.release_value());+ }++ virtual void flush() override+ {+ m_reached_end_of_stream = false;+ MutexLocker locker { m_withheld_outputs->m_mutex };+ m_withheld_outputs->m_withheld.clear();+ m_withheld_outputs->m_released.clear();+ }++private:+ static Optional<Media::DecoderCapabilities> capabilities(Media::ParsedCodec const& codec)+ {+ if (Media::track_type_from_codec_id(codec.codec_id()) != Media::TrackType::Video)+ return {};+ MutexLocker locker { *s_withheld_outputs_mutex };+ if (*s_withheld_outputs_for_new_decoders == nullptr)+ return {};+ return Media::DecoderCapabilities { .smooth = true, .power_efficient = false };+ }++ static Media::DecoderErrorOr<NonnullOwnPtr<Media::VideoDecoder>> create(Media::CodecID, ReadonlyBytes)+ {+ RefPtr<WithheldOutputs> withheld_outputs;+ {+ MutexLocker locker { *s_withheld_outputs_mutex };+ withheld_outputs = *s_withheld_outputs_for_new_decoders;+ }+ if (withheld_outputs == nullptr)+ return Media::DecoderError::with_description(Media::DecoderErrorCategory::NotImplemented, "No test is withholding outputs"sv);+ auto frame_pool = Media::VideoFramePool::create();+ if (frame_pool.is_error())+ return Media::DecoderError::with_description(Media::DecoderErrorCategory::Memory, "Failed to create a frame pool"sv);+ return NonnullOwnPtr<Media::VideoDecoder> { adopt_own(*new WithholdingVideoDecoder(withheld_outputs.release_nonnull(), frame_pool.release_value())) };+ }++ WithholdingVideoDecoder(NonnullRefPtr<WithheldOutputs> withheld_outputs, NonnullRefPtr<Media::VideoFramePool> frame_pool)+ : m_withheld_outputs(move(withheld_outputs))+ , m_frame_pool(move(frame_pool))+ {+ }++ static inline NeverDestroyed<Mutex> s_withheld_outputs_mutex;+ static inline NeverDestroyed<RefPtr<WithheldOutputs>> s_withheld_outputs_for_new_decoders;++ NonnullRefPtr<WithheldOutputs> m_withheld_outputs;+ NonnullRefPtr<Media::VideoFramePool> m_frame_pool;+ bool m_reached_end_of_stream { false };+};