Truly independent web browser
Everywhere: Move hardware video decoding to a separate process
Zaggy1024256e1bdba111
diff --git a/Libraries/LibMedia/CMakeLists.txt b/Libraries/LibMedia/CMakeLists.txtindex bfcc7728576..b92b0104d93 100644--- a/Libraries/LibMedia/CMakeLists.txt+++ b/Libraries/LibMedia/CMakeLists.txt@@ -60,6 +60,7 @@ set(SOURCESProducers/DecodedAudioProducer.cppProducers/DecodedVideoProducer.cppProducers/RemoteVideoProducer.cpp+ RemoteVideoDecoder.cppSinks/AudioPlaybackSink.cppSinks/DisplayingVideoSink.cppSinks/RemoteVideoSink.cpp@@ -79,7 +80,6 @@ set(GENERATED_SOURCESif (APPLE)list(APPEND SOURCESAudioToolbox/AudioToolboxAudioDecoder.cpp- VideoToolbox/VideoToolboxVideoDecoder.mm)endif()@@ -91,14 +91,13 @@ target_link_libraries(LibMedia PRIVATE LibCore LibCrypto LibIPC LibGfx LibThreadtarget_link_libraries(LibMedia PUBLIC LibAudio LibMediaCodecs)if (APPLE)- target_link_libraries(LibMedia PRIVATE "-framework AudioToolbox" "-framework VideoToolbox" "-framework CoreMedia" "-framework CoreVideo")+ target_link_libraries(LibMedia PRIVATE "-framework AudioToolbox")endif()target_sources(LibMedia PRIVATEFFmpeg/FFmpegAudioConverter.cppFFmpeg/FFmpegAudioDecoder.cppFFmpeg/FFmpegChannelLayout.cpp- FFmpeg/FFmpegVideoDecoder.cpp)if (NOT ANDROID)diff --git a/Libraries/LibMedia/DecoderRegistrations.cpp b/Libraries/LibMedia/DecoderRegistrations.cppindex 548af047d10..2400ee2b895 100644--- a/Libraries/LibMedia/DecoderRegistrations.cpp+++ b/Libraries/LibMedia/DecoderRegistrations.cpp@@ -7,10 +7,10 @@#include <AK/Array.h>#include <LibMedia/DecoderRegistrations.h>#include <LibMedia/FFmpeg/FFmpegAudioDecoder.h>-#include <LibMedia/FFmpeg/FFmpegVideoDecoder.h>+#include <LibMedia/RemoteVideoDecoder.h>+#include <LibMediaCodecs/FFmpeg/FFmpegVideoDecoder.h>#ifdef AK_OS_MACOS# include <LibMedia/AudioToolbox/AudioToolboxAudioDecoder.h>-# include <LibMedia/VideoToolbox/VideoToolboxVideoDecoder.h>#endif#ifdef AK_OS_LINUX# include <LibMedia/FFmpeg/SystemFFmpegDecoders.h>@@ -18,23 +18,17 @@namespace Media {-#ifdef AK_OS_MACOS-static DecoderErrorOr<NonnullOwnPtr<VideoDecoder>> create_videotoolbox_video_decoder(CodecID codec_id, ReadonlyBytes codec_initialization_data)+static DecoderErrorOr<NonnullOwnPtr<VideoDecoder>> create_remote_video_decoder(CodecID codec_id, ReadonlyBytes codec_initialization_data){- return NonnullOwnPtr<VideoDecoder> { TRY(VideoToolbox::VideoToolboxVideoDecoder::try_create(codec_id, codec_initialization_data)) };+ return NonnullOwnPtr<VideoDecoder> { TRY(RemoteVideoDecoder::try_create(codec_id, codec_initialization_data)) };}-#endif-ReadonlySpan<VideoDecoderRegistration> hardware_video_decoders()+ReadonlySpan<VideoDecoderRegistration> remote_video_decoders(){-#ifdef AK_OS_MACOSstatic Array const decoders {- VideoDecoderRegistration { VideoToolbox::VideoToolboxVideoDecoder::capabilities, create_videotoolbox_video_decoder },+ VideoDecoderRegistration { RemoteVideoDecoder::capabilities, create_remote_video_decoder },};return decoders;-#else- return {};-#endif}static DecoderErrorOr<NonnullOwnPtr<VideoDecoder>> create_ffmpeg_video_decoder(CodecID codec_id, ReadonlyBytes codec_initialization_data)diff --git a/Libraries/LibMedia/DecoderRegistrations.h b/Libraries/LibMedia/DecoderRegistrations.hindex 3f4ba248aa4..3a80dca8c5a 100644--- a/Libraries/LibMedia/DecoderRegistrations.h+++ b/Libraries/LibMedia/DecoderRegistrations.h@@ -9,11 +9,13 @@#include <AK/Span.h>#include <LibMedia/Export.h>#include <LibMediaCodecs/AudioDecoderRegistry.h>+#include <LibMediaCodecs/HardwareVideoDecoders.h>#include <LibMediaCodecs/VideoDecoderRegistry.h>namespace Media {-MEDIA_API ReadonlySpan<VideoDecoderRegistration> hardware_video_decoders();+// The decoders hosted by the VideoDecoderServer, reached through RemoteVideoDecoder.+MEDIA_API ReadonlySpan<VideoDecoderRegistration> remote_video_decoders();MEDIA_API ReadonlySpan<VideoDecoderRegistration> ffmpeg_video_decoders();MEDIA_API ReadonlySpan<AudioDecoderRegistration> audio_decoders();diff --git a/Libraries/LibMedia/FFmpeg/SystemFFmpegDecoders.cpp b/Libraries/LibMedia/FFmpeg/SystemFFmpegDecoders.cppindex cb21474d217..19647f7d842 100644--- a/Libraries/LibMedia/FFmpeg/SystemFFmpegDecoders.cpp+++ b/Libraries/LibMedia/FFmpeg/SystemFFmpegDecoders.cpp@@ -5,8 +5,8 @@*/#include <LibMedia/FFmpeg/FFmpegAudioDecoder.h>-#include <LibMedia/FFmpeg/FFmpegVideoDecoder.h>#include <LibMedia/FFmpeg/SystemFFmpegDecoders.h>+#include <LibMediaCodecs/FFmpeg/FFmpegVideoDecoder.h>#include <LibMediaCodecs/FFmpeg/SystemFFmpeg.h>namespace Media::FFmpeg {diff --git a/Libraries/LibMedia/Producers/DecodedAudioProducer.cpp b/Libraries/LibMedia/Producers/DecodedAudioProducer.cppindex 839bf3974a4..1573af977d5 100644--- a/Libraries/LibMedia/Producers/DecodedAudioProducer.cpp+++ b/Libraries/LibMedia/Producers/DecodedAudioProducer.cpp@@ -319,6 +319,7 @@ void DecodedAudioProducer::ThreadData::consume()note_consumer_activity_while_locked();if (m_queue.is_empty())return;+ m_earliest_available_timestamp = max(m_earliest_available_timestamp, m_queue.head().block.media_time_end());m_queue.dequeue();wake();}@@ -474,6 +475,38 @@ void DecodedAudioProducer::ThreadData::resolve_seek(u32 seek_id)m_last_processed_seek_id = seek_id;}+bool DecodedAudioProducer::ThreadData::seek_to_resubmit_if_decoder_lost_its_state(DecoderError const& error)+{+ if (error.category() != DecoderErrorCategory::NeedsResubmission)+ return false;++ auto locker = take_lock();+ seek_to_resubmit_while_locked();+ return true;+}++bool DecodedAudioProducer::ThreadData::seek_to_replace_decoder_if_it_cannot_decode_the_stream(DecoderError const& error)+{+ if (error.category() != DecoderErrorCategory::NotImplemented)+ return false;++ auto locker = take_lock();+ m_decoder_that_failed_due_to_missing_features = m_decoder_selection;+ m_decoder.clear();+ seek_to_resubmit_while_locked();+ return true;+}++void DecodedAudioProducer::ThreadData::seek_to_resubmit_while_locked()+{+ m_decoder_needs_keyframe_next_seek = true;+ 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_id++;+ m_downstream_needs_wake = true;+}+bool DecodedAudioProducer::ThreadData::handle_seek(){VERIFY(m_decode_thread_id.is_current_thread());@@ -498,6 +531,7 @@ bool DecodedAudioProducer::ThreadData::handle_seek()timestamp = m_seek_timestamp;m_demuxer->reset_blocking_reads_aborted_for_track(m_track);m_queue.clear();+ m_earliest_available_timestamp = timestamp;m_current_halting_status = PipelineStatus::Pending;m_frame_awaiting_decoder_replacement.clear();}@@ -538,6 +572,10 @@ bool DecodedAudioProducer::ThreadData::handle_seek()if (block_result.error().category() == DecoderErrorCategory::EndOfStream) {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;+ continue;+ }handle_error(error_or_decoder_was_replaced.release_error());return true;}@@ -554,6 +592,10 @@ bool DecodedAudioProducer::ThreadData::handle_seek()if (block_result.error().category() == DecoderErrorCategory::NeedsMoreInput)break;+ if (seek_to_resubmit_if_decoder_lost_its_state(block_result.error())) {+ new_seek_id = m_seek_id;+ continue;+ }handle_error(block_result.release_error());return true;}@@ -603,6 +645,10 @@ bool DecodedAudioProducer::ThreadData::handle_seek()auto coded_frame = coded_frame_result.release_value();auto decode_result = receive_coded_frame(coded_frame);if (decode_result.is_error()) {+ if (seek_to_resubmit_if_decoder_lost_its_state(decode_result.error())) {+ new_seek_id = m_seek_id;+ continue;+ }handle_error(decode_result.release_error());return true;}@@ -668,9 +714,13 @@ void DecodedAudioProducer::ThreadData::push_data_and_decode_a_block()if (block_result.is_error()) {if (block_result.error().category() == DecoderErrorCategory::NeedsMoreInput)break;+ if (seek_to_resubmit_if_decoder_lost_its_state(block_result.error()))+ return;if (block_result.error().category() == DecoderErrorCategory::EndOfStream) {auto replaced_result = replace_drained_decoder();if (replaced_result.is_error()) {+ if (seek_to_resubmit_if_decoder_lost_its_state(replaced_result.error()))+ return;set_halting_status_and_wait_for_seek(PipelineStatus::Error, replaced_result.release_error());return;}@@ -709,8 +759,11 @@ void DecodedAudioProducer::ThreadData::push_data_and_decode_a_block()auto coded_frame = sample_result.release_value();auto decode_result = receive_coded_frame(coded_frame);- if (decode_result.is_error())+ if (decode_result.is_error()) {+ if (seek_to_resubmit_if_decoder_lost_its_state(decode_result.error()))+ return;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 dd272c8f7b0..de6cd11991b 100644--- a/Libraries/LibMedia/Producers/DecodedAudioProducer.h+++ b/Libraries/LibMedia/Producers/DecodedAudioProducer.h@@ -98,6 +98,9 @@ private:DecoderErrorOr<void> retrieve_next_block(AudioBlock&);bool handle_seek();void resolve_seek(u32 seek_id);+ bool seek_to_resubmit_if_decoder_lost_its_state(DecoderError const&);+ bool seek_to_replace_decoder_if_it_cannot_decode_the_stream(DecoderError const&);+ void seek_to_resubmit_while_locked();void push_data_and_decode_a_block();AudioProducerOutput peek();@@ -147,6 +150,7 @@ private:size_t m_queue_max_size { 8 };AudioQueue m_queue;+ AK::Duration m_earliest_available_timestamp;ErrorHandler m_error_handler;ReadBlockedChangeHandler m_read_blocked_change_handler;PipelineStatus m_current_halting_status { PipelineStatus::Pending };diff --git a/Libraries/LibMedia/Producers/DecodedVideoProducer.cpp b/Libraries/LibMedia/Producers/DecodedVideoProducer.cppindex 83cf5ac462b..8aa5d725ab0 100644--- a/Libraries/LibMedia/Producers/DecodedVideoProducer.cpp+++ b/Libraries/LibMedia/Producers/DecodedVideoProducer.cpp@@ -502,6 +502,39 @@ void DecodedVideoProducer::ThreadData::resolve_seek(u32 seek_id)m_last_processed_seek_id = seek_id;}+bool DecodedVideoProducer::ThreadData::seek_to_resubmit_if_decoder_lost_its_state(DecoderError const& error)+{+ if (error.category() != DecoderErrorCategory::NeedsResubmission)+ return false;++ auto locker = take_lock();+ seek_to_resubmit_while_locked();+ return true;+}++bool DecodedVideoProducer::ThreadData::seek_to_replace_decoder_if_it_cannot_decode_the_stream(DecoderError const& error)+{+ if (error.category() != DecoderErrorCategory::NotImplemented)+ return false;++ auto locker = take_lock();+ m_decoder_that_failed_due_to_missing_features = m_decoder_selection;+ m_decoder.clear();+ seek_to_resubmit_while_locked();+ return true;+}++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;+ m_seek_id++;+ m_downstream_needs_wake = true;+}+bool DecodedVideoProducer::ThreadData::handle_seek(){VERIFY(m_decode_thread_id.is_current_thread());@@ -545,7 +578,8 @@ bool DecodedVideoProducer::ThreadData::handle_seek()m_latest_available_timestamp = timestamp;m_current_halting_status = PipelineStatus::Pending;m_frame_awaiting_decoder_replacement.clear();- m_decoder_that_failed_due_to_missing_features = {};+ if (m_decoder != nullptr)+ m_decoder_that_failed_due_to_missing_features = {};}auto seek_options = DemuxerSeekOptions::None;@@ -586,6 +620,10 @@ bool DecodedVideoProducer::ThreadData::handle_seek()if (frame_result.error().category() == DecoderErrorCategory::EndOfStream) {auto error_or_decoder_was_replaced = replace_drained_decoder(seek_id);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;+ continue;+ }handle_error(error_or_decoder_was_replaced.release_error());return true;}@@ -630,6 +668,14 @@ bool DecodedVideoProducer::ThreadData::handle_seek()continue;}+ if (seek_to_resubmit_if_decoder_lost_its_state(frame_result.error())) {+ new_seek_id = m_seek_id;+ continue;+ }+ if (seek_to_replace_decoder_if_it_cannot_decode_the_stream(frame_result.error())) {+ new_seek_id = m_seek_id;+ continue;+ }handle_error(frame_result.release_error());return true;}@@ -690,6 +736,10 @@ bool DecodedVideoProducer::ThreadData::handle_seek()auto decode_result = receive_coded_frame(coded_frame, decoding_for_output ? DecodeIntent::Output : DecodeIntent::Reference);if (decode_result.is_error()) {+ if (seek_to_resubmit_if_decoder_lost_its_state(decode_result.error())) {+ new_seek_id = m_seek_id;+ continue;+ }handle_error(decode_result.release_error());return true;}@@ -749,9 +799,15 @@ void DecodedVideoProducer::ThreadData::push_data_and_decode_some_frames()return;continue;}+ if (seek_to_resubmit_if_decoder_lost_its_state(frame_result.error()))+ return;+ 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));if (replaced_result.is_error()) {+ if (seek_to_resubmit_if_decoder_lost_its_state(replaced_result.error()))+ return;set_halting_status_and_wait_for_seek(PipelineStatus::Error, replaced_result.release_error());return;}@@ -792,8 +848,11 @@ void DecodedVideoProducer::ThreadData::push_data_and_decode_some_frames()auto coded_frame = sample_result.release_value();auto decode_result = receive_coded_frame(coded_frame, DecodeIntent::Output);- if (decode_result.is_error())+ if (decode_result.is_error()) {+ if (seek_to_resubmit_if_decoder_lost_its_state(decode_result.error()))+ return;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 3b6ec10edf6..77530676ffb 100644--- a/Libraries/LibMedia/Producers/DecodedVideoProducer.h+++ b/Libraries/LibMedia/Producers/DecodedVideoProducer.h@@ -105,6 +105,9 @@ private:void dispatch_error(DecoderError&&);bool handle_seek();void resolve_seek(u32 seek_id);+ bool seek_to_resubmit_if_decoder_lost_its_state(DecoderError const&);+ bool seek_to_replace_decoder_if_it_cannot_decode_the_stream(DecoderError const&);+ void seek_to_resubmit_while_locked();bool is_within_available_range_while_locked(AK::Duration) const;void re_emit_last_frame_if_at_end_of_stream_while_locked();void push_data_and_decode_some_frames();diff --git a/Libraries/LibMedia/Producers/RemoteVideoProducer.cpp b/Libraries/LibMedia/Producers/RemoteVideoProducer.cppindex b9e02c5cea1..f66ea88dcae 100644--- a/Libraries/LibMedia/Producers/RemoteVideoProducer.cpp+++ b/Libraries/LibMedia/Producers/RemoteVideoProducer.cpp@@ -112,8 +112,8 @@ void RemoteVideoProducer::seek(AK::Duration timestamp, InvalidateHeldData invali}m_expected_seek_id = requested_seek_id;- release_all_ring_frames();m_delegates.request_seek(timestamp, invalidate_held_data);+ discard_stale_ring_heads();}bool RemoteVideoProducer::can_satisfy_seek_locally(AK::Duration timestamp) constdiff --git a/Libraries/LibMedia/RemoteVideoDecoder.cpp b/Libraries/LibMedia/RemoteVideoDecoder.cppnew file mode 100644index 00000000000..db14170c3c7--- /dev/null+++ b/Libraries/LibMedia/RemoteVideoDecoder.cpp@@ -0,0 +1,795 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <AK/Atomic.h>+#include <AK/ConditionVariable.h>+#include <AK/HashMap.h>+#include <AK/Mutex.h>+#include <AK/NeverDestroyed.h>+#include <AK/ThreadID.h>+#include <AK/ThreadSafeWeakable.h>+#include <AK/Vector.h>+#include <LibCore/EventLoop.h>+#include <LibIPC/ConnectionToServer.h>+#include <LibMedia/RemoteVideoDecoder.h>+#include <LibMediaCodecs/CodedFrame.h>+#include <LibMediaCodecs/VideoDecoderClientEndpoint.h>+#include <LibMediaCodecs/VideoDecoderServerEndpoint.h>+#include <LibMediaCodecs/VideoFrame.h>+#include <LibMediaCodecs/VideoFrameHandle.h>+#include <LibMediaCodecs/VideoFramePool.h>+#include <LibThreading/Thread.h>++namespace Media {++static constexpr size_t MINIMUM_RING_SIZE = 4 * MiB;+static constexpr size_t MAXIMUM_RING_SIZE = 256 * MiB;+static constexpr AK::Duration SERVER_SILENCE_UNTIL_TREATED_AS_LOST = AK::Duration::from_seconds(10);++namespace {++class VideoDecoderClientConnection;++struct EventLoopThread {+ Core::EventLoop* event_loop { nullptr };+ AK::ThreadID thread_id;+};++}++// Shared by a decoder with the connection that routes its server's answers to it.+struct RemoteVideoDecoder::State : public AtomicRefCounted<State> {+ struct Output {+ NonnullRefPtr<PooledVideoFrameSlot> slot;+ VideoFrameHandle handle;+ };++ // A coded frame the server has yet to answer, whose data occupies its range of the ring until then.+ struct SubmissionInFlight {+ u64 ring_serial { 0 };+ u64 offset { 0 };+ u64 size { 0 };+ u32 generation { 0 };+ };++ size_t submissions_in_flight_of_current_generation() const+ {+ size_t count = 0;+ for (auto const& submission : submissions_in_flight) {+ if (submission.generation == generation)+ count++;+ }+ return count;+ }++ // The outputs are returned to be dropped after the mutex is released, since releasing their slots takes it.+ [[nodiscard]] Vector<Output> forget_server_while_locked()+ {+ connection_was_lost = true;+ connection = {};+ auto forgotten_outputs = move(outputs);+ relay_pools.clear();+ server_is_waiting_for_storage = false;+ submissions_in_flight.clear();+ failure.clear();+ server_decoder_state_changed.broadcast();+ drained = false;+ return forgotten_outputs;+ }++ Mutex mutex;+ ConditionVariable server_decoder_state_changed { mutex };+ ThreadSafeWeakRef<VideoDecoderClientConnection> connection;+ u64 decoder_id { 0 };+ u32 generation { 0 };+ bool connection_was_lost { false };+ // The server's answers are not wanted anymore, though the frames the decoder handed out still go back to it.+ bool decoder_was_destroyed { false };++ Vector<Output> outputs;+ HashMap<VideoFramePoolID, NonnullRefPtr<VideoFrameRelayPool>> relay_pools;+ Vector<SubmissionInFlight> submissions_in_flight;+ Optional<DecoderError> failure;+ bool drained { false };++ // Called under the mutex when the server reports something the decoder's caller is not already waiting for, so+ // that destroying the decoder, which clears it, ends its calls.+ Function<void()> output_arrived_callback;+ bool caller_is_waiting_for_output { false };++ // Set once before any frame is submitted, and called after the mutex is released.+ Function<void()> storage_freed_callback;+ // Set while the server waits for a slot to be released, which our caller is then answered TryAgain for. The server+ // reports nothing else while it waits, so anything it reports for the generation it waited in ends the wait too.+ bool server_is_waiting_for_storage { false };++ // Returns whether the server was waiting for storage, so that the storage freed callback must be called.+ [[nodiscard]] bool clear_server_wait_for_storage_while_locked()+ {+ return exchange(server_is_waiting_for_storage, false);+ }++ // Returns whether the server was waiting for this release, so that the storage freed callback must be called.+ [[nodiscard]] bool release_slot_to_server_while_locked(VideoFramePoolID pool_id, u32 slot_index)+ {+ connection.with_target([&](auto& connection) {+ connection.async_release_frame(pool_id, slot_index);+ });+ return clear_server_wait_for_storage_while_locked();+ }++ void tell_caller_of_new_state_while_locked()+ {+ if (!caller_is_waiting_for_output && output_arrived_callback)+ output_arrived_callback();+ }+};++namespace {++NeverDestroyed<RemoteVideoDecoder::TransportRequester> s_transport_requester;+Core::EventLoop* s_transport_requester_event_loop { nullptr };+AK::ThreadID s_transport_requester_thread_id;++// A request for a transport is in flight until its answer has been turned into a connection, or found to be none.+NeverDestroyed<Mutex> s_transport_request_mutex;+NeverDestroyed<ConditionVariable> s_transport_request_condition { *s_transport_request_mutex };+bool s_transport_request_is_in_flight { false };+u64 s_transport_requests_answered { 0 };++NeverDestroyed<Mutex> s_capabilities_mutex;+NeverDestroyed<HashMap<ParsedCodec, Optional<DecoderCapabilities>>> s_capabilities_by_format;++Atomic<u64> s_next_decoder_id { 1 };++template<typename T>+T run_on_thread(EventLoopThread const& thread, Function<T()> function)+{+ if (thread.thread_id.is_current_thread())+ return function();++ IGNORE_USE_IN_ESCAPING_LAMBDA Mutex mutex;+ IGNORE_USE_IN_ESCAPING_LAMBDA ConditionVariable condition { mutex };+ IGNORE_USE_IN_ESCAPING_LAMBDA Optional<T> result;+ thread.event_loop->deferred_invoke([&, function = move(function)] {+ auto function_result = function();+ MutexLocker locker { mutex };+ result = move(function_result);+ condition.broadcast();+ });++ MutexLocker locker { mutex };+ while (!result.has_value())+ condition.wait();+ return result.release_value();+}++// The connection's answers are handled here rather than on a busy event loop, since each one can hold up a decode.+// This thread never waits on another.+EventLoopThread const& connection_thread()+{+ static EventLoopThread const connection_thread = [] {+ IGNORE_USE_IN_ESCAPING_LAMBDA Mutex mutex;+ IGNORE_USE_IN_ESCAPING_LAMBDA ConditionVariable condition { mutex };+ IGNORE_USE_IN_ESCAPING_LAMBDA Optional<EventLoopThread> started_thread;+ auto thread = MUST(Threading::Thread::try_create("VideoDecoderIPC"sv, [&]() -> intptr_t {+ Core::EventLoop event_loop;+ {+ MutexLocker locker { mutex };+ started_thread = EventLoopThread { &event_loop, AK::ThreadID::current() };+ condition.broadcast();+ }+ return event_loop.exec();+ }));+ thread->start();+ thread->detach();++ MutexLocker locker { mutex };+ while (!started_thread.has_value())+ condition.wait();+ return *started_thread;+ }();+ return connection_thread;+}++template<typename T>+T run_on_connection_thread(Function<T()> function)+{+ return run_on_thread(connection_thread(), move(function));+}++// The connection to the VideoDecoderServer, used only on the connection thread except through weak references, whose+// targets are reached under the reference's lock.+class VideoDecoderClientConnection final+ : public IPC::ConnectionToServer<VideoDecoderClientEndpoint, VideoDecoderServerEndpoint>+ , public VideoDecoderClientEndpoint+ , public ThreadSafeWeakable<VideoDecoderClientConnection> {+ C_OBJECT_ABSTRACT(VideoDecoderClientConnection);++public:+ static ErrorOr<ThreadSafeWeakRef<VideoDecoderClientConnection>> acquire()+ {+ VERIFY(!connection_thread().thread_id.is_current_thread());+ if (auto connection = current(); connection.has_value())+ return connection.release_value();++ if (!*s_transport_requester)+ return Error::from_string_literal("No video decoder server transport requester is installed");+ // The requester answers through its thread's event loop, which that thread could not return to while waiting.+ VERIFY(!s_transport_requester_thread_id.is_current_thread());++ MutexLocker locker { *s_transport_request_mutex };+ // A request answered since the check above has already connected.+ if (auto connection = current(); connection.has_value())+ return connection.release_value();+ auto requests_answered = s_transport_requests_answered;+ if (!s_transport_request_is_in_flight) {+ s_transport_request_is_in_flight = true;+ s_transport_requester_event_loop->deferred_invoke([] {+ (*s_transport_requester)(transport_answered);+ });+ }+ while (s_transport_requests_answered == requests_answered)+ s_transport_request_condition->wait();++ if (auto connection = current(); connection.has_value())+ return connection.release_value();+ return Error::from_string_literal("Could not connect to a video decoder server");+ }++ static void transport_answered(ErrorOr<NonnullOwnPtr<IPC::Transport>> transport)+ {+ VERIFY(s_transport_requester_thread_id.is_current_thread());+ if (transport.is_error()) {+ dbgln("Could not get a transport to a video decoder server: {}", transport.error());+ } else {+ run_on_connection_thread<ThreadSafeWeakRef<VideoDecoderClientConnection>>([transport = transport.release_value()]() mutable {+ *s_connection = adopt_ref(*new VideoDecoderClientConnection(move(transport)));+ auto connection = (*s_connection)->make_weak_ref();+ MutexLocker locker { *s_current_connection_mutex };+ *s_current_connection = connection;+ return connection;+ });+ }++ MutexLocker locker { *s_transport_request_mutex };+ s_transport_request_is_in_flight = false;+ s_transport_requests_answered++;+ s_transport_request_condition->broadcast();+ }++ // Shuts the connection down on its own thread, where its death is handled, for a caller that found the server+ // unresponsive from any other thread.+ static void disconnect_from_unresponsive_server(ThreadSafeWeakRef<VideoDecoderClientConnection> connection)+ {+ connection_thread().event_loop->deferred_invoke([connection = move(connection)] {+ // Shutting down revokes the weak reference, so it happens outside the reference's lock.+ RefPtr<VideoDecoderClientConnection> strong_connection;+ connection.with_target([&](auto& target) { strong_connection = target; });+ if (strong_connection)+ strong_connection->shutdown();+ });+ }++ static Optional<Optional<DecoderCapabilities>> query_capabilities(ParsedCodec const& codec)+ {+ auto connection = acquire();+ if (connection.is_error()) {+ dbgln("Could not reach the video decoder server: {}", connection.error());+ return {};+ }+ return run_on_connection_thread<Optional<Optional<DecoderCapabilities>>>([codec]() -> Optional<Optional<DecoderCapabilities>> {+ if (s_connection->is_null())+ return {};+ auto response = (*s_connection)->send_sync_but_allow_failure<Messages::VideoDecoderServer::DecoderCapabilities>(codec);+ if (!response)+ return {};+ return response->capabilities();+ });+ }++ virtual ~VideoDecoderClientConnection() override+ {+ revoke_weak_refs();+ }++ void register_decoder(u64 decoder_id, NonnullRefPtr<RemoteVideoDecoder::State> state)+ {+ MutexLocker locker { m_decoders_mutex };+ m_decoders.set(decoder_id, move(state));+ }++ void unregister_decoder(u64 decoder_id)+ {+ MutexLocker locker { m_decoders_mutex };+ m_decoders.remove(decoder_id);+ }++private:+ explicit VideoDecoderClientConnection(NonnullOwnPtr<IPC::Transport> transport)+ : IPC::ConnectionToServer<VideoDecoderClientEndpoint, VideoDecoderServerEndpoint>(*this, move(transport))+ {+ }++ static Optional<ThreadSafeWeakRef<VideoDecoderClientConnection>> current()+ {+ MutexLocker locker { *s_current_connection_mutex };+ return *s_current_connection;+ }++ // Only the connection thread uses this.+ static NeverDestroyed<RefPtr<VideoDecoderClientConnection>> s_connection;+ // The connection that is open, for other threads to reach.+ static NeverDestroyed<Mutex> s_current_connection_mutex;+ static NeverDestroyed<Optional<ThreadSafeWeakRef<VideoDecoderClientConnection>>> s_current_connection;++ virtual void die() override+ {+ // NB: Forgetting this connection below can drop the last reference to it.+ NonnullRefPtr keep_alive_until_death_is_handled = *this;+ revoke_weak_refs();+ if (*s_connection == this) {+ *s_connection = nullptr;+ MutexLocker locker { *s_current_connection_mutex };+ *s_current_connection = {};+ }++ HashMap<u64, NonnullRefPtr<RemoteVideoDecoder::State>> decoders;+ {+ MutexLocker locker { m_decoders_mutex };+ decoders = move(m_decoders);+ }+ for (auto& [decoder_id, state] : decoders) {+ Vector<RemoteVideoDecoder::State::Output> forgotten_outputs;+ MutexLocker locker { state->mutex };+ if (state->decoder_id != decoder_id)+ continue;+ forgotten_outputs = state->forget_server_while_locked();+ state->tell_caller_of_new_state_while_locked();+ }+ }++ RefPtr<RemoteVideoDecoder::State> find_decoder(u64 decoder_id)+ {+ MutexLocker locker { m_decoders_mutex };+ if (auto state = m_decoders.get(decoder_id); state.has_value())+ return *state;+ return nullptr;+ }++ // What the decoder's caller is told of once the mutex is released: new state to take, through the output arrived+ // callback unless it is already waiting, and the end of a wait for storage it was answered TryAgain for, through+ // the storage freed callback.+ struct CallerWakeup {+ bool has_something_to_take { false };+ bool storage_was_freed { false };+ };++ // Returns whether the server reported for a decoder that is still known.+ template<typename Callback>+ bool with_decoder(u64 decoder_id, Callback callback)+ {+ auto state = find_decoder(decoder_id);+ if (!state)+ return false;+ CallerWakeup wakeup;+ {+ MutexLocker locker { state->mutex };+ if (state->decoder_id != decoder_id || state->decoder_was_destroyed)+ return false;+ wakeup = callback(*state);+ state->server_decoder_state_changed.broadcast();+ if (wakeup.has_something_to_take)+ state->tell_caller_of_new_state_while_locked();+ }+ if (wakeup.storage_was_freed && state->storage_freed_callback)+ state->storage_freed_callback();+ return true;+ }++ // A server that breaks the protocol is treated as lost, so that its decoders start over with a new one.+ void disconnect_misbehaving_server(StringView reason, Error const& error)+ {+ dbgln("The video decoder server misbehaved ({}: {}), disconnecting.", reason, error);+ shutdown();+ }++ virtual void video_frame_slot_announced(u64 decoder_id, VideoFramePoolID pool_id, u32 slot_index, Core::AnonymousBuffer slot_buffer, RefPtr<VideoSurface> surface) override+ {+ Optional<Error> misbehavior;+ with_decoder(decoder_id, [&](RemoteVideoDecoder::State& state) -> CallerWakeup {+ RefPtr<VideoFrameRelayPool> relay_pool;+ if (auto existing_relay_pool = state.relay_pools.get(pool_id); existing_relay_pool.has_value())+ relay_pool = *existing_relay_pool;+ if (!relay_pool) {+ // A pool can outlive the server it came from, whose replacement must not count its releases.+ auto relay_pool_or_error = VideoFrameRelayPool::create([state = NonnullRefPtr { state }, decoder_id, pool_id](u32 released_slot_index) {+ auto server_was_waiting_for_storage = false;+ {+ MutexLocker locker { state->mutex };+ if (state->decoder_id != decoder_id)+ return;+ server_was_waiting_for_storage = state->release_slot_to_server_while_locked(pool_id, released_slot_index);+ }+ if (server_was_waiting_for_storage && state->storage_freed_callback)+ state->storage_freed_callback();+ });+ if (relay_pool_or_error.is_error()) {+ state.failure = DecoderError::with_description(DecoderErrorCategory::Memory, "Could not create a pool to relay decoded video frames"sv);+ return { .has_something_to_take = true };+ }+ relay_pool = relay_pool_or_error.release_value();+ state.relay_pools.set(pool_id, *relay_pool);+ }+ if (auto result = relay_pool->set_slot_storage(slot_index, move(slot_buffer), move(surface)); result.is_error())+ misbehavior = result.release_error();+ return {};+ });+ if (misbehavior.has_value())+ disconnect_misbehaving_server("unusable slot"sv, *misbehavior);+ }++ virtual void frame_decoded(u64 decoder_id, u32 generation, VideoFrameHandle handle) override+ {+ Optional<Error> misbehavior;+ auto decoder_is_known = with_decoder(decoder_id, [&](RemoteVideoDecoder::State& state) -> CallerWakeup {+ // A frame that nobody wants anymore is returned to the server right away.+ if (generation != state.generation)+ return { .storage_was_freed = state.release_slot_to_server_while_locked(handle.pool_id, handle.slot_index) };+ auto storage_was_freed = state.clear_server_wait_for_storage_while_locked();+ auto relay_pool = state.relay_pools.get(handle.pool_id);+ if (!relay_pool.has_value()) {+ misbehavior = Error::from_string_literal("The frame is in a pool that was never announced");+ return {};+ }+ auto slot_or_error = (*relay_pool)->try_adopt_published_slot(handle.slot_index, handle.slot_acquisition_id);+ if (slot_or_error.is_error()) {+ misbehavior = slot_or_error.release_error();+ return {};+ }+ state.outputs.append({ slot_or_error.release_value(), handle });+ return { .has_something_to_take = true, .storage_was_freed = storage_was_freed };+ });+ if (misbehavior.has_value()) {+ disconnect_misbehaving_server("unusable frame"sv, *misbehavior);+ return;+ }+ // A decoder that is gone has no use for the frame either.+ if (!decoder_is_known)+ async_release_frame(handle.pool_id, handle.slot_index);+ }++ virtual void decoder_waiting_for_storage(u64 decoder_id, u32 generation) override+ {+ with_decoder(decoder_id, [&](RemoteVideoDecoder::State& state) -> CallerWakeup {+ if (generation == state.generation)+ state.server_is_waiting_for_storage = true;+ return {};+ });+ }++ virtual void coded_frame_consumed(u64 decoder_id) override+ {+ with_decoder(decoder_id, [&](RemoteVideoDecoder::State& state) -> CallerWakeup {+ if (!state.submissions_in_flight.is_empty())+ state.submissions_in_flight.remove(0);+ return {};+ });+ }++ virtual void decoder_failed(u64 decoder_id, u32 generation, DecoderError error) override+ {+ with_decoder(decoder_id, [&](RemoteVideoDecoder::State& state) -> CallerWakeup {+ if (generation != state.generation)+ return {};+ auto storage_was_freed = state.clear_server_wait_for_storage_while_locked();+ if (!state.failure.has_value())+ state.failure = move(error);+ return { .has_something_to_take = true, .storage_was_freed = storage_was_freed };+ });+ }++ virtual void decoder_drained(u64 decoder_id, u32 generation) override+ {+ with_decoder(decoder_id, [&](RemoteVideoDecoder::State& state) -> CallerWakeup {+ if (generation != state.generation)+ return {};+ auto storage_was_freed = state.clear_server_wait_for_storage_while_locked();+ state.drained = true;+ return { .has_something_to_take = true, .storage_was_freed = storage_was_freed };+ });+ }++ Mutex m_decoders_mutex;+ HashMap<u64, NonnullRefPtr<RemoteVideoDecoder::State>> m_decoders;+};++NeverDestroyed<RefPtr<VideoDecoderClientConnection>> VideoDecoderClientConnection::s_connection;+NeverDestroyed<Mutex> VideoDecoderClientConnection::s_current_connection_mutex;+NeverDestroyed<Optional<ThreadSafeWeakRef<VideoDecoderClientConnection>>> VideoDecoderClientConnection::s_current_connection;++}++void RemoteVideoDecoder::set_transport_requester(TransportRequester requester)+{+ *s_transport_requester = move(requester);+ s_transport_requester_event_loop = &Core::EventLoop::current();+ s_transport_requester_thread_id = AK::ThreadID::current();+}++Optional<DecoderCapabilities> RemoteVideoDecoder::capabilities(ParsedCodec const& codec)+{+ if (track_type_from_codec_id(codec.codec_id()) != TrackType::Video || !*s_transport_requester)+ return {};++ auto support_key = normalize_parsed_codec_for_support_keying(codec);+ {+ MutexLocker locker { *s_capabilities_mutex };+ if (auto cached_capabilities = s_capabilities_by_format->get(support_key); cached_capabilities.has_value())+ return *cached_capabilities;+ }++ auto capabilities = VideoDecoderClientConnection::query_capabilities(support_key);+ // An unanswered query is asked again next time, in case the server can be reached by then.+ if (!capabilities.has_value())+ return {};++ MutexLocker locker { *s_capabilities_mutex };+ s_capabilities_by_format->set(support_key, *capabilities);+ return *capabilities;+}++DecoderErrorOr<NonnullOwnPtr<RemoteVideoDecoder>> RemoteVideoDecoder::try_create(CodecID codec_id, ReadonlyBytes codec_initialization_data)+{+ auto codec_configuration = DECODER_TRY_ALLOC(ByteBuffer::copy(codec_initialization_data));+ auto state = DECODER_TRY_ALLOC(try_make_ref_counted<State>());+ auto decoder = DECODER_TRY_ALLOC(adopt_nonnull_own_or_enomem(new (nothrow) RemoteVideoDecoder(codec_id, move(codec_configuration), move(state))));+ TRY(decoder->start_server_decoder());+ return decoder;+}++RemoteVideoDecoder::RemoteVideoDecoder(CodecID codec_id, ByteBuffer codec_configuration, NonnullRefPtr<State> state)+ : m_codec_id(codec_id)+ , m_codec_configuration(move(codec_configuration))+ , m_state(move(state))+{+}++RemoteVideoDecoder::~RemoteVideoDecoder()+{+ ThreadSafeWeakRef<VideoDecoderClientConnection> connection;+ u64 decoder_id = 0;+ Vector<State::Output> outputs;+ {+ MutexLocker locker { m_state->mutex };+ connection = m_state->connection;+ decoder_id = m_state->decoder_id;+ outputs = move(m_state->outputs);+ m_state->decoder_was_destroyed = true;+ m_state->relay_pools.clear();+ m_state->output_arrived_callback = nullptr;+ }+ connection.with_target([&](auto& connection) {+ connection.async_destroy_decoder(decoder_id);+ connection.unregister_decoder(decoder_id);+ });+}++DecoderErrorOr<void> RemoteVideoDecoder::start_server_decoder()+{+ if (!*s_transport_requester)+ return DecoderError::with_description(DecoderErrorCategory::NotImplemented, "This process cannot reach a video decoder server"sv);+ if (m_server_loss_count > MAXIMUM_SERVER_LOSSES)+ return DecoderError::with_description(DecoderErrorCategory::NotImplemented, "The video decoder server was lost too many times"sv);++ auto connection_or_error = VideoDecoderClientConnection::acquire();+ if (connection_or_error.is_error())+ return DecoderError::format(DecoderErrorCategory::NotImplemented, "Could not reach the video decoder server: {}", connection_or_error.error());+ auto connection = connection_or_error.release_value();++ auto decoder_id = s_next_decoder_id.fetch_add(1, AK::MemoryOrder::memory_order_relaxed);+ u32 generation = 0;+ Vector<State::Output> forgotten_outputs;+ {+ MutexLocker locker { m_state->mutex };+ forgotten_outputs = m_state->forget_server_while_locked();+ m_state->connection_was_lost = false;+ m_state->connection = connection;+ m_state->decoder_id = decoder_id;+ generation = m_state->generation;+ }+ m_ring = {};+ m_server_loss_was_reported = false;++ auto connection_is_open = false;+ connection.with_target([&](auto& connection) {+ connection.register_decoder(decoder_id, m_state);+ connection.async_create_decoder(decoder_id, generation, m_codec_id, m_codec_configuration);+ connection_is_open = true;+ });+ if (!connection_is_open) {+ Vector<State::Output> outputs_of_the_unopened_connection;+ MutexLocker locker { m_state->mutex };+ outputs_of_the_unopened_connection = m_state->forget_server_while_locked();+ }+ return {};+}++void RemoteVideoDecoder::set_storage_freed_callback(Function<void()> callback)+{+ MutexLocker locker { m_state->mutex };+ m_state->storage_freed_callback = move(callback);+}++void RemoteVideoDecoder::set_output_arrived_callback(Function<void()> callback)+{+ MutexLocker locker { m_state->mutex };+ m_state->output_arrived_callback = move(callback);+}++DecoderError RemoteVideoDecoder::report_server_loss()+{+ m_server_loss_was_reported = true;+ m_server_loss_count++;+ return DecoderError::with_description(DecoderErrorCategory::NeedsResubmission, "The video decoder server was lost"sv);+}++DecoderErrorOr<u64> RemoteVideoDecoder::write_to_ring(ReadonlyBytes data)+{+ auto range_is_free = [&](u64 offset) {+ if (offset + data.size() > m_ring.size())+ return false;+ for (auto const& submission : m_state->submissions_in_flight) {+ if (submission.ring_serial != m_ring_serial)+ continue;+ if (offset < submission.offset + submission.size && submission.offset < offset + data.size())+ return false;+ }+ return true;+ };++ Optional<u64> offset;+ {+ MutexLocker locker { m_state->mutex };+ if (m_ring.is_valid()) {+ if (range_is_free(m_ring_write_offset))+ offset = m_ring_write_offset;+ else if (range_is_free(0))+ offset = 0;+ }+ }++ if (!offset.has_value()) {+ // The frames still in the old ring keep it alive on the server until it has consumed them.+ auto ring_size = max(m_ring.size() * 2, MINIMUM_RING_SIZE);+ while (ring_size < data.size() * 4 && ring_size < MAXIMUM_RING_SIZE)+ ring_size *= 2;+ if (data.size() > ring_size)+ return DecoderError::with_description(DecoderErrorCategory::Memory, "A coded video frame is too large to submit"sv);+ m_ring = DECODER_TRY_ALLOC(Core::AnonymousBuffer::create_with_size(ring_size));+ m_ring_serial++;+ offset = 0;++ MutexLocker locker { m_state->mutex };+ m_state->connection.with_target([&](auto& connection) {+ connection.async_replace_coded_data_ring(m_state->decoder_id, m_ring);+ });+ }++ data.copy_to(Bytes { m_ring.data<u8>() + *offset, data.size() });+ m_ring_write_offset = *offset + data.size();+ return *offset;+}++DecoderErrorOr<void> RemoteVideoDecoder::receive_coded_data(CodedFrame const& coded_frame, DecodeIntent intent)+{+ if (m_reached_end_of_stream)+ return DecoderError::with_description(DecoderErrorCategory::EndOfStream, "The decoder has been drained"sv);++ {+ MutexLocker locker { m_state->mutex };+ if (m_state->connection_was_lost && !m_server_loss_was_reported)+ return report_server_loss();+ }+ if (m_server_loss_was_reported)+ TRY(start_server_decoder());++ if (auto new_codec_configuration = coded_frame.new_codec_configuration(); new_codec_configuration.has_value())+ m_codec_configuration = DECODER_TRY_ALLOC(ByteBuffer::copy(*new_codec_configuration));++ auto ring_offset = TRY(write_to_ring(coded_frame.data()));++ Optional<ByteBuffer> new_codec_configuration;+ if (coded_frame.new_codec_configuration().has_value())+ new_codec_configuration = m_codec_configuration;++ MutexLocker locker { m_state->mutex };+ m_state->submissions_in_flight.append({ m_ring_serial, ring_offset, coded_frame.data().size(), m_state->generation });+ m_state->connection.with_target([&](auto& connection) {+ connection.async_submit_coded_frame(m_state->decoder_id, m_state->generation, ring_offset, coded_frame.data().size(), coded_frame.presentation_timestamp(), coded_frame.decode_timestamp(), coded_frame.duration(), coded_frame.flags(), move(new_codec_configuration), intent, m_output_target);+ });+ return {};+}++void RemoteVideoDecoder::signal_end_of_stream()+{+ m_reached_end_of_stream = true;+ MutexLocker locker { m_state->mutex };+ m_state->drained = false;+ m_state->connection.with_target([&](auto& connection) {+ connection.async_signal_end_of_stream(m_state->decoder_id, m_state->generation);+ });+}++DecoderErrorOr<NonnullRefPtr<VideoFrame>> RemoteVideoDecoder::take_next_output(CodingIndependentCodePoints const& container_cicp, Optional<AK::Duration> target)+{+ // The server hears of the target with the next submission, which follows the flush that any new target comes after.+ m_output_target = target;++ Optional<State::Output> output;+ {+ MutexLocker locker { m_state->mutex };+ while (true) {+ if (m_state->connection_was_lost) {+ if (!m_server_loss_was_reported)+ return report_server_loss();+ // Nothing is decoding until the frames are submitted again.+ if (m_reached_end_of_stream)+ return DecoderError::with_description(DecoderErrorCategory::EndOfStream, "The decoder has been drained"sv);+ return DecoderError::with_description(DecoderErrorCategory::NeedsMoreInput, "The decoder needs its frames submitted again"sv);+ }++ if (!m_state->outputs.is_empty()) {+ output = m_state->outputs.take_first();+ break;+ }+ if (m_state->failure.has_value())+ return m_state->failure.release_value();+ if (m_reached_end_of_stream) {+ if (m_state->drained)+ return DecoderError::with_description(DecoderErrorCategory::EndOfStream, "The decoder has been drained"sv);+ } else if (m_state->submissions_in_flight_of_current_generation() < MAXIMUM_FRAMES_IN_FLIGHT) {+ return DecoderError::with_description(DecoderErrorCategory::NeedsMoreInput, "The video decoder server has no frame ready"sv);+ }+ // Its answer waits on a slot that only our caller's consumers can release, however long they take.+ if (m_state->server_is_waiting_for_storage)+ return DecoderError::with_description(DecoderErrorCategory::TryAgain, "Every slot of the video decoder server is held"sv);+ m_state->caller_is_waiting_for_output = true;+ auto server_answered = m_state->server_decoder_state_changed.wait_for(SERVER_SILENCE_UNTIL_TREATED_AS_LOST);+ m_state->caller_is_waiting_for_output = false;+ if (!server_answered) {+ dbgln("The video decoder server has answered nothing for {} seconds, disconnecting.", SERVER_SILENCE_UNTIL_TREATED_AS_LOST.to_seconds());+ VideoDecoderClientConnection::disconnect_from_unresponsive_server(m_state->connection);+ }+ }+ }++ auto const& handle = output->handle;+ auto cicp = container_cicp;+ cicp.adopt_specified_values(handle.cicp);+ return DECODER_TRY_ALLOC(try_make_ref_counted<VideoFrame>(+ handle.timestamp, handle.duration, handle.size.to_type<u32>(),+ handle.bit_depth, handle.subsampling, cicp, move(output->slot)));+}++void RemoteVideoDecoder::flush()+{+ m_reached_end_of_stream = false;+ m_output_target = {};++ Vector<State::Output> outputs;+ MutexLocker locker { m_state->mutex };+ m_state->generation++;+ outputs = move(m_state->outputs);+ m_state->failure.clear();+ m_state->drained = false;+ m_state->server_is_waiting_for_storage = false;+ m_state->connection.with_target([&](auto& connection) {+ connection.async_flush(m_state->decoder_id, m_state->generation);+ });+}++}diff --git a/Libraries/LibMedia/RemoteVideoDecoder.h b/Libraries/LibMedia/RemoteVideoDecoder.hnew file mode 100644index 00000000000..9e3d1cedf5c--- /dev/null+++ b/Libraries/LibMedia/RemoteVideoDecoder.h@@ -0,0 +1,84 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <AK/Function.h>+#include <AK/NonnullOwnPtr.h>+#include <AK/NonnullRefPtr.h>+#include <AK/Optional.h>+#include <AK/kmalloc.h>+#include <LibCore/AnonymousBuffer.h>+#include <LibIPC/Forward.h>+#include <LibMedia/Export.h>+#include <LibMediaCodecs/CodecID.h>+#include <LibMediaCodecs/CodecParameters.h>+#include <LibMediaCodecs/DecoderCapabilities.h>+#include <LibMediaCodecs/VideoDecoder.h>++namespace Media {++// Decodes in the VideoDecoderServer. Coded frames are written to a shared-memory ring and submitted without waiting,+// and the server answers each one once it has consumed it. Output is waited for once the current generation's frames+// the server has yet to answer reach the maximum in flight, unless the server waits for one of its slots to be+// released here, which is answered with TryAgain. Decoded frames stay in the server's slots, which this process holds+// and lends onward until it releases them.+//+// If the server is lost, or answers nothing for too long while it is waited on, the next call reports+// NeedsResubmission, and the coded frames submitted after it, starting from a keyframe, go to a new server. A decoder+// that loses its server too many times answers NotImplemented instead, so that its stream falls back to the next+// decoder.+class MEDIA_API RemoteVideoDecoder final : public VideoDecoder {+public:+ AK_ALLOC_WITH_KMALLOC;++ static constexpr size_t MAXIMUM_FRAMES_IN_FLIGHT = 2;+ static constexpr u32 MAXIMUM_SERVER_LOSSES = 2;++ // The requester is called on the event loop of the thread installing it, and answers through the callback on that+ // thread, at once or later. Decoders are created and asked for capabilities on other threads, which wait for the+ // answer; the installing thread never asks, since it could not return to its event loop while waiting.+ using TransportCallback = Function<void(ErrorOr<NonnullOwnPtr<IPC::Transport>>)>;+ using TransportRequester = Function<void(TransportCallback)>;+ static void set_transport_requester(TransportRequester);++ static Optional<DecoderCapabilities> capabilities(ParsedCodec const&);+ static DecoderErrorOr<NonnullOwnPtr<RemoteVideoDecoder>> try_create(CodecID, ReadonlyBytes codec_initialization_data);++ virtual ~RemoteVideoDecoder() override;++ virtual void set_storage_freed_callback(Function<void()>) override;+ 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;+ virtual DecoderErrorOr<NonnullRefPtr<VideoFrame>> take_next_output(CodingIndependentCodePoints const& container_cicp, Optional<AK::Duration> target = {}) override;+ virtual void flush() override;++ struct State;++private:+ RemoteVideoDecoder(CodecID, ByteBuffer codec_configuration, NonnullRefPtr<State>);++ DecoderErrorOr<void> start_server_decoder();+ DecoderErrorOr<u64> write_to_ring(ReadonlyBytes);+ DecoderError report_server_loss();++ CodecID const m_codec_id;+ ByteBuffer m_codec_configuration;+ NonnullRefPtr<State> m_state;++ // Only the caller's thread uses these.+ bool m_reached_end_of_stream { false };+ bool m_server_loss_was_reported { false };+ u32 m_server_loss_count { 0 };+ Optional<AK::Duration> m_output_target;+ Core::AnonymousBuffer m_ring;+ u64 m_ring_serial { 0 };+ u64 m_ring_write_offset { 0 };+};++}diff --git a/Libraries/LibMediaClient/Client.cpp b/Libraries/LibMediaClient/Client.cppindex 71344b621c7..dfef9e24cf8 100644--- a/Libraries/LibMediaClient/Client.cpp+++ b/Libraries/LibMediaClient/Client.cpp@@ -83,6 +83,25 @@ Messages::MediaClient::RequestAudioServerConnectionResponse Client::request_audireturn handle.release_value();}+void Client::request_video_decoder_server_connection(u64 request_id)+{+ if (!on_request_video_decoder_server_connection) {+ dbgln("A MediaServer asked a non-controller for a VideoDecoderServer connection");+ async_video_decoder_server_connection_ready(request_id, OptionalNone {});+ return;+ }+ on_request_video_decoder_server_connection([self = NonnullRefPtr(*this), request_id](ErrorOr<IPC::TransportHandle> handle) {+ if (!self->is_open())+ return;+ if (handle.is_error()) {+ warnln("Unable to connect a MediaServer to a VideoDecoderServer: {}", handle.error());+ self->async_video_decoder_server_connection_ready(request_id, OptionalNone {});+ return;+ }+ self->async_video_decoder_server_connection_ready(request_id, handle.release_value());+ });+}+u64 Client::allocate_id(){return m_next_id++;diff --git a/Libraries/LibMediaClient/Client.h b/Libraries/LibMediaClient/Client.hindex f8b85a4fd5b..1b1ecfa5e26 100644--- a/Libraries/LibMediaClient/Client.h+++ b/Libraries/LibMediaClient/Client.h@@ -49,6 +49,9 @@ public:// Set by the Browser on the controller connection; a server's request for an AudioServer connection goes here.Function<ErrorOr<IPC::TransportHandle>()> on_request_audio_server_connection;+ // The answer may be given later, once the Browser can launch a server.+ using VideoDecoderServerConnectionAnswer = Function<void(ErrorOr<IPC::TransportHandle>)>;+ Function<void(VideoDecoderServerConnectionAnswer)> on_request_video_decoder_server_connection;// The synchronous queries serve APIs that must answer on the spot; everything else asks through a promise.Media::MediaSupportInfo query_file_media_support(StringView type, StringView subtype, Optional<String> codecs_parameter);@@ -82,6 +85,7 @@ private:virtual void die() override;virtual Messages::MediaClient::RequestAudioServerConnectionResponse request_audio_server_connection() override;+ virtual void request_video_decoder_server_connection(u64 request_id) override;virtual void file_media_support_reported(u64 request_id, Media::MediaSupportInfo info) override;virtual void decoder_capabilities_reported(u64 request_id, Optional<Media::DecoderCapabilities> capabilities) override;virtual void audio_data_decoded(u64 request_id, u32 sample_rate, u32 channel_count, u64 frame_count, Core::AnonymousBuffer planar_samples) override;diff --git a/Libraries/LibMediaCodecs/CMakeLists.txt b/Libraries/LibMediaCodecs/CMakeLists.txtindex f0a16edba6d..b3770ba2729 100644--- a/Libraries/LibMediaCodecs/CMakeLists.txt+++ b/Libraries/LibMediaCodecs/CMakeLists.txt@@ -12,8 +12,11 @@ set(SOURCESDecoderError.cppFFmpeg/FFmpegFunctions.cppFFmpeg/FFmpegHelpers.cpp+ FFmpeg/FFmpegVideoDecoder.cpp+ HardwareVideoDecoders.cppNonReferenceFrameDetector.cppVideoDecoderRegistry.cpp+ VideoDecoderServerConnection.cppVideoFrame.cppVideoFrameHandle.cppVideoFramePool.cpp@@ -24,8 +27,24 @@ if (LINUX)list(APPEND SOURCES FFmpeg/SystemFFmpeg.cpp)endif()+if (APPLE)+ list(APPEND SOURCES VideoToolbox/VideoToolboxVideoDecoder.mm)+endif()++set(GENERATED_SOURCES+ VideoDecoderClientEndpoint.h+ VideoDecoderServerEndpoint.h+ ../../Services/VideoDecoderServer/VideoDecoderServerControlClientEndpoint.h+ ../../Services/VideoDecoderServer/VideoDecoderServerControlEndpoint.h+)++compile_ipc(VideoDecoderClient.ipc VideoDecoderClientEndpoint.h)+compile_ipc(VideoDecoderServer.ipc VideoDecoderServerEndpoint.h)+compile_ipc(../../Services/VideoDecoderServer/VideoDecoderServerControl.ipc ../../Services/VideoDecoderServer/VideoDecoderServerControlEndpoint.h)+compile_ipc(../../Services/VideoDecoderServer/VideoDecoderServerControlClient.ipc ../../Services/VideoDecoderServer/VideoDecoderServerControlClientEndpoint.h)+ladybird_lib(LibMediaCodecs mediacodecs EXPLICIT_SYMBOL_EXPORT)-target_link_libraries(LibMediaCodecs PRIVATE LibCore LibGfx LibIPC)+target_link_libraries(LibMediaCodecs PRIVATE LibCore LibGfx LibIPC LibThreading)target_link_libraries(LibMediaCodecs PUBLIC LibAudio)if (NOT ANDROID)@@ -39,3 +58,7 @@ endif()if (LINUX)target_link_libraries(LibMediaCodecs PRIVATE ${CMAKE_DL_LIBS})endif()++if (APPLE)+ target_link_libraries(LibMediaCodecs PRIVATE "-framework VideoToolbox" "-framework CoreMedia" "-framework CoreVideo")+endif()diff --git a/Libraries/LibMediaCodecs/CodecParameters.cpp b/Libraries/LibMediaCodecs/CodecParameters.cppindex 9dbf2160527..57a78359901 100644--- a/Libraries/LibMediaCodecs/CodecParameters.cpp+++ b/Libraries/LibMediaCodecs/CodecParameters.cpp@@ -6,6 +6,8 @@#include <AK/GenericLexer.h>#include <AK/GenericShorthands.h>+#include <LibIPC/Decoder.h>+#include <LibIPC/Encoder.h>#include <LibMediaCodecs/CodecParameters.h>#include <LibMediaCodecs/Codecs/MPEG4Audio.h>#include <LibMediaCodecs/CodedFrame.h>@@ -154,4 +156,168 @@ ParsedCodec parsed_codec_for_coded_frame(CodedFrame const& coded_frame, ParsedCoreturn ParsedCodec { codec_id };}+ParsedCodec normalize_parsed_codec_for_support_keying(ParsedCodec const& codec)+{+ switch (codec.codec_id()) {+ case CodecID::VP9: {+ auto parameters = codec.vp9_parameters().value_or({ .profile = 0, .level = 0, .bit_depth = 8, .color_parameters = {} });+ parameters.level = 0;+ parameters.color_parameters.cicp = {};+ return ParsedCodec { parameters };+ }+ case CodecID::AV1: {+ auto parameters = codec.av1_parameters().value_or({ .profile = 0, .level = 0, .tier = Codecs::AV1::Tier::Main, .bit_depth = 8, .optional_fields = {} });+ parameters.level = 0;+ parameters.tier = Codecs::AV1::Tier::Main;+ parameters.optional_fields.cicp = {};+ return ParsedCodec { parameters };+ }+ case CodecID::H264: {+ Optional<Codecs::H264::Profile> profile = Codecs::H264::Profile::Main;+ if (auto parameters = codec.h264_parameters(); parameters.has_value())+ profile = parameters->profile();+ if (!profile.has_value())+ return codec;+ return ParsedCodec { Codecs::H264::canonical_parameters_for_profile(*profile) };+ }+ case CodecID::H265: {+ Optional<Codecs::H265::Profile> profile = Codecs::H265::Profile::Main;+ if (auto parameters = codec.h265_parameters(); parameters.has_value())+ profile = parameters->profile();+ if (!profile.has_value())+ return codec;+ return ParsedCodec { Codecs::H265::canonical_parameters_for_profile(*profile) };+ }+ default:+ return codec;+ }+}++}++namespace IPC {++template<>+ErrorOr<void> encode(Encoder& encoder, Media::ParsedCodec const& codec)+{+ TRY(encoder.encode(codec.codec_id()));+ TRY(encoder.encode(codec.has_parameters()));+ if (!codec.has_parameters())+ return {};++ switch (codec.codec_id()) {+ case Media::CodecID::AAC: {+ auto const& parameters = *codec.aac_parameters();+ TRY(encoder.encode(parameters.object_type_indication));+ TRY(encoder.encode(parameters.audio_object_type));+ return {};+ }+ case Media::CodecID::H264: {+ auto const& parameters = *codec.h264_parameters();+ TRY(encoder.encode(parameters.profile_idc));+ TRY(encoder.encode(parameters.constraint_set_flags));+ TRY(encoder.encode(parameters.level_idc));+ return {};+ }+ case Media::CodecID::H265: {+ auto const& parameters = *codec.h265_parameters();+ for (auto flags : parameters.constraint_indicator_flags)+ TRY(encoder.encode(flags));+ TRY(encoder.encode(parameters.profile_compatibility_flags));+ TRY(encoder.encode(parameters.profile_space));+ TRY(encoder.encode(parameters.profile_idc));+ TRY(encoder.encode(parameters.level_idc));+ TRY(encoder.encode(parameters.tier_flag));+ return {};+ }+ case Media::CodecID::AV1: {+ auto const& parameters = *codec.av1_parameters();+ TRY(encoder.encode(parameters.profile));+ TRY(encoder.encode(parameters.level));+ TRY(encoder.encode(parameters.tier));+ TRY(encoder.encode(parameters.bit_depth));+ TRY(encoder.encode(parameters.optional_fields.monochrome));+ TRY(encoder.encode(parameters.optional_fields.subsampling.x()));+ TRY(encoder.encode(parameters.optional_fields.subsampling.y()));+ TRY(encoder.encode(parameters.optional_fields.chroma_sample_position));+ TRY(encoder.encode(parameters.optional_fields.cicp));+ return {};+ }+ case Media::CodecID::VP9: {+ auto const& parameters = *codec.vp9_parameters();+ TRY(encoder.encode(parameters.profile));+ TRY(encoder.encode(parameters.level));+ TRY(encoder.encode(parameters.bit_depth));+ TRY(encoder.encode(parameters.color_parameters.subsampling.x()));+ TRY(encoder.encode(parameters.color_parameters.subsampling.y()));+ TRY(encoder.encode(parameters.color_parameters.cicp));+ return {};+ }+ default:+ VERIFY_NOT_REACHED();+ }+}++template<>+ErrorOr<Media::ParsedCodec> decode(Decoder& decoder)+{+ auto codec_id = TRY(decoder.decode<Media::CodecID>());+ if (!TRY(decoder.decode<bool>()))+ return Media::ParsedCodec { codec_id };++ switch (codec_id) {+ case Media::CodecID::AAC: {+ Media::Codecs::AAC::Parameters parameters {};+ parameters.object_type_indication = TRY(decoder.decode<u8>());+ parameters.audio_object_type = TRY(decoder.decode<Optional<u32>>());+ return Media::ParsedCodec { parameters };+ }+ case Media::CodecID::H264: {+ Media::Codecs::H264::Parameters parameters;+ parameters.profile_idc = TRY(decoder.decode<u8>());+ parameters.constraint_set_flags = TRY(decoder.decode<u8>());+ parameters.level_idc = TRY(decoder.decode<u8>());+ return Media::ParsedCodec { parameters };+ }+ case Media::CodecID::H265: {+ Media::Codecs::H265::Parameters parameters;+ for (auto& flags : parameters.constraint_indicator_flags)+ flags = TRY(decoder.decode<u8>());+ parameters.profile_compatibility_flags = TRY(decoder.decode<u32>());+ parameters.profile_space = TRY(decoder.decode<u8>());+ parameters.profile_idc = TRY(decoder.decode<u8>());+ parameters.level_idc = TRY(decoder.decode<u8>());+ parameters.tier_flag = TRY(decoder.decode<bool>());+ return Media::ParsedCodec { parameters };+ }+ case Media::CodecID::AV1: {+ Media::Codecs::AV1::Parameters parameters;+ parameters.profile = TRY(decoder.decode<u8>());+ parameters.level = TRY(decoder.decode<u8>());+ parameters.tier = TRY(decoder.decode<Media::Codecs::AV1::Tier>());+ parameters.bit_depth = TRY(decoder.decode<u8>());+ parameters.optional_fields.monochrome = TRY(decoder.decode<bool>());+ auto subsampling_x = TRY(decoder.decode<bool>());+ auto subsampling_y = TRY(decoder.decode<bool>());+ parameters.optional_fields.subsampling = { subsampling_x, subsampling_y };+ parameters.optional_fields.chroma_sample_position = TRY(decoder.decode<u8>());+ parameters.optional_fields.cicp = TRY(decoder.decode<Media::CodingIndependentCodePoints>());+ return Media::ParsedCodec { parameters };+ }+ case Media::CodecID::VP9: {+ Media::Codecs::VP9::Parameters parameters;+ parameters.profile = TRY(decoder.decode<u8>());+ parameters.level = TRY(decoder.decode<u8>());+ parameters.bit_depth = TRY(decoder.decode<u8>());+ auto subsampling_x = TRY(decoder.decode<bool>());+ auto subsampling_y = TRY(decoder.decode<bool>());+ parameters.color_parameters.subsampling = { subsampling_x, subsampling_y };+ parameters.color_parameters.cicp = TRY(decoder.decode<Media::CodingIndependentCodePoints>());+ return Media::ParsedCodec { parameters };+ }+ default:+ return Error::from_string_literal("Codec parameters for a codec that has none");+ }+}+}diff --git a/Libraries/LibMediaCodecs/CodecParameters.h b/Libraries/LibMediaCodecs/CodecParameters.hindex 004535f4c00..538c6445040 100644--- a/Libraries/LibMediaCodecs/CodecParameters.h+++ b/Libraries/LibMediaCodecs/CodecParameters.h@@ -11,6 +11,7 @@#include <AK/StdLibExtras.h>#include <AK/StringView.h>#include <AK/Traits.h>+#include <LibIPC/Forward.h>#include <LibMediaCodecs/CodecID.h>#include <LibMediaCodecs/Codecs/AAC.h>#include <LibMediaCodecs/Codecs/AV1.h>@@ -223,6 +224,10 @@ MEDIACODECS_API Optional<ParsedCodec> parse_codec_parameters_string(StringView);MEDIACODECS_API ParsedCodec parsed_codec_for_coded_frame(CodedFrame const&, ParsedCodec const& container_codec);+// Keeps only what decides whether a decoder supports a format, dropping level, tier and colour, so that formats a+// decoder handles alike share one key.+MEDIACODECS_API ParsedCodec normalize_parsed_codec_for_support_keying(ParsedCodec const&);+}namespace AK {@@ -233,3 +238,13 @@ struct Traits<Media::ParsedCodec> : public DefaultTraits<Media::ParsedCodec> {};}++namespace IPC {++template<>+MEDIACODECS_API ErrorOr<void> encode(Encoder&, Media::ParsedCodec const&);++template<>+MEDIACODECS_API ErrorOr<Media::ParsedCodec> decode(Decoder&);++}diff --git a/Libraries/LibMediaCodecs/DecoderError.h b/Libraries/LibMediaCodecs/DecoderError.hindex 57b403f2957..42a335261cb 100644--- a/Libraries/LibMediaCodecs/DecoderError.h+++ b/Libraries/LibMediaCodecs/DecoderError.h@@ -36,6 +36,8 @@ enum class DecoderErrorCategory : u8 {NotImplemented,// A reader doesn't recognize the provided data.UnrecognizedFormat,+ // The decoder lost its state, so coded data must be submitted to it again starting from a keyframe.+ NeedsResubmission,};class DecoderError {@@ -113,6 +115,8 @@ constexpr StringView decoder_error_category_to_string(DecoderErrorCategory categreturn "NotImplemented"sv;case DecoderErrorCategory::UnrecognizedFormat:return "UnrecognizedFormat"sv;+ case DecoderErrorCategory::NeedsResubmission:+ return "NeedsResubmission"sv;}return "Invalid"sv;}diff --git a/Libraries/LibMedia/FFmpeg/FFmpegVideoDecoder.cpp b/Libraries/LibMediaCodecs/FFmpeg/FFmpegVideoDecoder.cppsimilarity index 100%rename from Libraries/LibMedia/FFmpeg/FFmpegVideoDecoder.cpprename to Libraries/LibMediaCodecs/FFmpeg/FFmpegVideoDecoder.cppdiff --git a/Libraries/LibMedia/FFmpeg/FFmpegVideoDecoder.h b/Libraries/LibMediaCodecs/FFmpeg/FFmpegVideoDecoder.hsimilarity index 95%rename from Libraries/LibMedia/FFmpeg/FFmpegVideoDecoder.hrename to Libraries/LibMediaCodecs/FFmpeg/FFmpegVideoDecoder.hindex aaf0f89cf12..7a1865a8d84 100644--- a/Libraries/LibMedia/FFmpeg/FFmpegVideoDecoder.h+++ b/Libraries/LibMediaCodecs/FFmpeg/FFmpegVideoDecoder.h@@ -7,10 +7,10 @@#pragma once#include <AK/HashMap.h>-#include <LibMedia/Export.h>#include <LibMediaCodecs/CodecID.h>#include <LibMediaCodecs/CodecParameters.h>#include <LibMediaCodecs/DecoderCapabilities.h>+#include <LibMediaCodecs/Export.h>#include <LibMediaCodecs/VideoDecoder.h>#include <LibMediaCodecs/VideoFramePool.h>@@ -18,7 +18,7 @@namespace Media::FFmpeg {-class MEDIA_API FFmpegVideoDecoder final : public VideoDecoder {+class MEDIACODECS_API FFmpegVideoDecoder final : public VideoDecoder {public:AK_ALLOC_WITH_KMALLOC;diff --git a/Libraries/LibMediaCodecs/Forward.h b/Libraries/LibMediaCodecs/Forward.hindex 806c13dafdd..712935e7e62 100644--- a/Libraries/LibMediaCodecs/Forward.h+++ b/Libraries/LibMediaCodecs/Forward.h@@ -11,6 +11,7 @@ namespace Media {class CodedFrame;class DecoderError;class VideoDecoder;+class VideoDecoderServerConnection;class VideoFrame;}diff --git a/Libraries/LibMediaCodecs/HardwareVideoDecoders.cpp b/Libraries/LibMediaCodecs/HardwareVideoDecoders.cppnew file mode 100644index 00000000000..c55988f0087--- /dev/null+++ b/Libraries/LibMediaCodecs/HardwareVideoDecoders.cpp@@ -0,0 +1,34 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <AK/Array.h>+#include <LibMediaCodecs/HardwareVideoDecoders.h>+#ifdef AK_OS_MACOS+# include <LibMediaCodecs/VideoToolbox/VideoToolboxVideoDecoder.h>+#endif++namespace Media {++#ifdef AK_OS_MACOS+static DecoderErrorOr<NonnullOwnPtr<VideoDecoder>> create_videotoolbox_video_decoder(CodecID codec_id, ReadonlyBytes codec_initialization_data)+{+ return NonnullOwnPtr<VideoDecoder> { TRY(VideoToolbox::VideoToolboxVideoDecoder::try_create(codec_id, codec_initialization_data)) };+}+#endif++ReadonlySpan<VideoDecoderRegistration> hardware_video_decoders()+{+#ifdef AK_OS_MACOS+ static constexpr Array decoders {+ VideoDecoderRegistration { VideoToolbox::VideoToolboxVideoDecoder::capabilities, create_videotoolbox_video_decoder },+ };+ return decoders;+#else+ return {};+#endif+}++}diff --git a/Libraries/LibMediaCodecs/HardwareVideoDecoders.h b/Libraries/LibMediaCodecs/HardwareVideoDecoders.hnew file mode 100644index 00000000000..c30b23e279f--- /dev/null+++ b/Libraries/LibMediaCodecs/HardwareVideoDecoders.h@@ -0,0 +1,17 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <AK/Span.h>+#include <LibMediaCodecs/Export.h>+#include <LibMediaCodecs/VideoDecoderRegistry.h>++namespace Media {++MEDIACODECS_API ReadonlySpan<VideoDecoderRegistration> hardware_video_decoders();++}diff --git a/Libraries/LibMediaCodecs/VideoDecoderClient.ipc b/Libraries/LibMediaCodecs/VideoDecoderClient.ipcnew file mode 100644index 00000000000..4feedef3947--- /dev/null+++ b/Libraries/LibMediaCodecs/VideoDecoderClient.ipc@@ -0,0 +1,18 @@+#include <LibCore/AnonymousBuffer.h>+#include <LibMediaCodecs/DecoderError.h>+#include <LibMediaCodecs/VideoFrameHandle.h>+#include <LibMediaCodecs/VideoSurface.h>++endpoint VideoDecoderClient+{+ // Each new buffer backing a slot is announced once, before the first frame that refers to it.+ video_frame_slot_announced(u64 decoder_id, Media::VideoFramePoolID pool_id, u32 slot_index, Core::AnonymousBuffer slot_buffer, RefPtr<Media::VideoSurface> surface) =|+ // The decoder keeps the frame's slot until the client releases it.+ frame_decoded(u64 decoder_id, u32 generation, Media::VideoFrameHandle handle) =|+ coded_frame_consumed(u64 decoder_id) =|+ decoder_failed(u64 decoder_id, u32 generation, Media::DecoderError error) =|+ decoder_drained(u64 decoder_id, u32 generation) =|+ // Every slot the decoder can output into is held by the client, so it waits for one to be released. Anything the+ // decoder reports after this means it is no longer waiting.+ decoder_waiting_for_storage(u64 decoder_id, u32 generation) =|+}diff --git a/Libraries/LibMediaCodecs/VideoDecoderServer.ipc b/Libraries/LibMediaCodecs/VideoDecoderServer.ipcnew file mode 100644index 00000000000..633ff7dca77--- /dev/null+++ b/Libraries/LibMediaCodecs/VideoDecoderServer.ipc@@ -0,0 +1,26 @@+#include <AK/ByteBuffer.h>+#include <AK/Time.h>+#include <LibCore/AnonymousBuffer.h>+#include <LibMediaCodecs/CodecID.h>+#include <LibMediaCodecs/CodecParameters.h>+#include <LibMediaCodecs/DecoderCapabilities.h>+#include <LibMediaCodecs/FrameFlags.h>+#include <LibMediaCodecs/VideoDecoder.h>+#include <LibMediaCodecs/VideoFrameHandle.h>++endpoint VideoDecoderServer+{+ decoder_capabilities(Media::ParsedCodec codec) => (Optional<Media::DecoderCapabilities> capabilities)++ // A decoder answers every frame submitted to it with coded_frame_consumed, and tags everything else it reports with+ // the generation it was in, which each flush advances.+ create_decoder(u64 decoder_id, u32 generation, Media::CodecID codec_id, ByteBuffer codec_initialization_data) =|+ destroy_decoder(u64 decoder_id) =|+ // The coded data of the frames submitted after this lives in this ring, until it is replaced again.+ replace_coded_data_ring(u64 decoder_id, Core::AnonymousBuffer ring) =|+ submit_coded_frame(u64 decoder_id, u32 generation, u64 ring_offset, u64 size, AK::Duration presentation_timestamp, AK::Duration decode_timestamp, AK::Duration duration, Media::FrameFlags flags, Optional<ByteBuffer> new_codec_configuration, Media::DecodeIntent intent, Optional<AK::Duration> output_target) =|+ signal_end_of_stream(u64 decoder_id, u32 generation) =|+ flush(u64 decoder_id, u32 generation) =|++ release_frame(Media::VideoFramePoolID pool_id, u32 slot_index) =|+}diff --git a/Libraries/LibMediaCodecs/VideoDecoderServerConnection.cpp b/Libraries/LibMediaCodecs/VideoDecoderServerConnection.cppnew file mode 100644index 00000000000..5975d3b98d2--- /dev/null+++ b/Libraries/LibMediaCodecs/VideoDecoderServerConnection.cpp@@ -0,0 +1,487 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <AK/Checked.h>+#include <AK/ConditionVariable.h>+#include <AK/Queue.h>+#include <AK/Variant.h>+#include <LibCore/EventLoop.h>+#include <LibMediaCodecs/CodedFrame.h>+#include <LibMediaCodecs/VideoDecoder.h>+#include <LibMediaCodecs/VideoDecoderServerConnection.h>+#include <LibMediaCodecs/VideoFrame.h>+#include <LibMediaCodecs/VideoFramePool.h>+#include <LibThreading/Thread.h>++namespace Media {++class VideoDecoderServerConnection::DecoderSession final : public AtomicRefCounted<DecoderSession> {+public:+ struct Submission {+ u32 generation { 0 };+ u64 ring_offset { 0 };+ u64 size { 0 };+ AK::Duration presentation_timestamp;+ AK::Duration decode_timestamp;+ AK::Duration duration;+ FrameFlags flags { FrameFlags::None };+ Optional<ByteBuffer> new_codec_configuration;+ DecodeIntent intent { DecodeIntent::Output };+ Optional<AK::Duration> output_target;+ };+ struct EndOfStream {+ u32 generation { 0 };+ };+ struct Flush {+ u32 generation { 0 };+ };+ struct ReplaceRing {+ Core::AnonymousBuffer ring;+ };+ using Command = Variant<Submission, EndOfStream, Flush, ReplaceRing>;++ static ErrorOr<NonnullRefPtr<DecoderSession>> create(ThreadSafeWeakRef<VideoDecoderServerConnection> connection, Core::EventLoop& connection_event_loop, ReadonlySpan<VideoDecoderRegistration> hosted_decoders, u64 decoder_id, u32 generation, CodecID codec_id, ByteBuffer codec_initialization_data)+ {+ auto session = TRY(adopt_nonnull_ref_or_enomem(new (nothrow) DecoderSession(move(connection), connection_event_loop, hosted_decoders, decoder_id, generation, codec_id, move(codec_initialization_data))));+ session->m_thread = TRY(Threading::Thread::try_create("Video Decoder"sv, [session]() -> intptr_t {+ session->run();+ return 0;+ }));+ session->m_thread->start();+ return session;+ }++ void enqueue(Command command)+ {+ MutexLocker locker { m_wait_state->mutex };+ if (auto const* flush = command.get_pointer<Flush>())+ m_newest_requested_generation = flush->generation;+ m_commands.enqueue(move(command));+ m_wait_state->condition.broadcast();+ }++ void exit_and_detach()+ {+ request_exit();+ m_thread->detach();+ m_thread = nullptr;+ }++ // Once this returns, the decoder will not write to any slot again.+ void exit_and_join()+ {+ request_exit();+ (void)m_thread->join();+ m_thread = nullptr;+ }++private:+ void request_exit()+ {+ MutexLocker locker { m_wait_state->mutex };+ m_exit_requested = true;+ m_wait_state->condition.broadcast();+ }++ // Shared with the decoder's callbacks, which frames held by the client can outlive the session with.+ struct WaitState : public AtomicRefCounted<WaitState> {+ Mutex mutex;+ ConditionVariable condition { mutex };+ bool storage_was_freed { false };+ bool output_arrived { false };+ };++ DecoderSession(ThreadSafeWeakRef<VideoDecoderServerConnection> connection, Core::EventLoop& connection_event_loop, ReadonlySpan<VideoDecoderRegistration> hosted_decoders, u64 decoder_id, u32 generation, CodecID codec_id, ByteBuffer codec_initialization_data)+ : m_connection(move(connection))+ , m_connection_event_loop(connection_event_loop)+ , m_hosted_decoders(hosted_decoders)+ , m_decoder_id(decoder_id)+ , m_codec_id(codec_id)+ , m_codec_initialization_data(move(codec_initialization_data))+ , m_newest_requested_generation(generation)+ , m_generation(generation)+ {+ }++ void run()+ {+ create_decoder();+ while (true) {+ Optional<Command> command;+ auto output_arrived = false;+ {+ MutexLocker locker { m_wait_state->mutex };+ while (m_commands.is_empty() && !m_wait_state->output_arrived && !m_exit_requested)+ m_wait_state->condition.wait();+ if (m_exit_requested)+ break;+ output_arrived = exchange(m_wait_state->output_arrived, false);+ if (!m_commands.is_empty())+ command = m_commands.dequeue();+ }+ // Output the decoder finished on its own goes out before the next command, which it does not depend on.+ if (output_arrived && !m_failure.has_value())+ take_outputs();+ if (command.has_value()) {+ command->visit(+ [&](Submission& submission) { decode_submission(submission); },+ [&](EndOfStream const& end_of_stream) { drain_to_end_of_stream(end_of_stream.generation); },+ [&](Flush const& flush) { apply_flush(flush.generation); },+ [&](ReplaceRing& replace_ring) { m_ring = move(replace_ring.ring); });+ }+ }+ m_decoder.clear();+ }++ void create_decoder()+ {+ auto decoder_or_error = [&] -> DecoderErrorOr<NonnullOwnPtr<VideoDecoder>> {+ for (auto const& registration : m_hosted_decoders) {+ auto decoder = registration.create(m_codec_id, m_codec_initialization_data);+ if (!decoder.is_error() || decoder.error().category() != DecoderErrorCategory::NotImplemented)+ return decoder;+ }+ return DecoderError::format(DecoderErrorCategory::NotImplemented, "The video decoder server has no decoder for codec {}", m_codec_id);+ }();+ if (decoder_or_error.is_error()) {+ fail(decoder_or_error.release_error());+ return;+ }+ m_decoder = decoder_or_error.release_value();+ m_decoder->set_storage_freed_callback([wait_state = m_wait_state] {+ MutexLocker locker { wait_state->mutex };+ wait_state->storage_was_freed = true;+ wait_state->condition.broadcast();+ });+ m_decoder->set_output_arrived_callback([wait_state = m_wait_state] {+ MutexLocker locker { wait_state->mutex };+ wait_state->output_arrived = true;+ wait_state->condition.broadcast();+ });+ }++ bool is_superseded_by_flush(u32 generation)+ {+ MutexLocker locker { m_wait_state->mutex };+ return generation != m_newest_requested_generation;+ }++ void fail(DecoderError&& error)+ {+ m_failure = move(error);+ report_failure();+ }++ void report_failure()+ {+ VERIFY(m_failure.has_value());+ m_connection.with_target([&](auto& connection) {+ connection.async_decoder_failed(m_decoder_id, m_generation, *m_failure);+ });+ }++ void acknowledge_submission()+ {+ m_connection.with_target([&](auto& connection) {+ connection.async_coded_frame_consumed(m_decoder_id);+ });+ }++ DecoderErrorOr<CodedFrame> coded_frame_for_submission(Submission& submission)+ {+ Checked<u64> end = submission.ring_offset;+ end += submission.size;+ if (!m_ring.is_valid() || end.has_overflow() || end.value() > m_ring.size())+ return DecoderError::with_description(DecoderErrorCategory::Invalid, "A coded frame lies outside its ring"sv);++ auto data = DECODER_TRY_ALLOC(FixedArray<u8>::create(m_ring.bytes().slice(submission.ring_offset, submission.size)));+ Optional<FixedArray<u8>> new_codec_configuration;+ if (submission.new_codec_configuration.has_value())+ new_codec_configuration = DECODER_TRY_ALLOC(FixedArray<u8>::create(submission.new_codec_configuration->bytes()));+ return CodedFrame { m_codec_id, submission.presentation_timestamp, submission.decode_timestamp, submission.duration, submission.flags, move(data), move(new_codec_configuration) };+ }++ void decode_submission(Submission& submission)+ {+ if (m_failure.has_value() || is_superseded_by_flush(submission.generation)) {+ acknowledge_submission();+ return;+ }++ auto coded_frame_or_error = coded_frame_for_submission(submission);+ if (coded_frame_or_error.is_error()) {+ fail(coded_frame_or_error.release_error());+ acknowledge_submission();+ return;+ }++ auto receive_result = m_decoder->receive_coded_data(coded_frame_or_error.value(), submission.intent);+ if (receive_result.is_error()) {+ fail(receive_result.release_error());+ } else {+ m_output_target = submission.output_target;+ take_outputs();+ }+ acknowledge_submission();+ }++ void drain_to_end_of_stream(u32 generation)+ {+ if (m_failure.has_value() || is_superseded_by_flush(generation))+ return;+ m_decoder->signal_end_of_stream();+ m_output_target = {};+ if (!take_outputs())+ return;+ m_connection.with_target([&](auto& connection) {+ connection.async_decoder_drained(m_decoder_id, m_generation);+ });+ }++ void apply_flush(u32 generation)+ {+ m_generation = generation;+ m_output_target = {};+ if (m_failure.has_value()) {+ report_failure();+ return;+ }+ m_decoder->flush();+ }++ // Returns whether the decoder was drained or needs more input, rather than being abandoned or failing.+ bool take_outputs()+ {+ while (true) {+ auto frame_or_error = m_decoder->take_next_output({}, m_output_target);+ if (!frame_or_error.is_error()) {+ send_frame(frame_or_error.release_value());+ continue;+ }++ auto category = frame_or_error.error().category();+ if (category == DecoderErrorCategory::NeedsMoreInput || category == DecoderErrorCategory::EndOfStream)+ return true;+ if (category != DecoderErrorCategory::TryAgain) {+ fail(frame_or_error.release_error());+ return false;+ }++ // Every slot is held by the client, so wait for it to release one. A flush or exit means the frames+ // waiting for one are not wanted anymore.+ MutexLocker locker { m_wait_state->mutex };+ // The client's consumers may hold the slots indefinitely, so the client is told not to wait for an answer.+ if (!m_wait_state->storage_was_freed && !m_exit_requested && m_newest_requested_generation == m_generation) {+ m_connection.with_target([&](auto& connection) {+ connection.async_decoder_waiting_for_storage(m_decoder_id, m_generation);+ });+ }+ while (!m_wait_state->storage_was_freed && !m_exit_requested && m_newest_requested_generation == m_generation)+ m_wait_state->condition.wait();+ m_wait_state->storage_was_freed = false;+ if (m_exit_requested || m_newest_requested_generation != m_generation)+ return false;+ }+ }++ void send_frame(NonnullRefPtr<VideoFrame> frame)+ {+ auto const* pool_slot = frame->pool_slot();+ VERIFY(pool_slot != nullptr);+ auto& ledger = pool_slot->ledger();+ auto slot_index = pool_slot->slot_index();+ auto handle = VideoFrameHandle::for_frame(*frame);++ auto& announced_buffer_ids = m_announced_buffer_ids_by_pool.ensure(ledger.id());+ auto announced_buffer_id = announced_buffer_ids.get(slot_index);+ auto needs_announcement = !announced_buffer_id.has_value() || *announced_buffer_id != pool_slot->allocated_buffer_id();+ announced_buffer_ids.set(slot_index, pool_slot->allocated_buffer_id());++ auto should_close_connection = false;+ m_connection.with_target([&](auto& connection) {+ if (needs_announcement)+ connection.async_video_frame_slot_announced(m_decoder_id, ledger.id(), slot_index, ledger.slot_buffer(slot_index), ledger.slot_surface(slot_index));+ // The frame is held before the client hears of it, so that its release cannot arrive first.+ connection.hold_frame_until_released(move(frame));+ connection.async_frame_decoded(m_decoder_id, m_generation, handle);+ should_close_connection = connection.should_close_after_decoding_frame();+ });+ if (should_close_connection)+ close_connection();+ }++ void close_connection()+ {+ m_connection_event_loop.deferred_invoke([weak_connection = m_connection] {+ // Shutting down revokes the weak reference, so it happens outside the reference's lock.+ RefPtr<VideoDecoderServerConnection> connection;+ weak_connection.with_target([&](auto& target) { connection = target; });+ if (connection)+ connection->shutdown();+ });+ }++ ThreadSafeWeakRef<VideoDecoderServerConnection> m_connection;+ Core::EventLoop& m_connection_event_loop;+ ReadonlySpan<VideoDecoderRegistration> const m_hosted_decoders;+ u64 const m_decoder_id;+ CodecID const m_codec_id;+ ByteBuffer const m_codec_initialization_data;++ // Only the connection's thread uses this.+ RefPtr<Threading::Thread> m_thread;++ NonnullRefPtr<WaitState> m_wait_state { make_ref_counted<WaitState>() };+ Queue<Command> m_commands;+ bool m_exit_requested { false };+ u32 m_newest_requested_generation { 0 };++ // Only the decoder thread uses these.+ OwnPtr<VideoDecoder> m_decoder;+ Optional<DecoderError> m_failure;+ u32 m_generation { 0 };+ // The latest submission's, which output the decoder finishes later is taken with as well.+ Optional<AK::Duration> m_output_target;+ Core::AnonymousBuffer m_ring;+ HashMap<VideoFramePoolID, HashMap<u32, u64>> m_announced_buffer_ids_by_pool;+};++VideoDecoderServerConnection::VideoDecoderServerConnection(NonnullOwnPtr<IPC::Transport> transport, ReadonlySpan<VideoDecoderRegistration> hosted_decoders)+ : IPC::ConnectionFromClient<VideoDecoderClientEndpoint, VideoDecoderServerEndpoint>(*this, move(transport), 1)+ , m_event_loop(Core::EventLoop::current())+ , m_hosted_decoders(hosted_decoders)+{+}++VideoDecoderServerConnection::~VideoDecoderServerConnection()+{+ revoke_weak_refs();+}++void VideoDecoderServerConnection::die()+{+ revoke_weak_refs();+ // The client may still be showing frames in the slots held for it, so nothing may decode into them anymore.+ for (auto& entry : m_sessions)+ entry.value->exit_and_join();+ m_sessions.clear();++ HashMap<HeldSlot, NonnullRefPtr<VideoFrame>, HeldSlotTraits> held_frames;+ {+ MutexLocker locker { m_held_frames_mutex };+ held_frames = move(m_held_frames);+ }+ held_frames.clear();++ if (on_death)+ on_death();+}++void VideoDecoderServerConnection::close_after_decoded_frame_count(u32 frame_count)+{+ m_frames_until_close.store(frame_count, AK::MemoryOrder::memory_order_relaxed);+}++Messages::VideoDecoderServer::DecoderCapabilitiesResponse VideoDecoderServerConnection::decoder_capabilities(ParsedCodec codec)+{+ if (track_type_from_codec_id(codec.codec_id()) != TrackType::Video)+ return Optional<DecoderCapabilities> {};+ for (auto const& registration : m_hosted_decoders) {+ if (auto capabilities = registration.capabilities(codec); capabilities.has_value())+ return capabilities;+ }+ return Optional<DecoderCapabilities> {};+}++void VideoDecoderServerConnection::create_decoder(u64 decoder_id, u32 generation, CodecID codec_id, ByteBuffer codec_initialization_data)+{+ if (m_sessions.contains(decoder_id)) {+ did_misbehave("create_decoder: decoder ID already exists");+ return;+ }+ auto session = DecoderSession::create(make_weak_ref(), m_event_loop, m_hosted_decoders, decoder_id, generation, codec_id, move(codec_initialization_data));+ if (session.is_error()) {+ async_decoder_failed(decoder_id, generation, DecoderError::format(DecoderErrorCategory::Memory, "Could not start a video decoder: {}", session.error()));+ return;+ }+ m_sessions.set(decoder_id, session.release_value());+}++void VideoDecoderServerConnection::destroy_decoder(u64 decoder_id)+{+ if (auto session = m_sessions.take(decoder_id); session.has_value())+ (*session)->exit_and_detach();+}++void VideoDecoderServerConnection::replace_coded_data_ring(u64 decoder_id, Core::AnonymousBuffer ring)+{+ if (auto session = m_sessions.get(decoder_id); session.has_value())+ (*session)->enqueue(DecoderSession::ReplaceRing { move(ring) });+}++void VideoDecoderServerConnection::submit_coded_frame(u64 decoder_id, u32 generation, u64 ring_offset, u64 size, AK::Duration presentation_timestamp, AK::Duration decode_timestamp, AK::Duration duration, FrameFlags flags, Optional<ByteBuffer> new_codec_configuration, DecodeIntent intent, Optional<AK::Duration> output_target)+{+ auto session = m_sessions.get(decoder_id);+ if (!session.has_value())+ return;+ (*session)->enqueue(DecoderSession::Submission {+ .generation = generation,+ .ring_offset = ring_offset,+ .size = size,+ .presentation_timestamp = presentation_timestamp,+ .decode_timestamp = decode_timestamp,+ .duration = duration,+ .flags = flags,+ .new_codec_configuration = move(new_codec_configuration),+ .intent = intent,+ .output_target = output_target,+ });+}++void VideoDecoderServerConnection::signal_end_of_stream(u64 decoder_id, u32 generation)+{+ if (auto session = m_sessions.get(decoder_id); session.has_value())+ (*session)->enqueue(DecoderSession::EndOfStream { generation });+}++void VideoDecoderServerConnection::flush(u64 decoder_id, u32 generation)+{+ if (auto session = m_sessions.get(decoder_id); session.has_value())+ (*session)->enqueue(DecoderSession::Flush { generation });+}++void VideoDecoderServerConnection::release_frame(VideoFramePoolID pool_id, u32 slot_index)+{+ // The frame is dropped outside the lock, since freeing its slot wakes the decoder thread that may be taking it.+ Optional<NonnullRefPtr<VideoFrame>> frame;+ {+ MutexLocker locker { m_held_frames_mutex };+ frame = m_held_frames.take({ pool_id, slot_index });+ }+}++void VideoDecoderServerConnection::hold_frame_until_released(NonnullRefPtr<VideoFrame> frame)+{+ auto const* pool_slot = frame->pool_slot();+ VERIFY(pool_slot != nullptr);+ HeldSlot slot { pool_slot->ledger().id(), pool_slot->slot_index() };+ MutexLocker locker { m_held_frames_mutex };+ m_held_frames.set(slot, move(frame));+}++bool VideoDecoderServerConnection::should_close_after_decoding_frame()+{+ auto frames_until_close = m_frames_until_close.load(AK::MemoryOrder::memory_order_relaxed);+ while (true) {+ if (frames_until_close == 0)+ return false;+ if (m_frames_until_close.compare_exchange_strong(frames_until_close, frames_until_close - 1, AK::MemoryOrder::memory_order_relaxed))+ break;+ }+ return frames_until_close == 1;+}++}diff --git a/Libraries/LibMediaCodecs/VideoDecoderServerConnection.h b/Libraries/LibMediaCodecs/VideoDecoderServerConnection.hnew file mode 100644index 00000000000..39da37bce11--- /dev/null+++ b/Libraries/LibMediaCodecs/VideoDecoderServerConnection.h@@ -0,0 +1,81 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <AK/Atomic.h>+#include <AK/Function.h>+#include <AK/HashMap.h>+#include <AK/Mutex.h>+#include <AK/NonnullRefPtr.h>+#include <AK/ThreadSafeWeakable.h>+#include <LibIPC/ConnectionFromClient.h>+#include <LibMediaCodecs/Export.h>+#include <LibMediaCodecs/VideoDecoderClientEndpoint.h>+#include <LibMediaCodecs/VideoDecoderRegistry.h>+#include <LibMediaCodecs/VideoDecoderServerEndpoint.h>+#include <LibMediaCodecs/VideoFrameHandle.h>++namespace Media {++// The decoding end of the connection between a VideoDecoderServer and its client, hosting the decoders it is given in+// priority order. Each decoder the client creates runs on a thread of its own, reading the coded frames submitted to+// it out of a shared-memory ring. A decoded frame's slot stays held here until the client releases it.+class MEDIACODECS_API VideoDecoderServerConnection final+ : public IPC::ConnectionFromClient<VideoDecoderClientEndpoint, VideoDecoderServerEndpoint>+ , public ThreadSafeWeakable<VideoDecoderServerConnection> {+ C_OBJECT(VideoDecoderServerConnection);++public:+ virtual ~VideoDecoderServerConnection() override;++ Function<void()> on_death;++ // For tests of the client's recovery: the connection closes once its decoders have decoded this many frames, or+ // never if the count is zero.+ void close_after_decoded_frame_count(u32);++private:+ class DecoderSession;++ VideoDecoderServerConnection(NonnullOwnPtr<IPC::Transport>, ReadonlySpan<VideoDecoderRegistration> hosted_decoders);++ virtual void die() override;++ virtual Messages::VideoDecoderServer::DecoderCapabilitiesResponse decoder_capabilities(ParsedCodec codec) override;+ virtual void create_decoder(u64 decoder_id, u32 generation, CodecID codec_id, ByteBuffer codec_initialization_data) override;+ virtual void destroy_decoder(u64 decoder_id) override;+ virtual void replace_coded_data_ring(u64 decoder_id, Core::AnonymousBuffer ring) override;+ virtual void submit_coded_frame(u64 decoder_id, u32 generation, u64 ring_offset, u64 size, AK::Duration presentation_timestamp, AK::Duration decode_timestamp, AK::Duration duration, FrameFlags flags, Optional<ByteBuffer> new_codec_configuration, DecodeIntent intent, Optional<AK::Duration> output_target) override;+ virtual void signal_end_of_stream(u64 decoder_id, u32 generation) override;+ virtual void flush(u64 decoder_id, u32 generation) override;+ virtual void release_frame(VideoFramePoolID pool_id, u32 slot_index) override;++ // Called from the decoder threads.+ void hold_frame_until_released(NonnullRefPtr<VideoFrame>);+ bool should_close_after_decoding_frame();++ struct HeldSlot {+ VideoFramePoolID pool_id;+ u32 slot_index { 0 };++ bool operator==(HeldSlot const&) const = default;+ };+ struct HeldSlotTraits : public DefaultTraits<HeldSlot> {+ static unsigned hash(HeldSlot const& slot) { return pair_int_hash(u64_hash(slot.pool_id.value()), slot.slot_index); }+ };++ Core::EventLoop& m_event_loop;+ ReadonlySpan<VideoDecoderRegistration> const m_hosted_decoders;+ HashMap<u64, NonnullRefPtr<DecoderSession>> m_sessions;++ Mutex m_held_frames_mutex;+ HashMap<HeldSlot, NonnullRefPtr<VideoFrame>, HeldSlotTraits> m_held_frames;++ Atomic<u32> m_frames_until_close { 0 };+};++}diff --git a/Libraries/LibMediaCodecs/VideoFramePool.cpp b/Libraries/LibMediaCodecs/VideoFramePool.cppindex 022a4fe850f..9b5502b89e6 100644--- a/Libraries/LibMediaCodecs/VideoFramePool.cpp+++ b/Libraries/LibMediaCodecs/VideoFramePool.cpp@@ -147,13 +147,18 @@ ErrorOr<NonnullRefPtr<PooledVideoFrameSlot>> VideoFramePool::try_adopt_acquired_return try_adopt_slot(acquired_slot.index, acquired_slot.slot_acquisition_id, acquired_slot.allocated_buffer_id);}-void VideoFrameEntryLedger::publish_acquisition_while_locked(Slot& slot)+void VideoFrameEntryLedger::begin_hold_while_locked(Slot& slot, u64 slot_acquisition_id){m_shed_storage_on_release = false;if (slot.surface != nullptr)slot.surface_use = slot.surface->begin_use();slot.hold_count = 1;- slot.last_slot_acquisition_id++;+ slot.last_slot_acquisition_id = slot_acquisition_id;+}++void VideoFrameEntryLedger::publish_acquisition_while_locked(Slot& slot)+{+ begin_hold_while_locked(slot, slot.last_slot_acquisition_id + 1);slot_header(slot.buffer).slot_acquisition_id.store(slot.last_slot_acquisition_id);AK::atomic_thread_fence(AK::MemoryOrder::memory_order_seq_cst);}@@ -245,6 +250,7 @@ void VideoFrameEntryLedger::release_hold(u32 slot_index)if (m_slot_freed_callback)m_slot_freed_callback();+ did_free_slot(slot_index);}Core::AnonymousBuffer VideoFrameEntryLedger::slot_buffer(u32 slot_index) const@@ -333,6 +339,66 @@ ErrorOr<NonnullRefPtr<PooledVideoFrameSlot>> VideoFrameSurfacePool::try_adopt_acreturn try_adopt_slot(acquired_slot.index, acquired_slot.slot_acquisition_id, acquired_slot.allocated_buffer_id);}+ErrorOr<NonnullRefPtr<VideoFrameRelayPool>> VideoFrameRelayPool::create(SlotReleasedCallback slot_released_callback)+{+ return adopt_nonnull_ref_or_enomem(new (nothrow) VideoFrameRelayPool(move(slot_released_callback)));+}++VideoFrameRelayPool::VideoFrameRelayPool(SlotReleasedCallback slot_released_callback)+ : m_slot_released_callback(move(slot_released_callback))+{+}++ErrorOr<void> VideoFrameRelayPool::set_slot_storage(u32 slot_index, Core::AnonymousBuffer buffer, RefPtr<VideoSurface> surface)+{+ if (slot_index >= MAX_SLOT_COUNT)+ return Error::from_string_literal("Relayed video frame slot index is out of range");+ if (!buffer.is_valid() || buffer.size() < slot_data_offset())+ return Error::from_string_literal("Relayed video frame slot buffer is too small");++ MutexLocker locker { m_mutex };+ while (m_slots.size() <= slot_index)+ TRY(m_slots.try_append({}));+ auto& slot = m_slots[slot_index];+ if (slot.hold_count != 0)+ return Error::from_string_literal("Relayed video frame slot was replaced while held");+ slot.buffer = move(buffer);+ slot.surface = move(surface);+ slot.allocated_buffer_id++;+ return {};+}++ErrorOr<NonnullRefPtr<PooledVideoFrameSlot>> VideoFrameRelayPool::try_adopt_published_slot(u32 slot_index, u64 slot_acquisition_id)+{+ u64 allocated_buffer_id = 0;+ {+ MutexLocker locker { m_mutex };+ if (slot_index >= m_slots.size())+ return Error::from_string_literal("Relayed video frame refers to a slot that was never announced");+ auto& slot = m_slots[slot_index];+ if (!slot.buffer.is_valid())+ return Error::from_string_literal("Relayed video frame refers to a slot that has no buffer");+ if (slot.hold_count != 0)+ return Error::from_string_literal("Relayed video frame refers to a slot that is still held");+ if (slot_header(slot.buffer).slot_acquisition_id.load(AK::MemoryOrder::memory_order_acquire) != slot_acquisition_id)+ return Error::from_string_literal("Relayed video frame does not match its slot's published acquisition");+ begin_hold_while_locked(slot, slot_acquisition_id);+ allocated_buffer_id = slot.allocated_buffer_id;+ }+ return try_adopt_slot(slot_index, slot_acquisition_id, allocated_buffer_id);+}++void VideoFrameRelayPool::drop_slot_storage_while_locked(Slot& slot)+{+ slot.buffer = {};+ slot.surface = nullptr;+}++void VideoFrameRelayPool::did_free_slot(u32 slot_index)+{+ m_slot_released_callback(slot_index);+}+ResolvedVideoFrameSlot::ResolvedVideoFrameSlot(Core::AnonymousBuffer slot_buffer, RefPtr<VideoSurface> surface, VideoFramePoolID pool_id, u32 slot_index, u64 slot_acquisition_id, Function<void()> on_release): m_slot_buffer(move(slot_buffer)), m_surface(move(surface))diff --git a/Libraries/LibMediaCodecs/VideoFramePool.h b/Libraries/LibMediaCodecs/VideoFramePool.hindex c61e2b5c587..9d77c537989 100644--- a/Libraries/LibMediaCodecs/VideoFramePool.h+++ b/Libraries/LibMediaCodecs/VideoFramePool.h@@ -69,9 +69,12 @@ protected:Optional<u32> try_grow_while_locked();virtual void drop_slot_storage_while_locked(Slot&) = 0;+ // Runs after the slot freed callback, from the same thread.+ virtual void did_free_slot(u32) { }u32 held_slot_count_while_locked() const;void publish_acquisition_while_locked(Slot&);+ void begin_hold_while_locked(Slot&, u64 slot_acquisition_id);mutable Mutex m_mutex;Vector<Slot> m_slots;@@ -142,6 +145,30 @@ private:HashMap<u32, u32> m_slot_indices_by_surface_id;};+// Mirrors a pool in another process, whose frames this process holds and lends onward as its own. The other process+// publishes each acquisition in the slot's buffer and keeps the slot until this pool releases it, so this pool tracks+// holds without publishing anything.+class MEDIACODECS_API VideoFrameRelayPool final : public VideoFrameEntryLedger {+public:+ static constexpr u32 MAX_SLOT_COUNT = 16;++ using SlotReleasedCallback = Function<void(u32 slot_index)>;+ static ErrorOr<NonnullRefPtr<VideoFrameRelayPool>> create(SlotReleasedCallback);++ // Takes a new buffer for a slot, as the other process announces it. Fails if the slot is still held.+ ErrorOr<void> set_slot_storage(u32 slot_index, Core::AnonymousBuffer, RefPtr<VideoSurface>);+ // Holds a slot for an acquisition the other process published in the slot's buffer.+ ErrorOr<NonnullRefPtr<PooledVideoFrameSlot>> try_adopt_published_slot(u32 slot_index, u64 slot_acquisition_id);++private:+ explicit VideoFrameRelayPool(SlotReleasedCallback);++ virtual void drop_slot_storage_while_locked(Slot&) override;+ virtual void did_free_slot(u32 slot_index) override;++ SlotReleasedCallback m_slot_released_callback;+};+// A strong reference to a slot in a frame pool to be used within a single process.class PooledVideoFrameSlot : public AtomicRefCounted<PooledVideoFrameSlot> {public:diff --git a/Libraries/LibMedia/VideoToolbox/VideoToolboxVideoDecoder.h b/Libraries/LibMediaCodecs/VideoToolbox/VideoToolboxVideoDecoder.hsimilarity index 97%rename from Libraries/LibMedia/VideoToolbox/VideoToolboxVideoDecoder.hrename to Libraries/LibMediaCodecs/VideoToolbox/VideoToolboxVideoDecoder.hindex f551c2e3b2a..90921f85af7 100644--- a/Libraries/LibMedia/VideoToolbox/VideoToolboxVideoDecoder.h+++ b/Libraries/LibMediaCodecs/VideoToolbox/VideoToolboxVideoDecoder.h@@ -12,11 +12,11 @@#include <AK/NonnullOwnPtr.h>#include <AK/Vector.h>#include <AK/kmalloc.h>-#include <LibMedia/Export.h>#include <LibMediaCodecs/CodecID.h>#include <LibMediaCodecs/CodecParameters.h>#include <LibMediaCodecs/Codecs/VP9.h>#include <LibMediaCodecs/DecoderCapabilities.h>+#include <LibMediaCodecs/Export.h>#include <LibMediaCodecs/Subsampling.h>#include <LibMediaCodecs/VideoDecoder.h>#include <LibMediaCodecs/VideoFramePool.h>@@ -29,7 +29,7 @@ struct FormatState;// Decodes on the platform's media engine, which allocates the surfaces it decodes into and hands them back rather// than filling ones we provide.-class MEDIA_API VideoToolboxVideoDecoder final : public VideoDecoder {+class MEDIACODECS_API VideoToolboxVideoDecoder final : public VideoDecoder {public:AK_ALLOC_WITH_KMALLOC;diff --git a/Libraries/LibMedia/VideoToolbox/VideoToolboxVideoDecoder.mm b/Libraries/LibMediaCodecs/VideoToolbox/VideoToolboxVideoDecoder.mmsimilarity index 96%rename from Libraries/LibMedia/VideoToolbox/VideoToolboxVideoDecoder.mmrename to Libraries/LibMediaCodecs/VideoToolbox/VideoToolboxVideoDecoder.mmindex 477f5149b09..b46bdace98b 100644--- a/Libraries/LibMedia/VideoToolbox/VideoToolboxVideoDecoder.mm+++ b/Libraries/LibMediaCodecs/VideoToolbox/VideoToolboxVideoDecoder.mm@@ -7,7 +7,6 @@#include <AK/ByteBuffer.h>#include <AK/HashMap.h>#include <AK/NeverDestroyed.h>-#include <LibMedia/VideoToolbox/VideoToolboxVideoDecoder.h>#include <LibMediaCodecs/Codecs/AV1.h>#include <LibMediaCodecs/Codecs/H264.h>#include <LibMediaCodecs/Codecs/H265.h>@@ -15,6 +14,7 @@#include <LibMediaCodecs/Codecs/VP9.h>#include <LibMediaCodecs/CodedFrame.h>#include <LibMediaCodecs/VideoFrame.h>+#include <LibMediaCodecs/VideoToolbox/VideoToolboxVideoDecoder.h>#include <CoreMedia/CoreMedia.h>#include <CoreVideo/CoreVideo.h>@@ -236,43 +236,6 @@ bool session_uses_hardware_decoder(VTDecompressionSessionRef session)return uses_hardware.ref() != nullptr && CFBooleanGetValue(uses_hardware.ref());}-ParsedCodec normalize_parsed_codec_for_support_keying(ParsedCodec const& codec)-{- switch (codec.codec_id()) {- case CodecID::VP9: {- auto parameters = codec.vp9_parameters().value_or({ .profile = 0, .level = 0, .bit_depth = 8, .color_parameters = {} });- parameters.level = 0;- parameters.color_parameters.cicp = {};- return ParsedCodec { parameters };- }- case CodecID::AV1: {- auto parameters = codec.av1_parameters().value_or({ .profile = 0, .level = 0, .tier = Codecs::AV1::Tier::Main, .bit_depth = 8, .optional_fields = {} });- parameters.level = 0;- parameters.tier = Codecs::AV1::Tier::Main;- parameters.optional_fields.cicp = {};- return ParsedCodec { parameters };- }- case CodecID::H264: {- Optional<Codecs::H264::Profile> profile = Codecs::H264::Profile::Main;- if (auto parameters = codec.h264_parameters(); parameters.has_value())- profile = parameters->profile();- if (!profile.has_value())- return codec;- return ParsedCodec { Codecs::H264::canonical_parameters_for_profile(*profile) };- }- case CodecID::H265: {- Optional<Codecs::H265::Profile> profile = Codecs::H265::Profile::Main;- if (auto parameters = codec.h265_parameters(); parameters.has_value())- profile = parameters->profile();- if (!profile.has_value())- return codec;- return ParsedCodec { Codecs::H265::canonical_parameters_for_profile(*profile) };- }- default:- return codec;- }-}-}struct FormatState {diff --git a/Libraries/LibWebView/Application.cpp b/Libraries/LibWebView/Application.cppindex cf3596f8abe..3c1fd8aa461 100644--- a/Libraries/LibWebView/Application.cpp+++ b/Libraries/LibWebView/Application.cpp@@ -328,6 +328,7 @@ ErrorOr<void> Application::initialize(Main::Arguments const& arguments)bool disable_http_disk_cache = false;bool disable_content_blocker = false;bool disable_sandbox = false;+ bool force_video_decoder_server = false;Vector<ByteString> content_blocker_list_paths;Optional<StringView> resource_substitution_map_path;bool enable_autoplay = false;@@ -435,6 +436,7 @@ ErrorOr<void> Application::initialize(Main::Arguments const& arguments)args_parser.add_option(maximum_site_request_servers, "How many RequestServers a session may have for the sites it visits, 0 to share one", "max-site-request-servers", 0, "count");args_parser.add_option(disable_content_blocker, "Disable content blocker", "disable-content-blocker");args_parser.add_option(disable_sandbox, "Disable helper process sandboxing", "disable-sandbox");+ args_parser.add_option(force_video_decoder_server, "Also decode video that has no hardware decoder in the VideoDecoderServer", "force-video-decoder-server");args_parser.add_option(Core::ArgsParser::Option {.argument_mode = Core::ArgsParser::OptionArgumentMode::Required,.help_string = "Path to a content blocker list. May be specified multiple times.",@@ -638,6 +640,7 @@ ErrorOr<void> Application::initialize(Main::Arguments const& arguments).devtools_port = devtools_port,.enable_content_blocker = disable_content_blocker ? EnableContentBlocker::No : EnableContentBlocker::Yes,.disable_sandbox = disable_sandbox ? DisableSandbox::Yes : DisableSandbox::No,+ .force_video_decoder_server = force_video_decoder_server ? ForceVideoDecoderServer::Yes : ForceVideoDecoderServer::No,};rebuild_content_blocker_list_paths();@@ -2150,6 +2153,9 @@ void Application::process_did_exit(Process&& process, Optional<int>)// The connection's holder launches a new AudioServer when it next connects a client; the streams of the old// one report their loss and reopen.break;+ case ProcessType::VideoDecoderServer:+ // The MediaServer it served asks for a new one once its decoders notice the loss.+ break;case ProcessType::RequestServer:if (auto client = process.client<Requests::RequestControlClient>()) {dbgln_if(WEBVIEW_PROCESS_DEBUG, "Restart request server");diff --git a/Libraries/LibWebView/CMakeLists.txt b/Libraries/LibWebView/CMakeLists.txtindex 7de5f2c6f3e..f99e99b0a94 100644--- a/Libraries/LibWebView/CMakeLists.txt+++ b/Libraries/LibWebView/CMakeLists.txt@@ -66,6 +66,7 @@ set(SOURCESURL.cppUserAgent.cppUtilities.cpp+ VideoDecoderServerControlClient.cppViewImplementation.cppWebContentClient.cppWebContentPage.cpp@@ -103,6 +104,8 @@ set(GENERATED_SOURCES../../Services/AudioServer/AudioServerControlEndpoint.h../../Services/RequestServer/RequestClientEndpoint.h../../Services/RequestServer/RequestServerEndpoint.h+ ../../Services/VideoDecoderServer/VideoDecoderServerControlClientEndpoint.h+ ../../Services/VideoDecoderServer/VideoDecoderServerControlEndpoint.hUIProcessClientEndpoint.hUIProcessServerEndpoint.h)diff --git a/Libraries/LibWebView/CrashReportStore.cpp b/Libraries/LibWebView/CrashReportStore.cppindex 23cbc995e26..2be4180e5be 100644--- a/Libraries/LibWebView/CrashReportStore.cpp+++ b/Libraries/LibWebView/CrashReportStore.cpp@@ -66,7 +66,7 @@ bool CrashReportStore::is_saved_report_name(StringView name)suffix = name.substring_view(timestamp_pattern.length());}for (auto type : { ProcessType::Browser, ProcessType::WebContent, ProcessType::WebWorker,- ProcessType::RequestServer, ProcessType::ImageDecoder, ProcessType::MediaServer, ProcessType::AudioServer, ProcessType::Compositor,+ ProcessType::RequestServer, ProcessType::ImageDecoder, ProcessType::MediaServer, ProcessType::AudioServer, ProcessType::VideoDecoderServer, ProcessType::Compositor,ProcessType::WasmCompiler }) {auto prefix = ByteString::formatted("{}-", process_name_from_type(type));if (!suffix.starts_with(prefix) || suffix.length() != prefix.length() + 10)diff --git a/Libraries/LibWebView/Forward.h b/Libraries/LibWebView/Forward.hindex 43dff122459..3b6890f0f53 100644--- a/Libraries/LibWebView/Forward.h+++ b/Libraries/LibWebView/Forward.h@@ -58,6 +58,7 @@ class SettingsUI;class SpellChecker;class StorageJar;class TraversableSessionHistory;+class VideoDecoderServerControlClient;class ViewImplementation;class WebContentClient;class WebContentTestClient;diff --git a/Libraries/LibWebView/HelperProcess.cpp b/Libraries/LibWebView/HelperProcess.cppindex b65a90c4bfd..4d1e62f5d66 100644--- a/Libraries/LibWebView/HelperProcess.cpp+++ b/Libraries/LibWebView/HelperProcess.cpp@@ -19,6 +19,7 @@#include <LibWebView/HelperProcess.h>#include <LibWebView/RequestServerManager.h>#include <LibWebView/Utilities.h>+#include <LibWebView/VideoDecoderServerControlClient.h>#if defined(AK_OS_MACOS)# include <notify.h>@@ -461,6 +462,23 @@ ErrorOr<NonnullRefPtr<MediaClient::Client>> launch_media_server_process()return launch_server_process<MediaClient::Client>("MediaServer"sv, arguments);}+ErrorOr<NonnullRefPtr<VideoDecoderServerControlClient>> launch_video_decoder_server_process()+{+ auto const& browser_options = WebView::Application::browser_options();++ Vector<ByteString> arguments;+ if (browser_options.disable_sandbox == DisableSandbox::Yes)+ arguments.append("--disable-sandbox"sv);+ if (browser_options.force_video_decoder_server == ForceVideoDecoderServer::Yes)+ arguments.append("--host-software-decoders"sv);+ if (auto server = mach_server_name(); server.has_value()) {+ arguments.append("--mach-server-name"sv);+ arguments.append(server.value());+ }++ return launch_server_process<VideoDecoderServerControlClient>("VideoDecoderServer"sv, arguments);+}+#if defined(HAVE_WASM_COMPILER_SERVICE)ErrorOr<NonnullRefPtr<WasmCompilerClient::Client>> launch_wasm_compiler_process(){@@ -654,11 +672,26 @@ ErrorOr<IPC::TransportHandle> connect_new_audio_server_client(RefPtr<AudioServerreturn response->take_handle().release_value();}+static ErrorOr<IPC::TransportHandle> connect_new_video_decoder_server_client(RefPtr<VideoDecoderServerControlClient>& controller)+{+ if (!controller || !controller->is_open())+ controller = TRY(launch_video_decoder_server_process());++ auto response = controller->send_sync_but_allow_failure<Messages::VideoDecoderServerControl::ConnectNewClient>();+ if (!response || !response->handle().has_value())+ return Error::from_string_literal("Failed to connect to VideoDecoderServer");+ return response->take_handle().release_value();+}+ErrorOr<MediaServerClientConnection> connect_new_media_server_client(RefPtr<MediaClient::Client>& controller, Function<ErrorOr<IPC::TransportHandle>()> connect_audio_server){if (!controller || !controller->is_open()) {controller = TRY(launch_media_server_process());controller->on_request_audio_server_connection = move(connect_audio_server);+ // Each MediaServer has a VideoDecoderServer of its own, which lives as long as the controller holding it.+ controller->on_request_video_decoder_server_connection = [video_decoder_server = RefPtr<VideoDecoderServerControlClient> {}](auto answer) mutable {+ answer(connect_new_video_decoder_server_client(video_decoder_server));+ };}auto response = controller->send_sync_but_allow_failure<Messages::MediaServer::ConnectNewClient>();diff --git a/Libraries/LibWebView/HelperProcess.h b/Libraries/LibWebView/HelperProcess.hindex 9cd54d85772..35667aa553a 100644--- a/Libraries/LibWebView/HelperProcess.h+++ b/Libraries/LibWebView/HelperProcess.h@@ -30,6 +30,7 @@ WEBVIEW_API ErrorOr<NonnullRefPtr<WebView::WebContentClient>> launch_web_contentWEBVIEW_API ErrorOr<NonnullRefPtr<MediaClient::Client>> launch_media_server_process();WEBVIEW_API ErrorOr<NonnullRefPtr<AudioServerControlClient>> launch_audio_server_process();+WEBVIEW_API ErrorOr<NonnullRefPtr<VideoDecoderServerControlClient>> launch_video_decoder_server_process();WEBVIEW_API ErrorOr<NonnullRefPtr<WebView::CompositorClient>> launch_compositor_process();WEBVIEW_API ErrorOr<NonnullRefPtr<WebView::WebWorkerClient>> launch_web_worker_process(Web::HTML::AgentType, IsPrivate, Web::HTML::WorkerAgentId);WEBVIEW_API ErrorOr<NonnullRefPtr<Requests::RequestControlClient>> launch_request_server_process(ByteString const& cache_path, Optional<Utf16String> const& site, HTTPDiskCacheMode);@@ -66,7 +67,8 @@ WEBVIEW_API ErrorOr<void> ensure_audio_server_is_running(RefPtr<AudioServerContr// Likewise, and connects a new client to it as a member of the given tab's mix.WEBVIEW_API ErrorOr<IPC::TransportHandle> connect_new_audio_server_client(RefPtr<AudioServerControlClient>& controller, u64 audio_tab_id);// Launches the MediaServer for a renderer if it has none, keeping its controller connection in the given slot, and-// connects a new client to it. The server gets its AudioServer connection through connect_audio_server.+// connects a new client to it. The server gets its AudioServer connection through connect_audio_server, and its+// VideoDecoderServer from the Browser, which launches one for it on request.struct MediaServerClientConnection {IPC::TransportHandle handle;int client_id { -1 };diff --git a/Libraries/LibWebView/Options.h b/Libraries/LibWebView/Options.hindex 83d4acf9c58..ae8bcaff180 100644--- a/Libraries/LibWebView/Options.h+++ b/Libraries/LibWebView/Options.h@@ -76,6 +76,11 @@ enum class DisableSandbox {Yes,};+enum class ForceVideoDecoderServer {+ No,+ Yes,+};+enum class ProfileTool {Callgrind,CPU,@@ -103,6 +108,7 @@ struct BrowserOptions {Optional<u16> devtools_port;EnableContentBlocker enable_content_blocker { EnableContentBlocker::Yes };DisableSandbox disable_sandbox { DisableSandbox::No };+ ForceVideoDecoderServer force_video_decoder_server { ForceVideoDecoderServer::No };Vector<ByteString> content_blocker_list_paths {};};diff --git a/Libraries/LibWebView/ProcessManager.cpp b/Libraries/LibWebView/ProcessManager.cppindex bf6a1ae941b..d862bd6407c 100644--- a/Libraries/LibWebView/ProcessManager.cpp+++ b/Libraries/LibWebView/ProcessManager.cpp@@ -30,6 +30,8 @@ ProcessType process_type_from_name(StringView name)return ProcessType::MediaServer;if (name == "AudioServer"sv)return ProcessType::AudioServer;+ if (name == "VideoDecoderServer"sv)+ return ProcessType::VideoDecoderServer;if (name == "WasmCompiler"sv)return ProcessType::WasmCompiler;@@ -56,6 +58,8 @@ StringView process_name_from_type(ProcessType type)return "MediaServer"sv;case ProcessType::AudioServer:return "AudioServer"sv;+ case ProcessType::VideoDecoderServer:+ return "VideoDecoderServer"sv;case ProcessType::WasmCompiler:return "WasmCompiler"sv;}diff --git a/Libraries/LibWebView/ProcessType.h b/Libraries/LibWebView/ProcessType.hindex 05b89914c27..a6ce6b70ad9 100644--- a/Libraries/LibWebView/ProcessType.h+++ b/Libraries/LibWebView/ProcessType.h@@ -19,6 +19,7 @@ enum class ProcessType : u8 {ImageDecoder,MediaServer,AudioServer,+ VideoDecoderServer,WasmCompiler,};diff --git a/Libraries/LibWebView/VideoDecoderServerControlClient.cpp b/Libraries/LibWebView/VideoDecoderServerControlClient.cppnew file mode 100644index 00000000000..a20d4bc98c9--- /dev/null+++ b/Libraries/LibWebView/VideoDecoderServerControlClient.cpp@@ -0,0 +1,24 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <LibWebView/VideoDecoderServerControlClient.h>++namespace WebView {++VideoDecoderServerControlClient::VideoDecoderServerControlClient(NonnullOwnPtr<IPC::Transport> transport)+ : IPC::ConnectionToServer<VideoDecoderServerControlClientEndpoint, VideoDecoderServerControlEndpoint>(*this, move(transport))+{+}++VideoDecoderServerControlClient::~VideoDecoderServerControlClient() = default;++void VideoDecoderServerControlClient::die()+{+ // The holder launches a new VideoDecoderServer when its MediaServer next asks for one; the MediaServer hears about+ // the loss from its own connection.+}++}diff --git a/Libraries/LibWebView/VideoDecoderServerControlClient.h b/Libraries/LibWebView/VideoDecoderServerControlClient.hnew file mode 100644index 00000000000..eda3eb0d37f--- /dev/null+++ b/Libraries/LibWebView/VideoDecoderServerControlClient.h@@ -0,0 +1,30 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <LibIPC/ConnectionToServer.h>+#include <LibWebView/Export.h>+#include <VideoDecoderServer/VideoDecoderServerControlClientEndpoint.h>+#include <VideoDecoderServer/VideoDecoderServerControlEndpoint.h>++namespace WebView {++// The control plane of a MediaServer's VideoDecoderServer, spoken only by the Browser, which launched it.+class WEBVIEW_API VideoDecoderServerControlClient final+ : public IPC::ConnectionToServer<VideoDecoderServerControlClientEndpoint, VideoDecoderServerControlEndpoint>+ , public VideoDecoderServerControlClientEndpoint {+ C_OBJECT_ABSTRACT(VideoDecoderServerControlClient);++public:+ explicit VideoDecoderServerControlClient(NonnullOwnPtr<IPC::Transport>);+ virtual ~VideoDecoderServerControlClient() override;++private:+ virtual void die() override;+};++}diff --git a/Meta/CMake/ladybird_helper_processes.cmake b/Meta/CMake/ladybird_helper_processes.cmakeindex 608e527f7eb..89889f098df 100644--- a/Meta/CMake/ladybird_helper_processes.cmake+++ b/Meta/CMake/ladybird_helper_processes.cmake@@ -4,6 +4,7 @@ set(ladybird_helper_processesImageDecoderMediaServerRequestServer+ VideoDecoderServerWebContentWebWorker)diff --git a/Meta/Generators/generate-build-information.py b/Meta/Generators/generate-build-information.pyindex ba680712a7b..d2a0aa71b3d 100755--- a/Meta/Generators/generate-build-information.py+++ b/Meta/Generators/generate-build-information.py@@ -18,6 +18,7 @@ HELPERS = ("ImageDecoder","MediaServer","RequestServer",+ "VideoDecoderServer","WasmCompiler","WebContent","WebWorker",diff --git a/Services/CMakeLists.txt b/Services/CMakeLists.txtindex a99171ba056..14d5fdaf2e7 100644--- a/Services/CMakeLists.txt+++ b/Services/CMakeLists.txt@@ -6,6 +6,7 @@ if (APPLE)add_subdirectory(ProcessReaper)endif()add_subdirectory(RequestServer)+add_subdirectory(VideoDecoderServer)if (ENABLE_CRANELIFT_JIT)add_subdirectory(WasmCompiler)endif()diff --git a/Services/MediaServer/ConnectionFromClient.cpp b/Services/MediaServer/ConnectionFromClient.cppindex 11cd66f0bed..2fbd71c3b62 100644--- a/Services/MediaServer/ConnectionFromClient.cpp+++ b/Services/MediaServer/ConnectionFromClient.cpp@@ -58,6 +58,32 @@ ErrorOr<NonnullOwnPtr<IPC::Transport>> ConnectionFromClient::request_audio_servereturn response->take_handle()->create_transport();}+void ConnectionFromClient::request_video_decoder_server_transport(VideoDecoderServerTransportCallback callback)+{+ VERIFY(m_role == Role::Controller);+ auto request_id = m_next_video_decoder_server_transport_request_id++;+ m_video_decoder_server_transport_requests.set(request_id, move(callback));+ async_request_video_decoder_server_connection(request_id);+}++void ConnectionFromClient::video_decoder_server_connection_ready(u64 request_id, Optional<IPC::TransportHandle> handle)+{+ if (m_role != Role::Controller) {+ did_misbehave("Only the controller may connect a video decoder server");+ return;+ }+ auto callback = m_video_decoder_server_transport_requests.take(request_id);+ if (!callback.has_value()) {+ did_misbehave("A video decoder server connection answered no request");+ return;+ }+ if (!handle.has_value()) {+ (*callback)(Error::from_string_literal("The Browser did not connect a video decoder server"));+ return;+ }+ (*callback)(handle->create_transport());+}+ErrorOr<ConnectionFromClient::RendererConnection> ConnectionFromClient::create_renderer_connection(){auto paired_transports = TRY(IPC::Transport::create_paired());diff --git a/Services/MediaServer/ConnectionFromClient.h b/Services/MediaServer/ConnectionFromClient.hindex 5d9a5454cc9..4b986b330af 100644--- a/Services/MediaServer/ConnectionFromClient.h+++ b/Services/MediaServer/ConnectionFromClient.h@@ -39,9 +39,14 @@ public:// Controller only: asks the Browser for this server's connection to the AudioServer.ErrorOr<NonnullOwnPtr<IPC::Transport>> request_audio_server_transport();+ // Controller only: asks the Browser for this server's connection to its VideoDecoderServer. The Browser answers+ // once it has one, and the callback runs on this thread when the answer arrives.+ using VideoDecoderServerTransportCallback = Function<void(ErrorOr<NonnullOwnPtr<IPC::Transport>>)>;+ void request_video_decoder_server_transport(VideoDecoderServerTransportCallback);private:virtual Messages::MediaServer::ConnectNewClientResponse connect_new_client() override;+ virtual void video_decoder_server_connection_ready(u64 request_id, Optional<IPC::TransportHandle> handle) override;virtual void connect_video_presentation_channel(int client_id, IPC::TransportHandle handle) override;@@ -100,6 +105,9 @@ private:Role m_role { Role::Renderer };+ HashMap<u64, VideoDecoderServerTransportCallback> m_video_decoder_server_transport_requests;+ u64 m_next_video_decoder_server_transport_request_id { 1 };+HashMap<u64, NonnullOwnPtr<PlaybackSession>> m_playback_sessions;HashMap<u64, NonnullRefPtr<Media::IncrementallyPopulatedStream>> m_media_streams;RefPtr<Media::VideoPresentationServerConnection> m_video_presentation_connection;diff --git a/Services/MediaServer/MediaClient.ipc b/Services/MediaServer/MediaClient.ipcindex 37438f6568d..585672fac5d 100644--- a/Services/MediaServer/MediaClient.ipc+++ b/Services/MediaServer/MediaClient.ipc@@ -19,6 +19,9 @@ endpoint MediaClient{// Only the controller answers this: the Browser connects the server to the AudioServer as a member of its tab's mix.request_audio_server_connection() => (Optional<IPC::TransportHandle> handle)+ // Likewise, the Browser launches the server's VideoDecoderServer, or a new one if the last one was lost, and+ // answers with video_decoder_server_connection_ready() once it has.+ request_video_decoder_server_connection(u64 request_id) =|file_media_support_reported(u64 request_id, Media::MediaSupportInfo info) =|decoder_capabilities_reported(u64 request_id, Optional<Media::DecoderCapabilities> capabilities) =|diff --git a/Services/MediaServer/MediaServer.ipc b/Services/MediaServer/MediaServer.ipcindex a2e5a08aad0..509164d00f0 100644--- a/Services/MediaServer/MediaServer.ipc+++ b/Services/MediaServer/MediaServer.ipc@@ -14,6 +14,7 @@ endpoint MediaServer{connect_new_client() => (Optional<IPC::TransportHandle> handle, int client_id)+ video_decoder_server_connection_ready(u64 request_id, Optional<IPC::TransportHandle> handle) =|connect_video_presentation_channel(int client_id, IPC::TransportHandle handle) =|request_file_media_support(u64 request_id, String type, String subtype, Optional<String> codecs_parameter) =|diff --git a/Services/MediaServer/SandboxMacOS.cpp b/Services/MediaServer/SandboxMacOS.cppindex a671279d0fd..59acff5922b 100644--- a/Services/MediaServer/SandboxMacOS.cpp+++ b/Services/MediaServer/SandboxMacOS.cpp@@ -23,7 +23,7 @@ ErrorOr<void> apply_sandbox(StringView mach_server_name)if (auto bundle = Sandbox::application_bundle_for_executable(executable_path); bundle.has_value())TRY(Sandbox::add_seatbelt_path_if_exists(paths, *bundle, Sandbox::SeatbeltPath::Access::ReadOnly));- auto system_services = Sandbox::SystemService::AudioDecoding | Sandbox::SystemService::VideoDecoding | Sandbox::SystemService::IOSurface;+ auto system_services = Sandbox::SystemService::AudioDecoding | Sandbox::SystemService::IOSurface;return Sandbox::apply_macos_sandbox({.paths = paths.span(),diff --git a/Services/MediaServer/main.cpp b/Services/MediaServer/main.cppindex 09e797fafee..6e2809ccc8a 100644--- a/Services/MediaServer/main.cpp+++ b/Services/MediaServer/main.cpp@@ -14,6 +14,7 @@#include <LibIPC/SingleServer.h>#include <LibMain/Main.h>#include <LibMedia/DecoderRegistrations.h>+#include <LibMedia/RemoteVideoDecoder.h>#include <MediaServer/ConnectionFromClient.h>#include <MediaServer/Sandbox.h>@@ -57,7 +58,7 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)(void)Media::FFmpeg::SystemFFmpeg::the();#endif- Media::install_video_decoders({ Media::hardware_video_decoders(), Media::ffmpeg_video_decoders() });+ Media::install_video_decoders({ Media::remote_video_decoders(), Media::ffmpeg_video_decoders() });Media::install_audio_decoders({ Media::audio_decoders() });if (!disable_sandbox)@@ -70,6 +71,9 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)Audio::ClientConnection::set_transport_factory([client] {return client->request_audio_server_transport();});+ Media::RemoteVideoDecoder::set_transport_requester([client](auto callback) {+ client->request_video_decoder_server_transport(move(callback));+ });return event_loop.exec();}diff --git a/Services/VideoDecoderServer/CMakeLists.txt b/Services/VideoDecoderServer/CMakeLists.txtnew file mode 100644index 00000000000..66ee1333e20--- /dev/null+++ b/Services/VideoDecoderServer/CMakeLists.txt@@ -0,0 +1,33 @@+set(SOURCES+ ControlConnection.cpp+)++add_library(videodecoderserverservice STATIC ${SOURCES})+add_executable(VideoDecoderServer main.cpp)++if (LINUX)+ target_sources(VideoDecoderServer PRIVATE SandboxLinux.cpp)+elseif (APPLE)+ target_sources(VideoDecoderServer PRIVATE SandboxMacOS.cpp)+else()+ target_sources(VideoDecoderServer PRIVATE SandboxUnimplemented.cpp)+endif()++add_dependencies(videodecoderserverservice+ generate_VideoDecoderServerControlClientEndpoint.h+ generate_VideoDecoderServerControlEndpoint.h+)++target_include_directories(videodecoderserverservice PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/../..)+target_include_directories(videodecoderserverservice PRIVATE ${LADYBIRD_SOURCE_DIR}/Services/)++target_link_libraries(VideoDecoderServer PRIVATE videodecoderserverservice LibCore LibMain LibMediaCodecs LibSandbox)+target_link_libraries(videodecoderserverservice PRIVATE LibCore LibIPC LibMediaCodecs)++if (WIN32)+ target_include_directories(VideoDecoderServer PRIVATE $<BUILD_INTERFACE:${PTHREAD_INCLUDE_DIR}>)+ target_include_directories(videodecoderserverservice PRIVATE $<BUILD_INTERFACE:${PTHREAD_INCLUDE_DIR}>)+ ladybird_windows_bin(VideoDecoderServer CONSOLE)+endif()++ladybird_sign_helper_process(VideoDecoderServer)diff --git a/Services/VideoDecoderServer/ControlConnection.cpp b/Services/VideoDecoderServer/ControlConnection.cppnew file mode 100644index 00000000000..adb957f50a2--- /dev/null+++ b/Services/VideoDecoderServer/ControlConnection.cpp@@ -0,0 +1,47 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <LibCore/Process.h>+#include <LibMediaCodecs/VideoDecoderServerConnection.h>+#include <VideoDecoderServer/ControlConnection.h>++namespace VideoDecoderServer {++ControlConnection::ControlConnection(NonnullOwnPtr<IPC::Transport> transport, ReadonlySpan<Media::VideoDecoderRegistration> hosted_decoders)+ : IPC::ConnectionFromClient<VideoDecoderServerControlClientEndpoint, VideoDecoderServerControlEndpoint>(*this, move(transport), 0)+ , m_hosted_decoders(hosted_decoders)+{+}++ControlConnection::~ControlConnection() = default;++void ControlConnection::die()+{+ Core::Process::terminate_immediately(0);+}++Messages::VideoDecoderServerControl::ConnectNewClientResponse ControlConnection::connect_new_client()+{+ if (m_client) {+ did_misbehave("The video decoder server serves only one client");+ return OptionalNone {};+ }++ auto paired_transports = IPC::Transport::create_paired();+ if (paired_transports.is_error()) {+ dbgln("Failed to connect a video decoder client: {}", paired_transports.error());+ return OptionalNone {};+ }++ // Once its client is gone, the server has nothing left to do.+ m_client = Media::VideoDecoderServerConnection::construct(move(paired_transports.value().local), m_hosted_decoders);+ m_client->on_death = [] {+ Core::Process::terminate_immediately(0);+ };+ return move(paired_transports.value().remote_handle);+}++}diff --git a/Services/VideoDecoderServer/ControlConnection.h b/Services/VideoDecoderServer/ControlConnection.hnew file mode 100644index 00000000000..40f799e3b0c--- /dev/null+++ b/Services/VideoDecoderServer/ControlConnection.h@@ -0,0 +1,37 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <LibIPC/ConnectionFromClient.h>+#include <LibMediaCodecs/Forward.h>+#include <LibMediaCodecs/VideoDecoderRegistry.h>+#include <VideoDecoderServer/VideoDecoderServerControlClientEndpoint.h>+#include <VideoDecoderServer/VideoDecoderServerControlEndpoint.h>++namespace VideoDecoderServer {++// The control plane of the VideoDecoderServer, spoken only by the Browser over the initial socket. It connects the one+// client the server serves; the server exits when either the Browser or that client goes away.+class ControlConnection final+ : public IPC::ConnectionFromClient<VideoDecoderServerControlClientEndpoint, VideoDecoderServerControlEndpoint> {+ C_OBJECT(ControlConnection);++public:+ virtual ~ControlConnection() override;++ virtual void die() override;++private:+ ControlConnection(NonnullOwnPtr<IPC::Transport>, ReadonlySpan<Media::VideoDecoderRegistration> hosted_decoders);++ virtual Messages::VideoDecoderServerControl::ConnectNewClientResponse connect_new_client() override;++ ReadonlySpan<Media::VideoDecoderRegistration> const m_hosted_decoders;+ RefPtr<Media::VideoDecoderServerConnection> m_client;+};++}diff --git a/Services/VideoDecoderServer/Sandbox.h b/Services/VideoDecoderServer/Sandbox.hnew file mode 100644index 00000000000..b1dc0774387--- /dev/null+++ b/Services/VideoDecoderServer/Sandbox.h@@ -0,0 +1,16 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <AK/Error.h>+#include <AK/StringView.h>++namespace VideoDecoderServer {++[[nodiscard]] ErrorOr<void> apply_sandbox(StringView mach_server_name);++}diff --git a/Services/VideoDecoderServer/SandboxLinux.cpp b/Services/VideoDecoderServer/SandboxLinux.cppnew file mode 100644index 00000000000..4d23924d61a--- /dev/null+++ b/Services/VideoDecoderServer/SandboxLinux.cpp@@ -0,0 +1,44 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <AK/LexicalPath.h>+#include <LibCore/System.h>+#include <LibSandbox/Sandbox.h>+#include <LibSandbox/Seccomp.h>+#include <VideoDecoderServer/Sandbox.h>++namespace VideoDecoderServer {++// FIXME: Grant the GPU access that hardware decoders need once the server hosts one.+ErrorOr<void> apply_sandbox(StringView)+{+ TRY(Sandbox::install_no_new_privileges());+ TRY(Sandbox::configure_runtime());++ auto executable_path = TRY(Core::System::current_executable_path());+ auto build_root = LexicalPath::dirname(LexicalPath::dirname(executable_path));++ Vector<Sandbox::LandlockPath> paths;+ // cpptrace opens loaded ELF objects when symbolizing in-process stack traces.+ TRY(Sandbox::add_landlock_path_if_exists(paths, executable_path, Sandbox::LandlockPath::Access::ReadOnly));+ TRY(Sandbox::add_landlock_path_if_exists(paths, LexicalPath::join(build_root, "lib"sv).string(), Sandbox::LandlockPath::Access::ReadOnly));+ TRY(Sandbox::add_landlock_path_if_exists(paths, "/proc/self"sv, Sandbox::LandlockPath::Access::ReadOnly));++ TRY(Sandbox::restrict_filesystem_with_landlock(paths.span()));++ Sandbox::SeccompPolicy policy;+ policy.allow_readonly_file_opens();+ policy.allow_filesystem_metadata_queries();+ policy.allow_file_descriptor_operations();+ policy.allow_ipc();+ policy.allow_socket_pairs();+ policy.allow_common_runtime();+ TRY(policy.install());++ return {};+}++}diff --git a/Services/VideoDecoderServer/SandboxMacOS.cpp b/Services/VideoDecoderServer/SandboxMacOS.cppnew file mode 100644index 00000000000..1d819974b02--- /dev/null+++ b/Services/VideoDecoderServer/SandboxMacOS.cpp@@ -0,0 +1,33 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <LibCore/System.h>+#include <LibSandbox/Sandbox.h>+#include <VideoDecoderServer/Sandbox.h>++namespace VideoDecoderServer {++ErrorOr<void> apply_sandbox(StringView mach_server_name)+{+ TRY(Sandbox::configure_runtime());++ auto executable_path = TRY(Core::System::current_executable_path());++ Vector<Sandbox::SeatbeltPath> paths;+ TRY(Sandbox::add_seatbelt_path_if_exists(paths, executable_path, Sandbox::SeatbeltPath::Access::ReadOnly));++ // The platform media frameworks look up the main bundle of the process.+ if (auto bundle = Sandbox::application_bundle_for_executable(executable_path); bundle.has_value())+ TRY(Sandbox::add_seatbelt_path_if_exists(paths, *bundle, Sandbox::SeatbeltPath::Access::ReadOnly));++ return Sandbox::apply_macos_sandbox({+ .paths = paths.span(),+ .mach_server_name = mach_server_name,+ .system_services = Sandbox::SystemService::VideoDecoding | Sandbox::SystemService::IOSurface,+ });+}++}diff --git a/Services/VideoDecoderServer/SandboxUnimplemented.cpp b/Services/VideoDecoderServer/SandboxUnimplemented.cppnew file mode 100644index 00000000000..07218585551--- /dev/null+++ b/Services/VideoDecoderServer/SandboxUnimplemented.cpp@@ -0,0 +1,16 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <VideoDecoderServer/Sandbox.h>++namespace VideoDecoderServer {++ErrorOr<void> apply_sandbox(StringView)+{+ return {};+}++}diff --git a/Services/VideoDecoderServer/VideoDecoderServerControl.ipc b/Services/VideoDecoderServer/VideoDecoderServerControl.ipcnew file mode 100644index 00000000000..956776dec68--- /dev/null+++ b/Services/VideoDecoderServer/VideoDecoderServerControl.ipc@@ -0,0 +1,7 @@+#include <LibIPC/TransportHandle.h>++endpoint VideoDecoderServerControl+{+ // The server serves one client, the MediaServer whose decoders it hosts.+ connect_new_client() => (Optional<IPC::TransportHandle> handle)+}diff --git a/Services/VideoDecoderServer/VideoDecoderServerControlClient.ipc b/Services/VideoDecoderServer/VideoDecoderServerControlClient.ipcnew file mode 100644index 00000000000..17fdc1ade1e--- /dev/null+++ b/Services/VideoDecoderServer/VideoDecoderServerControlClient.ipc@@ -0,0 +1,3 @@+endpoint VideoDecoderServerControlClient+{+}diff --git a/Services/VideoDecoderServer/main.cpp b/Services/VideoDecoderServer/main.cppnew file mode 100644index 00000000000..d1949cb262f--- /dev/null+++ b/Services/VideoDecoderServer/main.cpp@@ -0,0 +1,84 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <AK/Array.h>+#include <LibCore/ArgsParser.h>+#include <LibCore/CrashHandler.h>+#include <LibCore/EventLoop.h>+#include <LibCore/Platform/TaskRole.h>+#include <LibCore/Platform/ThreadQoS.h>+#include <LibCore/Process.h>+#include <LibIPC/SingleServer.h>+#include <LibMain/Main.h>+#include <LibMediaCodecs/FFmpeg/FFmpegVideoDecoder.h>+#include <LibMediaCodecs/HardwareVideoDecoders.h>+#include <LibMediaCodecs/VideoDecoderRegistry.h>+#include <VideoDecoderServer/ControlConnection.h>+#include <VideoDecoderServer/Sandbox.h>++static Media::DecoderErrorOr<NonnullOwnPtr<Media::VideoDecoder>> create_software_video_decoder(Media::CodecID codec_id, ReadonlyBytes codec_initialization_data)+{+ return NonnullOwnPtr<Media::VideoDecoder> { TRY(Media::FFmpeg::FFmpegVideoDecoder::try_create(codec_id, codec_initialization_data)) };+}++// Software decoders belong in the MediaServer, away from the GPU access this process will have. These are only for+// exercising the path through this process where no hardware decoder is available, as in tests.+static ReadonlySpan<Media::VideoDecoderRegistration> software_video_decoders_for_testing()+{+ static Array const decoders {+ Media::VideoDecoderRegistration { Media::FFmpeg::FFmpegVideoDecoder::capabilities, create_software_video_decoder },+ };+ return decoders;+}++ErrorOr<int> ladybird_main(Main::Arguments arguments)+{+ AK::set_rich_debug_enabled(true);++ int crash_report_fd = -1;+ StringView mach_server_name;+ bool wait_for_debugger = false;+ bool disable_sandbox = false;+ bool host_software_decoders = false;++ Core::ArgsParser args_parser;+ args_parser.add_option(crash_report_fd, "Descriptor for anonymous crash diagnostics", "crash-report-fd", 0, "fd");+ args_parser.add_option(mach_server_name, "Mach server name", "mach-server-name", 0, "mach_server_name");+ args_parser.add_option(wait_for_debugger, "Wait for debugger", "wait-for-debugger");+ args_parser.add_option(disable_sandbox, "Disable process sandboxing", "disable-sandbox");+ args_parser.add_option(host_software_decoders, "Host software decoders, for testing", "host-software-decoders");+ args_parser.parse(arguments);++ if (crash_report_fd >= 0) {+ if (auto result = Core::CrashHandler::initialize(crash_report_fd); result.is_error())+ warnln("Could not install crash report handler: {}", result.error());+ }++ if (wait_for_debugger)+ Core::Process::wait_for_debugger_and_break();++ if (auto result = Core::Platform::adopt_foreground_application_task_role(); result.is_error())+ warnln("Could not adopt the foreground application task role: {}", result.error());+ if (auto result = Core::Platform::set_current_thread_qos(Core::Platform::ThreadQoS::UserInitiated); result.is_error())+ warnln("Could not set main thread QoS: {}", result.error());++ auto& event_loop = Core::EventLoop::initialize_for_current_thread();++ Vector<Media::VideoDecoderRegistration> hosted_decoders;+ auto hardware_decoders = Media::hardware_video_decoders();+ hosted_decoders.append(hardware_decoders.data(), hardware_decoders.size());+ if (host_software_decoders) {+ auto software_decoders = software_video_decoders_for_testing();+ hosted_decoders.append(software_decoders.data(), software_decoders.size());+ }++ if (!disable_sandbox)+ TRY(VideoDecoderServer::apply_sandbox(mach_server_name));++ auto client = TRY(IPC::take_over_accepted_client_from_system_server<VideoDecoderServer::ControlConnection>(mach_server_name, hosted_decoders));++ return event_loop.exec();+}diff --git a/Tests/LibMedia/CMakeLists.txt b/Tests/LibMedia/CMakeLists.txtindex edf78ce8b9b..64a4396c589 100644--- a/Tests/LibMedia/CMakeLists.txt+++ b/Tests/LibMedia/CMakeLists.txt@@ -33,6 +33,7 @@ set(TEST_SOURCESTestParseMatroska.cppTestPipelineNodes.cppTestPlaybackManager.cpp+ TestRemoteVideoDecoder.cppTestRemoteVideoNode.cppTestSourceBufferDemuxer.cppTestTimeRanges.cpp@@ -75,6 +76,7 @@ target_link_libraries(TestISOBMFF PRIVATE LibThreading)target_link_libraries(TestMediaTime PRIVATE LibThreading)target_link_libraries(TestVideoFramePool PRIVATE LibThreading)target_link_libraries(TestIncrementallyPopulatedStream PRIVATE LibThreading)+target_link_libraries(TestRemoteVideoDecoder PRIVATE LibThreading LibIPC LibMediaCodecs)target_link_libraries(TestRemoteVideoNode PRIVATE LibThreading LibGfx LibIPC)if (LINUX)diff --git a/Tests/LibMedia/TestDecoderRegistry.cpp b/Tests/LibMedia/TestDecoderRegistry.cppindex 9c52db2038a..9dc14eb4316 100644--- a/Tests/LibMedia/TestDecoderRegistry.cpp+++ b/Tests/LibMedia/TestDecoderRegistry.cpp@@ -6,7 +6,7 @@#include <LibMedia/DecoderRegistrations.h>#include <LibMedia/FFmpeg/FFmpegAudioDecoder.h>-#include <LibMedia/FFmpeg/FFmpegVideoDecoder.h>+#include <LibMediaCodecs/FFmpeg/FFmpegVideoDecoder.h>#include <LibTest/TestCase.h>#ifdef AK_OS_MACOSdiff --git a/Tests/LibMedia/TestH264Decode.cpp b/Tests/LibMedia/TestH264Decode.cppindex 9cce957ede8..aa889a0af33 100644--- a/Tests/LibMedia/TestH264Decode.cpp+++ b/Tests/LibMedia/TestH264Decode.cpp@@ -7,8 +7,8 @@#include <LibMedia/Containers/ISOBMFF/ISOBMFFDemuxer.h>#include <LibMedia/Demuxer.h>#include <LibMedia/DemuxerRegistry.h>-#include <LibMedia/FFmpeg/FFmpegVideoDecoder.h>#include <LibMedia/IncrementallyPopulatedStream.h>+#include <LibMediaCodecs/FFmpeg/FFmpegVideoDecoder.h>#include <LibMediaCodecs/FFmpeg/SystemFFmpeg.h>#include "TestMediaCommon.h"diff --git a/Tests/LibMedia/TestRemoteVideoDecoder.cpp b/Tests/LibMedia/TestRemoteVideoDecoder.cppnew file mode 100644index 00000000000..024e3acb15b--- /dev/null+++ b/Tests/LibMedia/TestRemoteVideoDecoder.cpp@@ -0,0 +1,500 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <AK/Array.h>+#include <AK/Atomic.h>+#include <AK/ConditionVariable.h>+#include <AK/Mutex.h>+#include <AK/ScopeGuard.h>+#include <AK/StringHash.h>+#include <LibCore/EventLoop.h>+#include <LibCore/File.h>+#include <LibIPC/Transport.h>+#include <LibIPC/TransportHandle.h>+#include <LibMedia/Containers/Matroska/MatroskaDemuxer.h>+#include <LibMedia/DecoderRegistrations.h>+#include <LibMedia/IncrementallyPopulatedStream.h>+#include <LibMedia/Producers/DecodedVideoProducer.h>+#include <LibMedia/RemoteVideoDecoder.h>+#include <LibMediaCodecs/FFmpeg/FFmpegVideoDecoder.h>+#include <LibMediaCodecs/VideoDecoderServerConnection.h>+#include <LibMediaCodecs/VideoFrame.h>+#include <LibThreading/Thread.h>+#include <Tests/LibMedia/TestMediaCommon.h>+#include <Tests/LibMedia/WithholdingVideoDecoder.h>++struct FrameDigest {+ AK::Duration timestamp;+ u32 pixel_hash { 0 };++ bool operator==(FrameDigest const&) const = default;+};++template<>+struct AK::Formatter<FrameDigest> : Formatter<FormatString> {+ ErrorOr<void> format(FormatBuilder& builder, FrameDigest const& digest)+ {+ return Formatter<FormatString>::format(builder, "{}ms:{:08x}"sv, digest.timestamp.to_milliseconds(), digest.pixel_hash);+ }+};++namespace {++Media::DecoderErrorOr<NonnullOwnPtr<Media::VideoDecoder>> create_software_video_decoder(Media::CodecID codec_id, ReadonlyBytes codec_initialization_data)+{+ return NonnullOwnPtr<Media::VideoDecoder> { TRY(Media::FFmpeg::FFmpegVideoDecoder::try_create(codec_id, codec_initialization_data)) };+}++ReadonlySpan<Media::VideoDecoderRegistration> hosted_decoders()+{+ // The withholding decoder answers only while a test is withholding outputs.+ static Array decoders {+ WithholdingVideoDecoder::registrations()[0],+ Media::VideoDecoderRegistration { Media::FFmpeg::FFmpegVideoDecoder::capabilities, create_software_video_decoder },+ };+ return decoders;+}++Atomic<u32> s_server_launch_count { 0 };++// The server that is running, if any. Its connection is only touched on its own thread.+Mutex s_running_server_mutex;+Core::EventLoop* s_running_server_event_loop { nullptr };+Media::VideoDecoderServerConnection* s_running_server_connection { nullptr };+u32 s_close_every_server_after_frames { 0 };++// Hosts a server on a thread of its own, as the VideoDecoderServer process would.+ErrorOr<NonnullOwnPtr<IPC::Transport>> launch_in_process_server()+{+ auto paired_transports = TRY(IPC::Transport::create_paired());+ s_server_launch_count++;++ auto thread = TRY(Threading::Thread::try_create("Video Decoder Server"sv, [transport = move(paired_transports.local)]() mutable -> intptr_t {+ Core::EventLoop loop;+ auto connection = Media::VideoDecoderServerConnection::construct(move(transport), hosted_decoders());+ {+ MutexLocker locker { s_running_server_mutex };+ if (s_close_every_server_after_frames > 0)+ connection->close_after_decoded_frame_count(s_close_every_server_after_frames);+ s_running_server_event_loop = &loop;+ s_running_server_connection = connection.ptr();+ }+ connection->on_death = [&loop] {+ MutexLocker locker { s_running_server_mutex };+ if (s_running_server_event_loop == &loop) {+ s_running_server_event_loop = nullptr;+ s_running_server_connection = nullptr;+ }+ loop.quit(0);+ };+ return loop.exec();+ }));+ thread->start();+ thread->detach();+ return paired_transports.remote_handle.create_transport();+}++// Applies to the running server, and to every one launched after it while the count is set.+void close_servers_after_decoded_frames(u32 frame_count)+{+ MutexLocker locker { s_running_server_mutex };+ s_close_every_server_after_frames = frame_count;+ if (s_running_server_event_loop == nullptr)+ return;+ s_running_server_event_loop->deferred_invoke([frame_count] {+ MutexLocker locker { s_running_server_mutex };+ if (s_running_server_connection != nullptr)+ s_running_server_connection->close_after_decoded_frame_count(frame_count);+ });+}++void use_remote_decoders()+{+ Media::install_video_decoders({ Media::remote_video_decoders(), Media::ffmpeg_video_decoders() });+}++void use_local_decoders()+{+ Media::install_video_decoders({ Media::ffmpeg_video_decoders() });+}++FrameDigest digest_frame(Media::VideoFrame const& frame)+{+ auto yuv_data = frame.yuv_data();+ VERIFY(yuv_data.has_value());+ auto hash = string_hash(reinterpret_cast<char const*>(yuv_data->y_data().data()), yuv_data->y_data().size());+ hash = string_hash(reinterpret_cast<char const*>(yuv_data->u_data().data()), yuv_data->u_data().size(), hash);+ hash = string_hash(reinterpret_cast<char const*>(yuv_data->v_data().data()), yuv_data->v_data().size(), hash);+ return { frame.timestamp(), hash };+}++NonnullRefPtr<Media::DecodedVideoProducer> create_started_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()));+ NonnullRefPtr<Media::Demuxer> demuxer = MUST(Media::Matroska::MatroskaDemuxer::from_stream(stream));+ auto track = MUST(demuxer->get_preferred_track_for_type(Media::TrackType::Video)).release_value();+ auto producer = MUST(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();+ return producer;+}++Optional<FrameDigest> take_frame(Media::DecodedVideoProducer& producer, Core::EventLoop& loop)+{+ auto deadline = MonotonicTime::now_coarse() + AK::Duration::from_seconds(5);+ while (MonotonicTime::now_coarse() < deadline) {+ auto output = producer.peek();+ if (output.status == Media::PipelineStatus::HaveData) {+ auto digest = digest_frame(*output.frame);+ producer.consume();+ return digest;+ }+ if (output.status == Media::PipelineStatus::EndOfStream || output.status == Media::PipelineStatus::Error)+ return {};+ loop.pump(Core::EventLoop::WaitMode::PollForEvents);+ }+ FAIL("Timed out waiting for a frame");+ return {};+}++// Frames submitted again after a decoder loses its state can repeat ones that were already delivered, which the+// sinks ignore, since they show nothing new.+void append_unless_repeated(Vector<FrameDigest>& digests, FrameDigest const& digest)+{+ if (!digests.is_empty() && digest.timestamp <= digests.last().timestamp)+ return;+ digests.append(digest);+}++Vector<FrameDigest> decode_every_frame(StringView path)+{+ auto& loop = never_destroyed_event_loop();+ auto producer = create_started_producer(loop, path);+ Vector<FrameDigest> digests;+ while (true) {+ auto digest = take_frame(*producer, loop);+ if (!digest.has_value())+ break;+ append_unless_repeated(digests, *digest);+ }+ return digests;+}++Vector<FrameDigest> decode_every_frame_locally(StringView path)+{+ use_local_decoders();+ auto digests = decode_every_frame(path);+ use_remote_decoders();+ return digests;+}++// The Browser is asked for transports from the MediaServer's main thread, which never asks for one itself. The tests+// ask from this thread, so the requester gets a thread of its own, as the Browser's answers would arrive on.+void install_transport_requester_on_its_own_thread()+{+ IGNORE_USE_IN_ESCAPING_LAMBDA Mutex mutex;+ IGNORE_USE_IN_ESCAPING_LAMBDA ConditionVariable condition { mutex };+ IGNORE_USE_IN_ESCAPING_LAMBDA bool requester_is_installed = false;+ auto thread = MUST(Threading::Thread::try_create("Transport Requester"sv, [&]() -> intptr_t {+ Core::EventLoop loop;+ Media::RemoteVideoDecoder::set_transport_requester([](auto callback) { callback(launch_in_process_server()); });+ {+ MutexLocker locker { mutex };+ requester_is_installed = true;+ condition.broadcast();+ }+ return loop.exec();+ }));+ thread->start();+ thread->detach();++ MutexLocker locker { mutex };+ while (!requester_is_installed)+ condition.wait();+}++constexpr auto test_video_path = "./vp9_in_webm.webm"sv;++}++TEST_SETUP+{+ (void)never_destroyed_event_loop();+ install_transport_requester_on_its_own_thread();+ use_remote_decoders();+ Media::install_audio_decoders({ Media::audio_decoders() });+}++TEST_CASE(frames_decoded_by_the_server_match_local_decoding)+{+ auto expected = decode_every_frame_locally(test_video_path);+ EXPECT(expected.size() > 10);++ auto launches_before = s_server_launch_count.load();+ auto actual = decode_every_frame(test_video_path);+ EXPECT_EQ(actual, expected);+ EXPECT(s_server_launch_count.load() - launches_before <= 1);+}++TEST_CASE(a_lost_server_is_relaunched_and_decoding_resumes_where_it_left_off)+{+ auto expected = decode_every_frame_locally(test_video_path);++ auto launches_before = s_server_launch_count.load();+ close_servers_after_decoded_frames(7);+ auto& loop = never_destroyed_event_loop();+ auto producer = create_started_producer(loop, test_video_path);+ Vector<FrameDigest> actual;+ while (true) {+ auto digest = take_frame(*producer, loop);+ if (!digest.has_value())+ break;+ append_unless_repeated(actual, *digest);+ // Only the first server is lost.+ if (s_server_launch_count.load() > launches_before)+ close_servers_after_decoded_frames(0);+ }+ EXPECT_EQ(actual, expected);+ EXPECT(s_server_launch_count.load() > launches_before);+}++TEST_CASE(a_decoder_that_keeps_losing_its_server_falls_back_to_the_next_decoder)+{+ auto expected = decode_every_frame_locally(test_video_path);++ auto launches_before = s_server_launch_count.load();+ bool server_was_running = false;+ {+ MutexLocker locker { s_running_server_mutex };+ server_was_running = s_running_server_event_loop != nullptr;+ }+ close_servers_after_decoded_frames(3);+ auto actual = decode_every_frame(test_video_path);+ close_servers_after_decoded_frames(0);+ EXPECT_EQ(actual, expected);++ // Every server it lost was replaced, except the last.+ auto expected_launches = Media::RemoteVideoDecoder::MAXIMUM_SERVER_LOSSES;+ if (!server_was_running)+ expected_launches++;+ EXPECT_EQ(s_server_launch_count.load() - launches_before, expected_launches);+}++TEST_CASE(a_seek_discards_the_frames_in_flight)+{+ auto expected = decode_every_frame_locally(test_video_path);+ VERIFY(expected.size() > 20);++ auto& loop = never_destroyed_event_loop();+ auto producer = create_started_producer(loop, test_video_path);+ for (size_t index = 0; index < 3; index++)+ EXPECT_EQ(take_frame(*producer, loop), expected[index]);++ // Seeking backward leaves the frames already submitted for later timestamps in flight.+ auto const& target = expected[1];+ producer->seek(target.timestamp, Media::InvalidateHeldData::Yes);+ EXPECT_EQ(take_frame(*producer, loop), target);+ EXPECT_EQ(take_frame(*producer, loop), expected[2]);+}++namespace {++// A decoder whose server withholds as many outputs as it can, and so has stopped answering: the last submissions in+// flight stay unanswered until the test releases an output.+struct StalledDecoding {+ NonnullRefPtr<WithheldOutputs> withheld_outputs;+ NonnullOwnPtr<Media::RemoteVideoDecoder> decoder;+};++StalledDecoding submit_until_the_server_stops_answering(size_t unanswered_submission_count)+{+ 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 file = MUST(Core::File::open(test_video_path, Core::File::OpenMode::Read));+ auto stream = Media::IncrementallyPopulatedStream::create_from_buffer(MUST(file->read_until_eof()));+ NonnullRefPtr<Media::Demuxer> demuxer = MUST(Media::Matroska::MatroskaDemuxer::from_stream(stream));+ auto track = MUST(demuxer->get_preferred_track_for_type(Media::TrackType::Video)).release_value();+ MUST(demuxer->create_context_for_track(track));++ auto first_coded_frame = MUST(demuxer->get_next_sample_for_track(track));+ auto decoder = MUST(Media::RemoteVideoDecoder::try_create(first_coded_frame.codec_id(), first_coded_frame.new_codec_configuration().value()));+ decoder->set_output_arrived_callback([] { });++ MUST(decoder->receive_coded_data(first_coded_frame, Media::DecodeIntent::Output));+ for (size_t index = 1; index < WithholdingVideoDecoder::MAXIMUM_WITHHELD_OUTPUTS + unanswered_submission_count; index++)+ MUST(decoder->receive_coded_data(MUST(demuxer->get_next_sample_for_track(track)), Media::DecodeIntent::Output));+ EXPECT(withheld_outputs->wait_until_withheld_count_reaches(WithholdingVideoDecoder::MAXIMUM_WITHHELD_OUTPUTS, AK::Duration::from_seconds(5)));+ return { move(withheld_outputs), move(decoder) };+}++// Takes output on a thread of its own, so that a wait inside the call can be observed and ended from the test.+struct OutputTaker {+ explicit OutputTaker(Media::RemoteVideoDecoder& decoder)+ : thread(MUST(Threading::Thread::try_create("Taker"sv, [this, &decoder]() -> intptr_t {+ auto result = decoder.take_next_output({});+ MutexLocker locker { mutex };+ answer = result.is_error() ? result.error().category() : Media::DecoderErrorCategory::Unknown;+ condition.broadcast();+ return 0;+ })))+ {+ thread->start();+ }++ ~OutputTaker() { (void)thread->join(); }++ Optional<Media::DecoderErrorCategory> wait_for_answer(AK::Duration timeout)+ {+ auto deadline = MonotonicTime::now() + timeout;+ MutexLocker locker { mutex };+ while (!answer.has_value() && MonotonicTime::now() < deadline)+ condition.wait_for(deadline - MonotonicTime::now());+ return answer;+ }++ Mutex mutex;+ ConditionVariable condition { mutex };+ Optional<Media::DecoderErrorCategory> answer;+ NonnullRefPtr<Threading::Thread> thread;+};++}++// The server answers the submissions a flush supersedes only once its decoder lets it, so the frames submitted after+// the flush must not wait behind them.+TEST_CASE(superseded_submissions_are_not_waited_for_after_a_flush)+{+ auto stalled = submit_until_the_server_stops_answering(Media::RemoteVideoDecoder::MAXIMUM_FRAMES_IN_FLIGHT);+ stalled.decoder->flush();++ {+ OutputTaker taker { *stalled.decoder };+ auto answer = taker.wait_for_answer(AK::Duration::from_seconds(2));+ if (!answer.has_value())+ FAIL("The frames submitted before the flush were waited for");+ else+ EXPECT_EQ(*answer, Media::DecoderErrorCategory::NeedsMoreInput);+ // Letting the server's decoder finish answers the superseded submissions and ends the taker either way.+ while (stalled.withheld_outputs->release_next()) { }+ }+}++// A frame the server's decoder finishes after the server answered its submission has to reach the client, and wake+// it, without the client submitting anything else.+TEST_CASE(output_the_server_decoder_finishes_later_wakes_the_client)+{+ 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 file = MUST(Core::File::open(test_video_path, Core::File::OpenMode::Read));+ auto stream = Media::IncrementallyPopulatedStream::create_from_buffer(MUST(file->read_until_eof()));+ NonnullRefPtr<Media::Demuxer> demuxer = MUST(Media::Matroska::MatroskaDemuxer::from_stream(stream));+ auto track = MUST(demuxer->get_preferred_track_for_type(Media::TrackType::Video)).release_value();+ TRY_OR_FAIL(demuxer->create_context_for_track(track));++ Mutex wake_mutex;+ ConditionVariable wake_condition { wake_mutex };+ size_t wake_count = 0;++ auto first_coded_frame = TRY_OR_FAIL(demuxer->get_next_sample_for_track(track));+ auto decoder = TRY_OR_FAIL(Media::RemoteVideoDecoder::try_create(first_coded_frame.codec_id(), first_coded_frame.new_codec_configuration().value()));+ decoder->set_output_arrived_callback([&] {+ MutexLocker locker { wake_mutex };+ wake_count++;+ wake_condition.broadcast();+ });++ constexpr size_t submitted_frame_count = 3;+ TRY_OR_FAIL(decoder->receive_coded_data(first_coded_frame, Media::DecodeIntent::Output));+ for (size_t index = 1; index < submitted_frame_count; index++)+ TRY_OR_FAIL(decoder->receive_coded_data(TRY_OR_FAIL(demuxer->get_next_sample_for_track(track)), Media::DecodeIntent::Output));++ auto result = decoder->take_next_output({});+ EXPECT(result.is_error() && result.error().category() == Media::DecoderErrorCategory::NeedsMoreInput);+ EXPECT(withheld_outputs->wait_until_withheld_count_reaches(submitted_frame_count, AK::Duration::from_seconds(5)));+ EXPECT_EQ(wake_count, 0u);++ EXPECT(withheld_outputs->release_next());+ {+ auto deadline = MonotonicTime::now() + AK::Duration::from_seconds(5);+ MutexLocker locker { wake_mutex };+ while (wake_count == 0 && MonotonicTime::now() < deadline)+ wake_condition.wait_for(deadline - MonotonicTime::now());+ if (wake_count == 0) {+ FAIL("The client was not woken for the frame the server's decoder finished");+ return;+ }+ }++ auto frame = decoder->take_next_output({});+ if (frame.is_error())+ FAIL(ByteString::formatted("The frame the server's decoder finished was not delivered: {}", frame.error().description()));+ else+ EXPECT_EQ(frame.value()->timestamp(), first_coded_frame.presentation_timestamp());+}++// Once the client holds every slot the server can decode into, the server waits for one to be released, and the+// client answers TryAgain until a release of its own lets the server decode again.+TEST_CASE(a_server_out_of_slots_is_waited_for_until_a_frame_is_released)+{+ auto file = MUST(Core::File::open(test_video_path, Core::File::OpenMode::Read));+ auto stream = Media::IncrementallyPopulatedStream::create_from_buffer(MUST(file->read_until_eof()));+ NonnullRefPtr<Media::Demuxer> demuxer = MUST(Media::Matroska::MatroskaDemuxer::from_stream(stream));+ auto track = MUST(demuxer->get_preferred_track_for_type(Media::TrackType::Video)).release_value();+ TRY_OR_FAIL(demuxer->create_context_for_track(track));++ auto coded_frame = TRY_OR_FAIL(demuxer->get_next_sample_for_track(track));+ auto decoder = TRY_OR_FAIL(Media::RemoteVideoDecoder::try_create(coded_frame.codec_id(), coded_frame.new_codec_configuration().value()));+ size_t storage_freed_count = 0;+ decoder->set_storage_freed_callback([&] { storage_freed_count++; });+ decoder->set_output_arrived_callback([] { });++ Vector<NonnullRefPtr<Media::VideoFrame>> held_frames;+ auto server_ran_out_of_slots = false;+ for (size_t submitted_count = 0; submitted_count < 32 && !server_ran_out_of_slots; submitted_count++) {+ TRY_OR_FAIL(decoder->receive_coded_data(coded_frame, Media::DecodeIntent::Output));+ while (true) {+ auto result = decoder->take_next_output({});+ if (!result.is_error()) {+ held_frames.append(result.release_value());+ continue;+ }+ if (result.error().category() == Media::DecoderErrorCategory::TryAgain) {+ server_ran_out_of_slots = true;+ break;+ }+ if (result.error().category() == Media::DecoderErrorCategory::NeedsMoreInput)+ break;+ FAIL(ByteString::formatted("Unexpected decoder error: {}", result.error().description()));+ return;+ }+ coded_frame = TRY_OR_FAIL(demuxer->get_next_sample_for_track(track));+ }+ EXPECT(server_ran_out_of_slots);+ EXPECT_EQ(held_frames.size(), static_cast<size_t>(Media::VideoFramePool::MAX_SLOT_COUNT));+ EXPECT_EQ(storage_freed_count, 0u);++ // Nothing has changed for the server, so the answer is the same without waiting.+ auto result = decoder->take_next_output({});+ EXPECT(result.is_error() && result.error().category() == Media::DecoderErrorCategory::TryAgain);++ auto last_held_timestamp = held_frames.last()->timestamp();+ held_frames.remove(0);+ EXPECT_EQ(storage_freed_count, 1u);++ auto frame = decoder->take_next_output({});+ if (frame.is_error())+ FAIL(ByteString::formatted("The frame decoded into the released slot was not delivered: {}", frame.error().description()));+ else+ EXPECT(frame.value()->timestamp() > last_held_timestamp);+ EXPECT_EQ(storage_freed_count, 1u);+}diff --git a/Tests/LibMedia/TestRemoteVideoNode.cpp b/Tests/LibMedia/TestRemoteVideoNode.cppindex 8c173fd6957..97b4c18c341 100644--- a/Tests/LibMedia/TestRemoteVideoNode.cpp+++ b/Tests/LibMedia/TestRemoteVideoNode.cpp@@ -395,6 +395,48 @@ TEST_CASE(consumer_sends_backward_seeks_upstream)EXPECT_EQ(upstream_seeks, 1u);}+// The seek must reach upstream before the stale frames' slots are released, and a frame of the new seek that arrives+// in between must stay in the ring.+TEST_CASE(consumer_requests_seeks_before_releasing_stale_frames)+{+ auto producer_edge = MUST(VideoEdgeQueue::create());+ auto ring_fd = MUST(Core::System::dup(producer_edge.ring_fd()));+ auto consumer_edge = MUST(VideoEdgeQueue::create(ring_fd, producer_edge.header_buffer()));++ Vector<StringView> events;+ Vector<u32> released_slot_indices;+ RemoteVideoProducer::Delegates delegates;+ delegates.request_start = [] { };+ delegates.request_seek = [&](AK::Duration, InvalidateHeldData) {+ events.append("seek"sv);+ VideoFrameHandle handle;+ handle.timestamp = AK::Duration::from_milliseconds(500);+ handle.duration = AK::Duration::from_milliseconds(100);+ handle.slot_index = 4;+ MUST(producer_edge.enqueue(handle, 1));+ };+ delegates.release_slot = [&](VideoFramePoolID, u32 slot_index) {+ events.append("release"sv);+ released_slot_indices.append(slot_index);+ };+ delegates.notify_space_available = [] { };+ auto consumer = RemoteVideoProducer::create(move(consumer_edge), VideoFrameSlotDirectory::create(), move(delegates));++ for (u32 i = 0; i < 4; i++) {+ VideoFrameHandle handle;+ handle.timestamp = AK::Duration::from_milliseconds(1000 + (i * 100));+ handle.duration = AK::Duration::from_milliseconds(100);+ handle.slot_index = i;+ MUST(producer_edge.enqueue(handle, 0));+ }++ consumer->seek(AK::Duration::from_milliseconds(500));++ EXPECT_EQ(events.size(), 5u);+ EXPECT_EQ(events.first(), "seek"sv);+ EXPECT_EQ(released_slot_indices, (Vector<u32> { 0, 1, 2, 3 }));+}+// With the end of stream published, no frames exist beyond the lookahead for the producer to// re-emit, so a seek past the end must resolve locally instead of discarding the queued tail.TEST_CASE(consumer_resolves_seeks_past_the_end_of_stream_locally)diff --git a/Tests/LibMedia/TestSystemFFmpeg.cpp b/Tests/LibMedia/TestSystemFFmpeg.cppindex bb8fe74dcfc..2f8c23eeb57 100644--- a/Tests/LibMedia/TestSystemFFmpeg.cpp+++ b/Tests/LibMedia/TestSystemFFmpeg.cpp@@ -5,8 +5,8 @@*/#include <LibMedia/DemuxerRegistry.h>-#include <LibMedia/FFmpeg/FFmpegVideoDecoder.h>#include <LibMedia/IncrementallyPopulatedStream.h>+#include <LibMediaCodecs/FFmpeg/FFmpegVideoDecoder.h>#include <LibMediaCodecs/FFmpeg/SystemFFmpeg.h>#include "TestMediaCommon.h"diff --git a/Tests/LibMedia/TestVP9Decode.cpp b/Tests/LibMedia/TestVP9Decode.cppindex c0f3a0ad48c..81011428fbd 100644--- a/Tests/LibMedia/TestVP9Decode.cpp+++ b/Tests/LibMedia/TestVP9Decode.cpp@@ -5,7 +5,7 @@*/#include <LibMedia/DemuxerRegistry.h>-#include <LibMedia/FFmpeg/FFmpegVideoDecoder.h>+#include <LibMediaCodecs/FFmpeg/FFmpegVideoDecoder.h>#include "TestMediaCommon.h"diff --git a/Tests/LibMedia/TestVideoToolboxDecode.cpp b/Tests/LibMedia/TestVideoToolboxDecode.cppindex 04a97cd0964..0fd9eb2e6f2 100644--- a/Tests/LibMedia/TestVideoToolboxDecode.cpp+++ b/Tests/LibMedia/TestVideoToolboxDecode.cpp@@ -7,13 +7,13 @@#include <AK/HashMap.h>#include <AK/HashTable.h>#include <LibMedia/DemuxerRegistry.h>-#include <LibMedia/VideoToolbox/VideoToolboxVideoDecoder.h>#include <LibMediaCodecs/CodecParameters.h>#include <LibMediaCodecs/Codecs/AV1.h>#include <LibMediaCodecs/Codecs/H264.h>#include <LibMediaCodecs/VideoFrame.h>#include <LibMediaCodecs/VideoFramePool.h>#include <LibMediaCodecs/VideoSurface.h>+#include <LibMediaCodecs/VideoToolbox/VideoToolboxVideoDecoder.h>#include "TestMediaCommon.h"diff --git a/Tests/LibMedia/WithholdingVideoDecoder.h b/Tests/LibMedia/WithholdingVideoDecoder.hindex efd23bd01a5..d611d3fb066 100644--- a/Tests/LibMedia/WithholdingVideoDecoder.h+++ b/Tests/LibMedia/WithholdingVideoDecoder.h@@ -46,11 +46,25 @@ public:return m_withheld.size();}+ bool wait_until_withheld_count_reaches(size_t count, AK::Duration timeout)+ {+ auto deadline = MonotonicTime::now() + timeout;+ MutexLocker locker { m_mutex };+ while (m_withheld.size() < count) {+ auto now = MonotonicTime::now();+ if (now >= deadline)+ return false;+ m_withheld_changed.wait_for(deadline - now);+ }+ return true;+ }+private:friend class WithholdingVideoDecoder;mutable Mutex m_mutex;ConditionVariable m_released_changed { m_mutex };+ ConditionVariable m_withheld_changed { m_mutex };Vector<Output> m_withheld;Vector<Output> m_released;Function<void()> m_output_arrived_callback;@@ -105,6 +119,7 @@ public:m_withheld_outputs->m_caller_is_waiting_for_output = false;}m_withheld_outputs->m_withheld.append({ coded_frame.presentation_timestamp(), coded_frame.duration() });+ m_withheld_outputs->m_withheld_changed.broadcast();return {};}