Truly independent web browser
LibMediaCodecs: Hold every video frame's pixels the same way
Zaggy10241dd191759408
diff --git a/Libraries/LibMedia/RemoteVideoDecoder.cpp b/Libraries/LibMedia/RemoteVideoDecoder.cppindex eec02100b08..a1b06baf12f 100644--- a/Libraries/LibMedia/RemoteVideoDecoder.cpp+++ b/Libraries/LibMedia/RemoteVideoDecoder.cpp@@ -394,7 +394,7 @@ private:shutdown();}- virtual void frame_decoded(u64 decoder_id, u32 generation, u64 frame_id, VideoFrameMetadata metadata, Core::AnonymousBuffer pixel_buffer, RefPtr<VideoSurface> surface) override+ virtual void frame_decoded(u64 decoder_id, u32 generation, u64 frame_id, VideoFrameMetadata metadata, VideoFramePixels pixels) override{auto state = find_decoder(decoder_id);if (!state) {@@ -414,7 +414,7 @@ private:if (server_was_waiting_for_storage && state->storage_freed_callback)state->storage_freed_callback();};- auto frame_or_error = create_received_video_frame(metadata, move(pixel_buffer), move(surface), 0, move(release_to_server));+ auto frame_or_error = create_received_video_frame(metadata, move(pixels), 0, move(release_to_server));if (frame_or_error.is_error()) {disconnect_misbehaving_server("unusable frame"sv, frame_or_error.release_error());return;@@ -740,7 +740,7 @@ DecoderErrorOr<NonnullRefPtr<VideoFrame>> RemoteVideoDecoder::take_next_output(Ccicp.adopt_specified_values(frame->cicp());return DECODER_TRY_ALLOC(try_make_ref_counted<VideoFrame>(frame->timestamp(), frame->duration(), frame->size(),- frame->bit_depth(), frame->subsampling(), cicp, frame->backing_storage()));+ frame->bit_depth(), frame->subsampling(), cicp, frame->storage()));}void RemoteVideoDecoder::flush()diff --git a/Libraries/LibMedia/Sinks/RemoteVideoSink.cpp b/Libraries/LibMedia/Sinks/RemoteVideoSink.cppindex 19192d6a2ec..7d61fb122f2 100644--- a/Libraries/LibMedia/Sinks/RemoteVideoSink.cpp+++ b/Libraries/LibMedia/Sinks/RemoteVideoSink.cpp@@ -12,7 +12,7 @@#include <LibMedia/Producers/VideoProducer.h>#include <LibMedia/Sinks/RemoteVideoSink.h>#include <LibMediaCodecs/VideoFrame.h>-#include <LibMediaCodecs/VideoSurface.h>+#include <LibMediaCodecs/VideoFramePool.h>#include <LibThreading/Thread.h>namespace Media {@@ -354,16 +354,12 @@ void RemoteVideoSink::ThreadData::lend_frame(NonnullRefPtr<VideoFrame> const& frm_lent_frames.set(lend_id, frame);}- LentFrame lent_frame {+ m_delegates.send_frame({.lend_id = lend_id,.seek_id = seek_id,.metadata = VideoFrameMetadata::for_frame(*frame),- .pixel_buffer = {},- .surface = frame->surface(),- };- if (!lent_frame.surface)- lent_frame.pixel_buffer = frame->pixel_buffer();- m_delegates.send_frame(move(lent_frame));+ .pixels = frame->storage()->pixels(),+ });}void RemoteVideoSink::ThreadData::pump_thread_loop()diff --git a/Libraries/LibMedia/Sinks/RemoteVideoSink.h b/Libraries/LibMedia/Sinks/RemoteVideoSink.hindex f7fbfaf050a..d58b5f8c7f3 100644--- a/Libraries/LibMedia/Sinks/RemoteVideoSink.h+++ b/Libraries/LibMedia/Sinks/RemoteVideoSink.h@@ -15,8 +15,8 @@#include <LibMedia/Forward.h>#include <LibMedia/MediaTime.h>#include <LibMedia/Sinks/VideoSink.h>+#include <LibMediaCodecs/VideoFrame.h>#include <LibMediaCodecs/VideoFrameMetadata.h>-#include <LibMediaCodecs/VideoSurface.h>#include <LibThreading/Forward.h>namespace Media {@@ -30,9 +30,7 @@ public:u64 lend_id { 0 };u32 seek_id { 0 };VideoFrameMetadata metadata;- // Exactly one of these holds the frame's pixels.- Core::AnonymousBuffer pixel_buffer;- RefPtr<VideoSurface> surface;+ VideoFramePixels pixels;};struct Delegates {diff --git a/Libraries/LibMedia/VideoPresentation/VideoPresentationClient.ipc b/Libraries/LibMedia/VideoPresentation/VideoPresentationClient.ipcindex dd0acf7ba60..49f8dd6cd96 100644--- a/Libraries/LibMedia/VideoPresentation/VideoPresentationClient.ipc+++ b/Libraries/LibMedia/VideoPresentation/VideoPresentationClient.ipc@@ -1,13 +1,14 @@#include <LibMedia/InvalidateHeldData.h>#include <LibMedia/MediaTime.h>#include <LibMedia/PipelineStatus.h>+#include <LibMediaCodecs/VideoFrame.h>#include <LibMediaCodecs/VideoFrameMetadata.h>#include <LibMediaCodecs/VideoSurface.h>endpoint VideoPresentationClient {video_edge_ready(u64 edge_id, Media::MediaTimeReader time_reader) =|update_edge_time_reader(u64 edge_id, Media::MediaTimeReader time_reader) =|- lend_frame(u64 edge_id, u64 lend_id, u32 seek_id, Media::VideoFrameMetadata metadata, Core::AnonymousBuffer pixel_buffer, RefPtr<Media::VideoSurface> surface) =|+ lend_frame(u64 edge_id, u64 lend_id, u32 seek_id, Media::VideoFrameMetadata metadata, Media::VideoFramePixels pixels) =|// The status the consumer reaches once every frame lent under the same seek has been taken.edge_status_changed(u64 edge_id, Media::PipelineStatus status, u32 seek_id) =|notify_clock_resumed(u64 edge_id) =|diff --git a/Libraries/LibMedia/VideoPresentation/VideoPresentationClientConnection.cpp b/Libraries/LibMedia/VideoPresentation/VideoPresentationClientConnection.cppindex 05736e6e08e..3037ae41714 100644--- a/Libraries/LibMedia/VideoPresentation/VideoPresentationClientConnection.cpp+++ b/Libraries/LibMedia/VideoPresentation/VideoPresentationClientConnection.cpp@@ -117,7 +117,7 @@ void VideoPresentationClientConnection::update_edge_time_reader(u64 edge_id, Mededge_state->sink->set_time_reader(move(time_reader));}-void VideoPresentationClientConnection::lend_frame(u64 edge_id, u64 lend_id, u32 seek_id, VideoFrameMetadata metadata, Core::AnonymousBuffer pixel_buffer, RefPtr<VideoSurface> surface)+void VideoPresentationClientConnection::lend_frame(u64 edge_id, u64 lend_id, u32 seek_id, VideoFrameMetadata metadata, VideoFramePixels pixels){// The frame may be dropped on any thread.auto release = [weak_connection = make_weak_ref(), edge_id, lend_id] {@@ -131,7 +131,7 @@ void VideoPresentationClientConnection::lend_frame(u64 edge_id, u64 lend_id, u32release();return;}- auto frame_or_error = create_received_video_frame(metadata, move(pixel_buffer), move(surface), edge_state->sender_id, move(release));+ auto frame_or_error = create_received_video_frame(metadata, move(pixels), edge_state->sender_id, move(release));if (frame_or_error.is_error()) {dbgln("VideoPresentation: Dropping a lent frame that does not fit its storage: {}", frame_or_error.error());return;diff --git a/Libraries/LibMedia/VideoPresentation/VideoPresentationClientConnection.h b/Libraries/LibMedia/VideoPresentation/VideoPresentationClientConnection.hindex 6318795800d..adb52748fcd 100644--- a/Libraries/LibMedia/VideoPresentation/VideoPresentationClientConnection.h+++ b/Libraries/LibMedia/VideoPresentation/VideoPresentationClientConnection.h@@ -46,7 +46,7 @@ private:virtual void video_edge_ready(u64 edge_id, Media::MediaTimeReader time_reader) override;virtual void update_edge_time_reader(u64 edge_id, Media::MediaTimeReader time_reader) override;- virtual void lend_frame(u64 edge_id, u64 lend_id, u32 seek_id, Media::VideoFrameMetadata metadata, Core::AnonymousBuffer pixel_buffer, RefPtr<Media::VideoSurface> surface) override;+ virtual void lend_frame(u64 edge_id, u64 lend_id, u32 seek_id, Media::VideoFrameMetadata metadata, Media::VideoFramePixels pixels) override;virtual void edge_status_changed(u64 edge_id, Media::PipelineStatus status, u32 seek_id) override;virtual void notify_clock_resumed(u64 edge_id) override;virtual void seek_sink(u64 edge_id, u32 requested_seek_id, InvalidateHeldData) override;@@ -57,7 +57,6 @@ private:RefPtr<RemoteVideoProducer> consumer;RefPtr<DisplayingVideoSink> sink;Optional<MediaTimeReader> time_reader;- // Tells the frames lent over this edge apart from those of every other edge in this process.u64 sender_id { 0 };u32 expected_requested_seek_id { 0 };};diff --git a/Libraries/LibMedia/VideoPresentation/VideoPresentationServerConnection.cpp b/Libraries/LibMedia/VideoPresentation/VideoPresentationServerConnection.cppindex d94309c8a36..f6772b08ce3 100644--- a/Libraries/LibMedia/VideoPresentation/VideoPresentationServerConnection.cpp+++ b/Libraries/LibMedia/VideoPresentation/VideoPresentationServerConnection.cpp@@ -73,7 +73,7 @@ void VideoPresentationServerConnection::create_registered_video_edge(VideoSinkHaRemoteVideoSink::Delegates delegates;delegates.send_frame = [weak_connection, edge_id](RemoteVideoSink::LentFrame lent_frame) {weak_connection.with_target([&](auto& connection) {- connection.async_lend_frame(edge_id, lent_frame.lend_id, lent_frame.seek_id, lent_frame.metadata, move(lent_frame.pixel_buffer), move(lent_frame.surface));+ connection.async_lend_frame(edge_id, lent_frame.lend_id, lent_frame.seek_id, lent_frame.metadata, move(lent_frame.pixels));});};delegates.send_status = [weak_connection, edge_id](PipelineStatus status, u32 seek_id) {diff --git a/Libraries/LibMediaCodecs/FFmpeg/FFmpegVideoDecoder.cpp b/Libraries/LibMediaCodecs/FFmpeg/FFmpegVideoDecoder.cppindex 3008bb11ae3..5e9507e1bb3 100644--- a/Libraries/LibMediaCodecs/FFmpeg/FFmpegVideoDecoder.cpp+++ b/Libraries/LibMediaCodecs/FFmpeg/FFmpegVideoDecoder.cpp@@ -193,18 +193,13 @@ DecoderErrorOr<NonnullRefPtr<VideoFrame>> FFmpegVideoDecoder::take_next_output(Cif (!acquired_slot.has_value())return DecoderError::with_description(DecoderErrorCategory::TryAgain, "Every video frame slot is held elsewhere"sv);- auto pool_slot_result = m_frame_pool->try_adopt_acquired_slot(*acquired_slot);- if (pool_slot_result.is_error())- return DecoderError::with_description(DecoderErrorCategory::Memory, "Failed to allocate a pooled frame slot reference"sv);- auto pool_slot = pool_slot_result.release_value();-auto yuv_data = DECODER_TRY_ALLOC(Gfx::YUVData::create(size, *bit_depth, subsampling, cicp,acquired_slot->bytes.slice(0, layout.y_size),acquired_slot->bytes.slice(layout.u_offset, layout.u_size),acquired_slot->bytes.slice(layout.v_offset, layout.v_size)));TRY(copy_pending_frame_into(yuv_data));- auto frame = DECODER_TRY_ALLOC(try_make_ref_counted<VideoFrame>(m_pending_frame->timestamp, m_pending_frame->duration, size.to_type<u32>(), *bit_depth, subsampling, cicp, move(pool_slot)));+ auto frame = DECODER_TRY_ALLOC(try_make_ref_counted<VideoFrame>(m_pending_frame->timestamp, m_pending_frame->duration, size.to_type<u32>(), *bit_depth, subsampling, cicp, acquired_slot->storage));m_pending_frame.clear();return frame;}diff --git a/Libraries/LibMediaCodecs/FFmpeg/FFmpegVulkanVideoDecoder.cpp b/Libraries/LibMediaCodecs/FFmpeg/FFmpegVulkanVideoDecoder.cppindex e6f5ea0636a..4208456c90c 100644--- a/Libraries/LibMediaCodecs/FFmpeg/FFmpegVulkanVideoDecoder.cpp+++ b/Libraries/LibMediaCodecs/FFmpeg/FFmpegVulkanVideoDecoder.cpp@@ -417,12 +417,8 @@ DecoderErrorOr<NonnullOwnPtr<FFmpegVulkanVideoDecoder>> FFmpegVulkanVideoDecoderif (frame == nullptr)return DecoderError::with_description(DecoderErrorCategory::Memory, "Failed to allocate FFmpeg frame"sv);- auto surface_pool = VideoFrameSurfacePool::create();- if (surface_pool.is_error())- return DecoderError::format(DecoderErrorCategory::Memory, "Failed to create a video surface pool: {}", surface_pool.release_error());-memory_guard.disarm();- auto decoder = DECODER_TRY_ALLOC(adopt_nonnull_own_or_enomem(new (nothrow) FFmpegVulkanVideoDecoder(functions, *device, codec_context, packet, frame, surface_pool.release_value())));+ auto decoder = DECODER_TRY_ALLOC(adopt_nonnull_own_or_enomem(new (nothrow) FFmpegVulkanVideoDecoder(functions, *device, codec_context, packet, frame)));codec_context->opaque = decoder.ptr();decoder->m_completion_thread = DECODER_TRY_ALLOC(Threading::Thread::try_create("VulkanDecode"sv, [decoder = decoder.ptr()] -> intptr_t {@@ -433,13 +429,12 @@ DecoderErrorOr<NonnullOwnPtr<FFmpegVulkanVideoDecoder>> FFmpegVulkanVideoDecoderreturn decoder;}-FFmpegVulkanVideoDecoder::FFmpegVulkanVideoDecoder(FFmpegFunctions const& functions, VulkanVideoDevice& device, AVCodecContext* codec_context, AVPacket* packet, AVFrame* received_frame, NonnullRefPtr<VideoFrameSurfacePool> surface_pool)+FFmpegVulkanVideoDecoder::FFmpegVulkanVideoDecoder(FFmpegFunctions const& functions, VulkanVideoDevice& device, AVCodecContext* codec_context, AVPacket* packet, AVFrame* received_frame): m_functions(functions), m_device(device), m_codec_context(codec_context), m_packet(packet), m_received_frame(received_frame)- , m_surface_pool(move(surface_pool)){}@@ -458,7 +453,6 @@ FFmpegVulkanVideoDecoder::~FFmpegVulkanVideoDecoder()free_decoding_frames(decoding_frames);m_outputs.clear();- m_surface_pool->shed_storage();m_functions.av_packet_free(&m_packet);m_functions.av_frame_free(&m_received_frame);m_functions.avcodec_free_context(&m_codec_context);@@ -751,15 +745,12 @@ DecoderErrorOr<NonnullRefPtr<VideoFrame>> FFmpegVulkanVideoDecoder::take_next_ou}auto const& output = m_outputs.first();- auto acquired_slot = m_surface_pool->try_acquire(output.surface, output.contents);- if (!acquired_slot.has_value())- return DecoderError::with_description(DecoderErrorCategory::TryAgain, "Every video frame slot is held elsewhere"sv);- auto pool_slot = m_surface_pool->try_adopt_acquired_slot(*acquired_slot);- if (pool_slot.is_error())- return DecoderError::with_description(DecoderErrorCategory::Memory, "Failed to allocate a pooled frame slot reference"sv);+ auto storage = m_surface_budget->try_hold(output.surface, output.contents);+ if (!storage)+ return DecoderError::with_description(DecoderErrorCategory::TryAgain, "Every video surface the decoder may hand out is held elsewhere"sv);auto cicp = coding_independent_code_points_of(m_functions, *m_codec_context, container_cicp);- auto frame = DECODER_TRY_ALLOC(try_make_ref_counted<VideoFrame>(output.timing.timestamp, output.timing.duration, output.size, output.bit_depth, Subsampling::yuv420(), cicp, pool_slot.release_value()));+ auto frame = DECODER_TRY_ALLOC(try_make_ref_counted<VideoFrame>(output.timing.timestamp, output.timing.duration, output.size, output.bit_depth, Subsampling::yuv420(), cicp, storage.release_nonnull()));m_outputs.take_first();return frame;}diff --git a/Libraries/LibMediaCodecs/FFmpeg/FFmpegVulkanVideoDecoder.h b/Libraries/LibMediaCodecs/FFmpeg/FFmpegVulkanVideoDecoder.hindex ae27aa7f588..34eecb3acf9 100644--- a/Libraries/LibMediaCodecs/FFmpeg/FFmpegVulkanVideoDecoder.h+++ b/Libraries/LibMediaCodecs/FFmpeg/FFmpegVulkanVideoDecoder.h@@ -37,7 +37,7 @@ public:static DecoderErrorOr<NonnullOwnPtr<FFmpegVulkanVideoDecoder>> try_create(CodecID, ReadonlyBytes codec_initialization_data);virtual ~FFmpegVulkanVideoDecoder() override;- virtual void set_storage_freed_callback(Function<void()> callback) override { m_surface_pool->set_slot_freed_callback(move(callback)); }+ virtual void set_storage_freed_callback(Function<void()> callback) override { m_surface_budget->set_storage_freed_callback(move(callback)); }virtual void set_output_arrived_callback(Function<void()> callback) override{MutexLocker locker { m_mutex };@@ -63,14 +63,14 @@ private:struct DecodedOutput {NonnullRefPtr<VideoSurface> surface;- // Holds the decoded image out of FFmpeg's pool until the slot the frame goes out in is released.+ // Holds the decoded image out of FFmpeg's pool until the frame it goes out in is released.NonnullRefPtr<VideoSurfaceContents> contents;VideoFramesAwaitingOutput::Frame timing;Gfx::Size<u32> size;u8 bit_depth { 0 };};- FFmpegVulkanVideoDecoder(FFmpegFunctions const&, VulkanVideoDevice&, AVCodecContext*, AVPacket*, AVFrame*, NonnullRefPtr<VideoFrameSurfacePool>);+ FFmpegVulkanVideoDecoder(FFmpegFunctions const&, VulkanVideoDevice&, AVCodecContext*, AVPacket*, AVFrame*);static AVPixelFormat negotiate_pixel_format(AVCodecContext*, AVPixelFormat const*);static int get_buffer(AVCodecContext*, AVFrame*, int flags);@@ -89,7 +89,7 @@ private:AVCodecContext* m_codec_context { nullptr };AVPacket* m_packet { nullptr };AVFrame* m_received_frame { nullptr };- NonnullRefPtr<VideoFrameSurfacePool> m_surface_pool;+ NonnullRefPtr<VideoSurfaceBudget> m_surface_budget { make_ref_counted<VideoSurfaceBudget>() };// Only the caller's thread uses these.VideoFramesAwaitingOutput m_frames_awaiting_output;diff --git a/Libraries/LibMediaCodecs/VideoDecoderClient.ipc b/Libraries/LibMediaCodecs/VideoDecoderClient.ipcindex 63741222e7a..f0fc99bd938 100644--- a/Libraries/LibMediaCodecs/VideoDecoderClient.ipc+++ b/Libraries/LibMediaCodecs/VideoDecoderClient.ipc@@ -1,11 +1,11 @@-#include <LibCore/AnonymousBuffer.h>#include <LibMediaCodecs/DecoderError.h>+#include <LibMediaCodecs/VideoFrame.h>#include <LibMediaCodecs/VideoFrameMetadata.h>#include <LibMediaCodecs/VideoSurface.h>endpoint VideoDecoderClient{- frame_decoded(u64 decoder_id, u32 generation, u64 frame_id, Media::VideoFrameMetadata metadata, Core::AnonymousBuffer pixel_buffer, RefPtr<Media::VideoSurface> surface) =|+ frame_decoded(u64 decoder_id, u32 generation, u64 frame_id, Media::VideoFrameMetadata metadata, Media::VideoFramePixels pixels) =|coded_frame_consumed(u64 decoder_id) =|decoder_failed(u64 decoder_id, u32 generation, Media::DecoderError error) =|decoder_drained(u64 decoder_id, u32 generation) =|diff --git a/Libraries/LibMediaCodecs/VideoDecoderServerConnection.cpp b/Libraries/LibMediaCodecs/VideoDecoderServerConnection.cppindex ee16d9b00ad..ddb950d1311 100644--- a/Libraries/LibMediaCodecs/VideoDecoderServerConnection.cpp+++ b/Libraries/LibMediaCodecs/VideoDecoderServerConnection.cpp@@ -290,16 +290,13 @@ private:void send_frame(NonnullRefPtr<VideoFrame> frame){auto metadata = VideoFrameMetadata::for_frame(*frame);- auto surface = frame->surface();- Core::AnonymousBuffer pixel_buffer;- if (!surface)- pixel_buffer = frame->pixel_buffer();+ auto pixels = frame->storage()->pixels();auto should_close_connection = false;m_connection.with_target([&](auto& connection) {// The frame is held before the client hears of it, so that its release cannot arrive first.auto frame_id = connection.hold_frame_until_released(move(frame));- connection.async_frame_decoded(m_decoder_id, m_generation, frame_id, metadata, move(pixel_buffer), move(surface));+ connection.async_frame_decoded(m_decoder_id, m_generation, frame_id, metadata, move(pixels));should_close_connection = connection.should_close_after_decoding_frame();});if (should_close_connection)diff --git a/Libraries/LibMediaCodecs/VideoFrame.cpp b/Libraries/LibMediaCodecs/VideoFrame.cppindex b6a3a3dbcf2..a63c0d5212e 100644--- a/Libraries/LibMediaCodecs/VideoFrame.cpp+++ b/Libraries/LibMediaCodecs/VideoFrame.cpp@@ -26,7 +26,7 @@ VideoFrame::VideoFrame(u8 bit_depth,Subsampling subsampling,CodingIndependentCodePoints cicp,- BackingStorage backing_storage)+ NonnullRefPtr<VideoFrameStorage> storage): m_id(next_frame_id()), m_timestamp(timestamp), m_duration(duration)@@ -34,31 +34,25 @@ VideoFrame::VideoFrame(, m_bit_depth(bit_depth), m_subsampling(subsampling), m_cicp(cicp)- , m_backing_storage(move(backing_storage))+ , m_storage(move(storage)){}+VideoFrame::~VideoFrame() = default;+RefPtr<VideoSurface> VideoFrame::surface() const{- return m_backing_storage.visit(- [](NonnullRefPtr<PooledVideoFrameSlot> const& slot) -> RefPtr<VideoSurface> { return slot->ledger().slot_surface(slot->slot_index()); },- [](NonnullRefPtr<ReceivedVideoFrameStorage> const& storage) -> RefPtr<VideoSurface> { return storage->surface(); });+ return m_storage->surface();}Core::AnonymousBuffer VideoFrame::pixel_buffer() const{- return m_backing_storage.visit(- [](NonnullRefPtr<PooledVideoFrameSlot> const& slot) -> Core::AnonymousBuffer {- if (slot->ledger().slot_surface(slot->slot_index()))- return {};- return slot->ledger().slot_buffer(slot->slot_index());- },- [](NonnullRefPtr<ReceivedVideoFrameStorage> const& storage) { return storage->pixel_buffer(); });+ return m_storage->pixel_buffer();}Optional<Gfx::YUVData> VideoFrame::yuv_data() const{- auto yuv_data = yuv_data_in_slot_buffer(pixel_buffer(), m_size.to_type<int>(), m_bit_depth, m_subsampling, m_cicp);+ auto yuv_data = yuv_data_in_buffer(pixel_buffer(), m_size.to_type<int>(), m_bit_depth, m_subsampling, m_cicp);if (yuv_data.is_error())return {};return yuv_data.release_value();@@ -74,20 +68,4 @@ ErrorOr<NonnullRefPtr<Gfx::Bitmap>> VideoFrame::to_bitmap() constreturn yuv_data->to_bitmap();}-VideoFrame::~VideoFrame() = default;--PooledVideoFrameSlot const* VideoFrame::pool_slot() const-{- if (!m_backing_storage.has<NonnullRefPtr<PooledVideoFrameSlot>>())- return nullptr;- return m_backing_storage.get<NonnullRefPtr<PooledVideoFrameSlot>>().ptr();-}--ReceivedVideoFrameStorage const* VideoFrame::received_storage() const-{- if (auto const* storage = m_backing_storage.get_pointer<NonnullRefPtr<ReceivedVideoFrameStorage>>())- return storage->ptr();- return nullptr;-}-}diff --git a/Libraries/LibMediaCodecs/VideoFrame.h b/Libraries/LibMediaCodecs/VideoFrame.hindex ff0b227b996..fa4e11354cb 100644--- a/Libraries/LibMediaCodecs/VideoFrame.h+++ b/Libraries/LibMediaCodecs/VideoFrame.h@@ -20,15 +20,14 @@namespace Media {-class PooledVideoFrameSlot;-class ReceivedVideoFrameStorage;+class VideoFrameStorage;class VideoSurface;+using VideoFramePixels = Variant<Core::AnonymousBuffer, NonnullRefPtr<VideoSurface>>;+class MEDIACODECS_API VideoFrame final : public AtomicRefCounted<VideoFrame> {public:- using BackingStorage = Variant<NonnullRefPtr<PooledVideoFrameSlot>, NonnullRefPtr<ReceivedVideoFrameStorage>>;-VideoFrame(AK::Duration timestamp,AK::Duration duration,@@ -36,7 +35,7 @@ public:u8 bit_depth,Subsampling subsampling,CodingIndependentCodePoints cicp,- BackingStorage backing_storage);+ NonnullRefPtr<VideoFrameStorage>);~VideoFrame();// Tells this frame apart from every other frame in this process, including ones whose storage it shares.@@ -57,21 +56,19 @@ public:Subsampling subsampling() const { return m_subsampling; }CodingIndependentCodePoints const& cicp() const { return m_cicp; }- // A view of the planes in the backing slot's buffer, absent when a platform surface holds them instead.+ // A view of the planes in the frame's buffer, absent when a surface holds them instead.Optional<Gfx::YUVData> yuv_data() const;- // The platform surface holding the frame's pixels, null when they live in the backing slot's buffer.+ // The surface holding the frame's pixels, null when they are in a buffer instead.RefPtr<VideoSurface> surface() const;- // The shared memory holding the frame's pixels, invalid when a surface holds them instead.+ // The buffer holding the frame's pixels, invalid when a surface holds them instead.Core::AnonymousBuffer pixel_buffer() const;// Converts the pixels to RGBA in memory, wherever they are, if this process can read them.ErrorOr<NonnullRefPtr<Gfx::Bitmap>> to_bitmap() const;- BackingStorage const& backing_storage() const { return m_backing_storage; }- PooledVideoFrameSlot const* pool_slot() const;- ReceivedVideoFrameStorage const* received_storage() const;+ NonnullRefPtr<VideoFrameStorage> const& storage() const { return m_storage; }private:u64 m_id { 0 };@@ -81,7 +78,7 @@ private:u8 m_bit_depth;Subsampling m_subsampling;CodingIndependentCodePoints m_cicp;- BackingStorage m_backing_storage;+ NonnullRefPtr<VideoFrameStorage> m_storage;};}diff --git a/Libraries/LibMediaCodecs/VideoFrameMetadata.h b/Libraries/LibMediaCodecs/VideoFrameMetadata.hindex 0ee5f6378e2..dca44b52de3 100644--- a/Libraries/LibMediaCodecs/VideoFrameMetadata.h+++ b/Libraries/LibMediaCodecs/VideoFrameMetadata.h@@ -17,14 +17,11 @@namespace Media {-// Everything about a decoded frame that a consumer in another process needs to present it, apart from its pixels.struct MEDIACODECS_API VideoFrameMetadata {static VideoFrameMetadata for_frame(VideoFrame const&);bool is_valid() const;- AK::Duration conservative_end() const { return VideoFrame::conservative_end_of(timestamp, duration); }-AK::Duration timestamp;AK::Duration duration;Gfx::IntSize size;diff --git a/Libraries/LibMediaCodecs/VideoFramePool.cpp b/Libraries/LibMediaCodecs/VideoFramePool.cppindex bf9990dcd99..59cf2e69c7e 100644--- a/Libraries/LibMediaCodecs/VideoFramePool.cpp+++ b/Libraries/LibMediaCodecs/VideoFramePool.cpp@@ -13,18 +13,36 @@namespace Media {-ErrorOr<NonnullRefPtr<VideoFramePool>> VideoFramePool::create(size_t byte_budget)+VideoFrameStorage::VideoFrameStorage(VideoFramePixels pixels, u64 sender_id, Function<void()> on_release)+ : m_pixels(move(pixels))+ , m_sender_id(sender_id)+ , m_on_release(move(on_release)){- return adopt_nonnull_ref_or_enomem(new (nothrow) VideoFramePool(byte_budget));}-VideoFrameEntryLedger::~VideoFrameEntryLedger() = default;+VideoFrameStorage::~VideoFrameStorage()+{+ if (m_on_release)+ m_on_release();+}-void VideoFrameEntryLedger::set_slot_freed_callback(Function<void()> slot_freed_callback)+Core::AnonymousBuffer VideoFrameStorage::pixel_buffer() const{- MutexLocker locker { m_mutex };- VERIFY(m_slots.is_empty());- m_slot_freed_callback = move(slot_freed_callback);+ if (auto const* buffer = m_pixels.get_pointer<Core::AnonymousBuffer>())+ return *buffer;+ return {};+}++RefPtr<VideoSurface> VideoFrameStorage::surface() const+{+ if (auto const* surface = m_pixels.get_pointer<NonnullRefPtr<VideoSurface>>())+ return *surface;+ return nullptr;+}++ErrorOr<NonnullRefPtr<VideoFramePool>> VideoFramePool::create(size_t byte_budget)+{+ return adopt_nonnull_ref_or_enomem(new (nothrow) VideoFramePool(byte_budget));}VideoFramePool::VideoFramePool(size_t byte_budget)@@ -32,6 +50,15 @@ VideoFramePool::VideoFramePool(size_t byte_budget){}+VideoFramePool::~VideoFramePool() = default;++void VideoFramePool::set_slot_freed_callback(Function<void()> slot_freed_callback)+{+ MutexLocker locker { m_mutex };+ VERIFY(m_slots.is_empty());+ m_slot_freed_callback = move(slot_freed_callback);+}+Optional<VideoFramePool::AcquiredSlot> VideoFramePool::try_acquire(size_t byte_count){VERIFY(byte_count > 0);@@ -42,7 +69,7 @@ Optional<VideoFramePool::AcquiredSlot> VideoFramePool::try_acquire(size_t byte_cOptional<u32> free_slot_index;for (u32 index = 0; index < m_slots.size(); index++) {auto const& slot = m_slots[index];- if (slot.hold_count != 0)+ if (slot.is_held)continue;if (!free_slot_index.has_value())free_slot_index = index;@@ -60,23 +87,22 @@ Optional<VideoFramePool::AcquiredSlot> VideoFramePool::try_acquire(size_t byte_cif (!free_slot_index.has_value()) {if (m_slots.size() >= MAX_SLOT_COUNT)return {};- free_slot_index = try_grow_while_locked();- if (!free_slot_index.has_value())+ if (m_slots.try_append({}).is_error())return {};+ free_slot_index = static_cast<u32>(m_slots.size() - 1);}chosen_slot = &m_slots[*free_slot_index];- auto buffer_size = byte_count;- auto allocated_bytes_after = m_allocated_bytes - chosen_slot->buffer.size() + buffer_size;+ auto allocated_bytes_after = m_allocated_bytes - chosen_slot->buffer.size() + byte_count;if (allocated_bytes_after > m_byte_budget) {if (held_slot_count_while_locked() >= MIN_SLOT_COUNT) {- dbgln_if(VIDEO_FRAME_POOL_DEBUG, "VideoFramePool: Refusing to allocate {} bytes over the budget of {}", buffer_size, m_byte_budget);+ dbgln_if(VIDEO_FRAME_POOL_DEBUG, "VideoFramePool: Refusing to allocate {} bytes over the budget of {}", byte_count, m_byte_budget);return {};}dbgln_if(VIDEO_FRAME_POOL_DEBUG, "VideoFramePool: Exceeding the byte budget ({} > {}) to keep the minimum {} slots live", allocated_bytes_after, m_byte_budget, MIN_SLOT_COUNT);}- auto buffer_result = Core::AnonymousBuffer::create_with_size(buffer_size);+ auto buffer_result = Core::AnonymousBuffer::create_with_size(byte_count);if (buffer_result.is_error())return {};drop_slot_storage_while_locked(*chosen_slot);@@ -84,55 +110,26 @@ Optional<VideoFramePool::AcquiredSlot> VideoFramePool::try_acquire(size_t byte_cm_allocated_bytes += chosen_slot->buffer.size();}- begin_hold_while_locked(*chosen_slot);+ m_shed_storage_on_release = false;+ chosen_slot->is_held = true;free_excess_buffers_while_locked();auto slot_index = static_cast<u32>(chosen_slot - m_slots.data());+ auto storage = make_ref_counted<VideoFrameStorage>(chosen_slot->buffer, 0, [pool = NonnullRefPtr { *this }, slot_index] {+ pool->release_slot(slot_index);+ });return AcquiredSlot {- .index = slot_index,+ .storage = move(storage),.bytes = { chosen_slot->buffer.data<u8>(), byte_count },};}-ErrorOr<NonnullRefPtr<PooledVideoFrameSlot>> VideoFramePool::try_adopt_acquired_slot(AcquiredSlot const& acquired_slot)-{- return try_adopt_slot(acquired_slot.index);-}--void VideoFrameEntryLedger::begin_hold_while_locked(Slot& slot)-{- m_shed_storage_on_release = false;- slot.hold_count = 1;-}--Optional<u32> VideoFrameEntryLedger::try_grow_while_locked()-{- if (m_slots.try_append({}).is_error())- return {};- return static_cast<u32>(m_slots.size() - 1);-}--RefPtr<VideoSurface> VideoFrameEntryLedger::slot_surface(u32 slot_index) const-{- MutexLocker locker { m_mutex };- VERIFY(m_slots[slot_index].hold_count > 0);- return m_slots[slot_index].surface;-}--ErrorOr<NonnullRefPtr<PooledVideoFrameSlot>> VideoFrameEntryLedger::try_adopt_slot(u32 slot_index)-{- auto slot_result = try_make_ref_counted<PooledVideoFrameSlot>(*this, slot_index);- if (slot_result.is_error())- release_hold(slot_index);- return slot_result;-}--u32 VideoFrameEntryLedger::held_slot_count_while_locked() const+u32 VideoFramePool::held_slot_count_while_locked() const{u32 held_count = 0;for (auto const& slot : m_slots)- held_count += slot.hold_count != 0;+ held_count += slot.is_held;return held_count;}@@ -149,7 +146,7 @@ void VideoFramePool::free_excess_buffers_while_locked()while (m_allocated_bytes > m_byte_budget) {Slot* largest_free_slot = nullptr;for (auto& slot : m_slots) {- if (slot.hold_count != 0 || !slot.buffer.is_valid())+ if (slot.is_held || !slot.buffer.is_valid())continue;if (largest_free_slot == nullptr || slot.buffer.size() > largest_free_slot->buffer.size())largest_free_slot = &slot;@@ -160,147 +157,102 @@ void VideoFramePool::free_excess_buffers_while_locked()}}-void VideoFrameEntryLedger::shed_storage()+void VideoFramePool::shed_storage(){MutexLocker locker { m_mutex };m_shed_storage_on_release = true;for (auto& slot : m_slots) {- if (slot.hold_count == 0)+ if (!slot.is_held)drop_slot_storage_while_locked(slot);}}-void VideoFrameEntryLedger::add_hold(u32 slot_index)-{- MutexLocker locker { m_mutex };- VERIFY(m_slots[slot_index].hold_count > 0);- m_slots[slot_index].hold_count++;-}--void VideoFrameEntryLedger::release_hold(u32 slot_index)+void VideoFramePool::release_slot(u32 slot_index){- // The surface and its contents go outside the lock, and before the decoder hears that the slot is free, so that it- // finds the surface free to decode into again by the time it looks.- RefPtr<VideoSurface> released_surface;- RefPtr<VideoSurfaceContents> released_contents;{MutexLocker locker { m_mutex };auto& slot = m_slots[slot_index];- VERIFY(slot.hold_count > 0);- if (--slot.hold_count > 0)- return;- released_surface = move(slot.surface);- released_contents = move(slot.contents);+ VERIFY(slot.is_held);+ slot.is_held = false;if (m_shed_storage_on_release)drop_slot_storage_while_locked(slot);}- released_contents = nullptr;- released_surface = nullptr;if (m_slot_freed_callback)m_slot_freed_callback();}-Core::AnonymousBuffer VideoFrameEntryLedger::slot_buffer(u32 slot_index) const-{- MutexLocker locker { m_mutex };- VERIFY(m_slots[slot_index].hold_count > 0);- return m_slots[slot_index].buffer;-}-size_t VideoFramePool::allocated_byte_count() const{MutexLocker locker { m_mutex };return m_allocated_bytes;}-ErrorOr<NonnullRefPtr<VideoFrameSurfacePool>> VideoFrameSurfacePool::create()-{- return adopt_nonnull_ref_or_enomem(new (nothrow) VideoFrameSurfacePool());-}+VideoSurfaceBudget::~VideoSurfaceBudget() = default;-Optional<VideoFrameSurfacePool::AcquiredSlot> VideoFrameSurfacePool::try_acquire(NonnullRefPtr<VideoSurface> const& surface, NonnullRefPtr<VideoSurfaceContents> contents)+void VideoSurfaceBudget::set_storage_freed_callback(Function<void()> storage_freed_callback){MutexLocker locker { m_mutex };-- Optional<u32> free_slot_index;- for (u32 index = 0; index < m_slots.size(); index++) {- if (m_slots[index].hold_count == 0) {- free_slot_index = index;- break;- }- }- if (!free_slot_index.has_value()) {- if (m_slots.size() >= MAX_HELD_SLOT_COUNT)- return {};- free_slot_index = try_grow_while_locked();- if (!free_slot_index.has_value())- return {};- }-- auto& slot = m_slots[free_slot_index.value()];- slot.surface = surface;- slot.contents = move(contents);- begin_hold_while_locked(slot);- return AcquiredSlot { .index = free_slot_index.value() };+ VERIFY(m_held_surface_count == 0);+ m_storage_freed_callback = move(storage_freed_callback);}-ErrorOr<NonnullRefPtr<PooledVideoFrameSlot>> VideoFrameSurfacePool::try_adopt_acquired_slot(AcquiredSlot const& acquired_slot)-{- return try_adopt_slot(acquired_slot.index);-}--ReceivedVideoFrameStorage::ReceivedVideoFrameStorage(Core::AnonymousBuffer pixel_buffer, RefPtr<VideoSurface> surface, u64 sender_id, Function<void()> on_release)- : m_pixel_buffer(move(pixel_buffer))- , m_surface(move(surface))- , m_sender_id(sender_id)- , m_on_release(move(on_release))+RefPtr<VideoFrameStorage> VideoSurfaceBudget::try_hold(NonnullRefPtr<VideoSurface> surface, NonnullRefPtr<VideoSurfaceContents> contents){+ {+ MutexLocker locker { m_mutex };+ if (m_held_surface_count >= MAX_HELD_SURFACE_COUNT)+ return nullptr;+ m_held_surface_count++;+ }+ // The contents go before the decoder hears that the surface is free, so that it finds the surface free to decode+ // into again by the time it looks.+ return make_ref_counted<VideoFrameStorage>(move(surface), 0, [budget = NonnullRefPtr { *this }, contents = RefPtr<VideoSurfaceContents> { move(contents) }]() mutable {+ contents = nullptr;+ budget->release_hold();+ });}-ReceivedVideoFrameStorage::~ReceivedVideoFrameStorage()+void VideoSurfaceBudget::release_hold(){- if (m_on_release)- m_on_release();+ {+ MutexLocker locker { m_mutex };+ VERIFY(m_held_surface_count > 0);+ m_held_surface_count--;+ }+ if (m_storage_freed_callback)+ m_storage_freed_callback();}-ErrorOr<Gfx::YUVData> yuv_data_in_slot_buffer(Core::AnonymousBuffer const& slot_buffer, Gfx::IntSize size, u8 bit_depth, Subsampling subsampling, CodingIndependentCodePoints const& cicp)+ErrorOr<Gfx::YUVData> yuv_data_in_buffer(Core::AnonymousBuffer const& buffer, Gfx::IntSize size, u8 bit_depth, Subsampling subsampling, CodingIndependentCodePoints const& cicp){- if (!slot_buffer.is_valid() || slot_buffer.size() == 0)+ if (!buffer.is_valid() || buffer.size() == 0)return Error::from_string_literal("Invalid video frame buffer");auto layout = TRY(frame_plane_layout(size, bit_depth, subsampling));- if (layout.total_byte_count > slot_buffer.size())+ if (layout.total_byte_count > buffer.size())return Error::from_string_literal("Video frame format does not fit its buffer");- auto bytes = Bytes { const_cast<u8*>(slot_buffer.data<u8 const>()), slot_buffer.size() };+ auto bytes = Bytes { const_cast<u8*>(buffer.data<u8 const>()), buffer.size() };return Gfx::YUVData::create(size, bit_depth, subsampling, cicp, bytes.slice(0, layout.y_size), bytes.slice(layout.u_offset, layout.u_size), bytes.slice(layout.v_offset, layout.v_size));}-ErrorOr<NonnullRefPtr<VideoFrame>> create_received_video_frame(VideoFrameMetadata const& metadata, Core::AnonymousBuffer pixel_buffer, RefPtr<VideoSurface> surface, u64 sender_id, Function<void()> on_release)+ErrorOr<NonnullRefPtr<VideoFrame>> create_received_video_frame(VideoFrameMetadata const& metadata, VideoFramePixels pixels, u64 sender_id, Function<void()> on_release){- auto storage_or_error = try_make_ref_counted<ReceivedVideoFrameStorage>(move(pixel_buffer), move(surface), sender_id, move(on_release));- if (storage_or_error.is_error()) {- if (on_release)- on_release();- return storage_or_error.release_error();- }- auto storage = storage_or_error.release_value();+ auto storage = make_ref_counted<VideoFrameStorage>(move(pixels), sender_id, move(on_release));if (!metadata.is_valid())return Error::from_string_literal("Video frame metadata describes a frame that could not have been decoded");- if (auto const& received_surface = storage->surface()) {- if (storage->pixel_buffer().is_valid())- return Error::from_string_literal("Video frame was sent with both a surface and a pixel buffer");- auto surface_size = received_surface->size();+ if (auto surface = storage->surface()) {+ auto surface_size = surface->size();if (metadata.subsampling != Subsampling::yuv420() || metadata.size.width() > surface_size.width() || metadata.size.height() > surface_size.height())return Error::from_string_literal("Video frame metadata does not match its surface");} else {- TRY(yuv_data_in_slot_buffer(storage->pixel_buffer(), metadata.size, metadata.bit_depth, metadata.subsampling, metadata.cicp));+ TRY(yuv_data_in_buffer(storage->pixel_buffer(), metadata.size, metadata.bit_depth, metadata.subsampling, metadata.cicp));}- return try_make_ref_counted<VideoFrame>(metadata.timestamp, metadata.duration, metadata.size.to_type<u32>(), metadata.bit_depth, metadata.subsampling, metadata.cicp, move(storage));+ return make_ref_counted<VideoFrame>(metadata.timestamp, metadata.duration, metadata.size.to_type<u32>(), metadata.bit_depth, metadata.subsampling, metadata.cicp, move(storage));}}diff --git a/Libraries/LibMediaCodecs/VideoFramePool.h b/Libraries/LibMediaCodecs/VideoFramePool.hindex 065f6880002..92a7799e658 100644--- a/Libraries/LibMediaCodecs/VideoFramePool.h+++ b/Libraries/LibMediaCodecs/VideoFramePool.h@@ -15,161 +15,108 @@#include <LibCore/AnonymousBuffer.h>#include <LibGfx/YUVData.h>#include <LibMediaCodecs/Export.h>+#include <LibMediaCodecs/VideoFrame.h>#include <LibMediaCodecs/VideoFrameMetadata.h>#include <LibMediaCodecs/VideoSurface.h>namespace Media {-class PooledVideoFrameSlot;--// The lifetime bookkeeping shared by every kind of frame pool: each slot stays held while any frame stored in it is.-class MEDIACODECS_API VideoFrameEntryLedger : public AtomicRefCounted<VideoFrameEntryLedger> {+// Holds a frame's pixels until the last frame sharing them is dropped, then runs the release callback once, on+// whichever thread dropped it.+class MEDIACODECS_API VideoFrameStorage final : public AtomicRefCounted<VideoFrameStorage> {public:- virtual ~VideoFrameEntryLedger();-- // The callback runs on whichever thread frees a slot, without the ledger's lock held, and may run concurrently- // with itself when separate slots are freed at once.- void set_slot_freed_callback(Function<void()>);-- void add_hold(u32 slot_index);- void release_hold(u32 slot_index);-- // Marks each slot's storage for freeing when its hold count drops to zero. This marker is cleared upon the- // next acquire.- void shed_storage();-- // The buffer backing a held slot, for lending to consumer processes.- Core::AnonymousBuffer slot_buffer(u32 slot_index) const;-- // The surface backing a held slot, null when the slot's pixels live in its buffer instead.- RefPtr<VideoSurface> slot_surface(u32 slot_index) const;--protected:- VideoFrameEntryLedger() = default;+ VideoFrameStorage(VideoFramePixels, u64 sender_id, Function<void()> on_release);+ ~VideoFrameStorage();- ErrorOr<NonnullRefPtr<PooledVideoFrameSlot>> try_adopt_slot(u32 slot_index);-- struct Slot {- Core::AnonymousBuffer buffer;- // Only a held slot has a surface, and the contents the decoder gave with it, which go with the last hold.- RefPtr<VideoSurface> surface;- RefPtr<VideoSurfaceContents> contents;- u32 hold_count { 0 };- };-- // Appends a slot with no payload, for a pool that has no free slot to reuse.- Optional<u32> try_grow_while_locked();-- virtual void drop_slot_storage_while_locked(Slot&) { }-- u32 held_slot_count_while_locked() const;- void begin_hold_while_locked(Slot&);-- mutable Mutex m_mutex;- Vector<Slot> m_slots;+ VideoFramePixels const& pixels() const { return m_pixels; }+ // Tells the frames one peer sent apart from every other peer's in this process, and is 0 for frames decoded here.+ u64 sender_id() const { return m_sender_id; }+ // Invalid when a surface holds the pixels instead.+ Core::AnonymousBuffer pixel_buffer() const;+ // Null when a buffer holds the pixels instead.+ RefPtr<VideoSurface> surface() const;private:- Function<void()> m_slot_freed_callback;- bool m_shed_storage_on_release { false };+ VideoFramePixels m_pixels;+ u64 m_sender_id { 0 };+ Function<void()> m_on_release;};-// A pool of shared-memory framebuffers that are allocated on demand up to a limited budget. A slot's buffer is reused-// until a different size is needed.-class MEDIACODECS_API VideoFramePool final : public VideoFrameEntryLedger {+// A pool of shared-memory framebuffers, allocated on demand within a byte budget that the first MIN_SLOT_COUNT+// held slots may exceed.+class MEDIACODECS_API VideoFramePool final : public AtomicRefCounted<VideoFramePool> {public:static constexpr u32 MIN_SLOT_COUNT = 4;static constexpr u32 MAX_SLOT_COUNT = 8;static constexpr size_t DEFAULT_BYTE_BUDGET = 256 * MiB;static ErrorOr<NonnullRefPtr<VideoFramePool>> create(size_t byte_budget = DEFAULT_BYTE_BUDGET);+ ~VideoFramePool();++ // The callback runs on whichever thread frees a slot, without the pool's lock held, and may run concurrently+ // with itself when separate slots are freed at once.+ void set_slot_freed_callback(Function<void()>);struct AcquiredSlot {- u32 index { 0 };+ NonnullRefPtr<VideoFrameStorage> storage;Bytes bytes;};// Gets a free slot with the requested capacity if it is available, reallocating the buffer if needed.Optional<AcquiredSlot> try_acquire(size_t byte_count);- ErrorOr<NonnullRefPtr<PooledVideoFrameSlot>> try_adopt_acquired_slot(AcquiredSlot const&);++ // Marks each slot's storage for freeing when its hold count drops to zero. This marker is cleared upon the+ // next acquire.+ void shed_storage();size_t allocated_byte_count() const;private:- explicit VideoFramePool(size_t byte_budget);+ struct Slot {+ Core::AnonymousBuffer buffer;+ bool is_held { false };+ };- void drop_slot_storage_while_locked(Slot&) override;+ explicit VideoFramePool(size_t byte_budget);+ void release_slot(u32 slot_index);+ u32 held_slot_count_while_locked() const;+ void drop_slot_storage_while_locked(Slot&);void free_excess_buffers_while_locked();+ mutable Mutex m_mutex;+ Vector<Slot> m_slots;+ Function<void()> m_slot_freed_callback;+ bool m_shed_storage_on_release { false };+size_t const m_byte_budget { 0 };size_t m_allocated_bytes { 0 };};-// A pool of surfaces produced by a hardware decoder. The decoder allocates and recycles them, so this pool only holds-// each surface for as long as a frame decoded into it is held. The held slot count is what bounds how many frames a-// hardware decoder may have in flight, since the platform's own allocator will keep handing out surfaces indefinitely.-class MEDIACODECS_API VideoFrameSurfacePool final : public VideoFrameEntryLedger {+class MEDIACODECS_API VideoSurfaceBudget final : public AtomicRefCounted<VideoSurfaceBudget> {public:- static constexpr u32 MAX_HELD_SLOT_COUNT = 8;+ static constexpr u32 MAX_HELD_SURFACE_COUNT = 8;- static ErrorOr<NonnullRefPtr<VideoFrameSurfacePool>> create();+ ~VideoSurfaceBudget();- struct AcquiredSlot {- u32 index { 0 };- };- // Gets a free slot for the surface, holding it and the contents the decoder gave with it.- Optional<AcquiredSlot> try_acquire(NonnullRefPtr<VideoSurface> const&, NonnullRefPtr<VideoSurfaceContents>);- ErrorOr<NonnullRefPtr<PooledVideoFrameSlot>> try_adopt_acquired_slot(AcquiredSlot const&);--private:- VideoFrameSurfacePool() = default;-};+ // The callback runs on whichever thread releases a surface, without the budget's lock held, and may run+ // concurrently with itself.+ void set_storage_freed_callback(Function<void()>);-// A strong reference to a slot in a frame pool to be used within a single process.-class PooledVideoFrameSlot : public AtomicRefCounted<PooledVideoFrameSlot> {-public:- PooledVideoFrameSlot(NonnullRefPtr<VideoFrameEntryLedger> ledger, u32 slot_index)- : m_ledger(move(ledger))- , m_slot_index(slot_index)- {- }-- ~PooledVideoFrameSlot()- {- m_ledger->release_hold(m_slot_index);- }-- VideoFrameEntryLedger& ledger() const { return m_ledger; }- u32 slot_index() const { return m_slot_index; }+ // Null once MAX_HELD_SURFACE_COUNT surfaces are held, until one is released.+ RefPtr<VideoFrameStorage> try_hold(NonnullRefPtr<VideoSurface>, NonnullRefPtr<VideoSurfaceContents>);private:- NonnullRefPtr<VideoFrameEntryLedger> m_ledger;- u32 m_slot_index { 0 };-};+ void release_hold();-// The storage a frame received from another process arrived with, held until the frame is released. Exactly one of the-// pixel buffer and the surface holds the frame's pixels.-class MEDIACODECS_API ReceivedVideoFrameStorage : public AtomicRefCounted<ReceivedVideoFrameStorage> {-public:- ReceivedVideoFrameStorage(Core::AnonymousBuffer pixel_buffer, RefPtr<VideoSurface> surface, u64 sender_id, Function<void()> on_release);- ~ReceivedVideoFrameStorage();-- Core::AnonymousBuffer const& pixel_buffer() const { return m_pixel_buffer; }- RefPtr<VideoSurface> const& surface() const { return m_surface; }- // Names the peer the frame came from, so that anything kept by an ID the peer chose is never shared with another.- u64 sender_id() const { return m_sender_id; }--private:- Core::AnonymousBuffer m_pixel_buffer;- RefPtr<VideoSurface> m_surface;- u64 m_sender_id { 0 };- Function<void()> m_on_release;+ Mutex m_mutex;+ u32 m_held_surface_count { 0 };+ Function<void()> m_storage_freed_callback;};// Views the planes laid out within a frame's buffer, failing if they do not fit its capacity.-MEDIACODECS_API ErrorOr<Gfx::YUVData> yuv_data_in_slot_buffer(Core::AnonymousBuffer const&, Gfx::IntSize, u8 bit_depth, Subsampling, CodingIndependentCodePoints const&);+MEDIACODECS_API ErrorOr<Gfx::YUVData> yuv_data_in_buffer(Core::AnonymousBuffer const&, Gfx::IntSize, u8 bit_depth, Subsampling, CodingIndependentCodePoints const&);-// Builds a frame from the storage another process sent along with its metadata, checking that the storage can hold-// such a frame. The release callback runs once the frame is dropped, or right away if it cannot be built.-MEDIACODECS_API ErrorOr<NonnullRefPtr<VideoFrame>> create_received_video_frame(VideoFrameMetadata const&, Core::AnonymousBuffer pixel_buffer, RefPtr<VideoSurface>, u64 sender_id, Function<void()> on_release);+// Refuses a frame the pixels could not hold, releasing them.+MEDIACODECS_API ErrorOr<NonnullRefPtr<VideoFrame>> create_received_video_frame(VideoFrameMetadata const&, VideoFramePixels, u64 sender_id, Function<void()> on_release);}diff --git a/Libraries/LibMediaCodecs/VideoSurface.cpp b/Libraries/LibMediaCodecs/VideoSurface.cppindex 0032f3973c3..843134df179 100644--- a/Libraries/LibMediaCodecs/VideoSurface.cpp+++ b/Libraries/LibMediaCodecs/VideoSurface.cpp@@ -68,12 +68,8 @@ ErrorOr<NonnullRefPtr<VideoSurface>> VideoSurface::create_from_dma_buf(u64 id, Gnamespace IPC {template<>-ErrorOr<void> encode(Encoder& encoder, RefPtr<Media::VideoSurface> const& surface)+ErrorOr<void> encode([[maybe_unused]] Encoder& encoder, [[maybe_unused]] NonnullRefPtr<Media::VideoSurface> const& surface){- TRY(encoder.encode(surface != nullptr));- if (surface == nullptr)- return {};-#if defined(AK_OS_MACOS)TRY(encoder.append_attachment(Attachment::from_mach_port(surface->create_mach_port(), Core::MachPort::MessageRight::MoveSend)));return {};@@ -87,11 +83,8 @@ ErrorOr<void> encode(Encoder& encoder, RefPtr<Media::VideoSurface> const& surfac}template<>-ErrorOr<RefPtr<Media::VideoSurface>> decode(Decoder& decoder)+ErrorOr<NonnullRefPtr<Media::VideoSurface>> decode([[maybe_unused]] Decoder& decoder){- if (!TRY(decoder.decode<bool>()))- return RefPtr<Media::VideoSurface> {};-#if defined(AK_OS_MACOS)auto attachment = TRY(decoder.attachments().try_dequeue());if (attachment.message_right() != Core::MachPort::MessageRight::MoveSend)diff --git a/Libraries/LibMediaCodecs/VideoSurface.h b/Libraries/LibMediaCodecs/VideoSurface.hindex 0e41e69abaf..7011918001e 100644--- a/Libraries/LibMediaCodecs/VideoSurface.h+++ b/Libraries/LibMediaCodecs/VideoSurface.h@@ -33,8 +33,7 @@ public:};// A frame's pixels in memory that a GPU can sample without a copy. Hardware decoders allocate these and recycle a-// bounded set of them, so each carries the identity its recycling is recognized by. The hold on the frame slot a-// surface was handed out in is what keeps its pixels from being decoded over, wherever they are shown.+// bounded set of them, so each carries the identity its recycling is recognized by.class MEDIACODECS_API VideoSurface : public AtomicRefCounted<VideoSurface> {public:~VideoSurface();@@ -90,9 +89,9 @@ private:namespace IPC {template<>-MEDIACODECS_API ErrorOr<void> encode(Encoder&, RefPtr<Media::VideoSurface> const&);+MEDIACODECS_API ErrorOr<void> encode(Encoder&, NonnullRefPtr<Media::VideoSurface> const&);template<>-MEDIACODECS_API ErrorOr<RefPtr<Media::VideoSurface>> decode(Decoder&);+MEDIACODECS_API ErrorOr<NonnullRefPtr<Media::VideoSurface>> decode(Decoder&);}diff --git a/Libraries/LibMediaCodecs/VideoToolbox/VideoToolboxVideoDecoder.h b/Libraries/LibMediaCodecs/VideoToolbox/VideoToolboxVideoDecoder.hindex a6640b0f50a..77c68bfc6d1 100644--- a/Libraries/LibMediaCodecs/VideoToolbox/VideoToolboxVideoDecoder.h+++ b/Libraries/LibMediaCodecs/VideoToolbox/VideoToolboxVideoDecoder.h@@ -38,7 +38,7 @@ public:virtual ~VideoToolboxVideoDecoder() override;- virtual void set_storage_freed_callback(Function<void()> callback) override { m_surface_pool->set_slot_freed_callback(move(callback)); }+ virtual void set_storage_freed_callback(Function<void()> callback) override { m_surface_budget->set_storage_freed_callback(move(callback)); }virtual void set_output_arrived_callback(Function<void()> callback) override { m_output_arrived_callback = move(callback); }virtual DecoderErrorOr<void> receive_coded_data(CodedFrame const&, DecodeIntent) override;@@ -50,8 +50,8 @@ private:struct Session;struct DecodedOutput {NonnullRefPtr<VideoSurface> surface;- // Keeps the media engine from decoding over the surface, from the reorder window until the slot the frame- // goes out in is released.+ // Keeps the media engine from decoding over the surface, from the reorder window until the frame it goes out+ // in is released.NonnullRefPtr<VideoSurfaceContents> contents;AK::Duration timestamp;AK::Duration duration;@@ -61,7 +61,7 @@ private:CodingIndependentCodePoints cicp;};- VideoToolboxVideoDecoder(CodecID, NonnullRefPtr<VideoFrameSurfacePool>, NonnullOwnPtr<FormatState>);+ VideoToolboxVideoDecoder(CodecID, NonnullOwnPtr<FormatState>);DecoderErrorOr<void> ensure_session_for_frame(CodedFrame const&);@@ -76,7 +76,7 @@ private:DecoderErrorOr<NonnullRefPtr<VideoFrame>> adopt_output_while_locked(CodingIndependentCodePoints const& container_cicp, size_t index);CodecID const m_codec_id;- NonnullRefPtr<VideoFrameSurfacePool> m_surface_pool;+ NonnullRefPtr<VideoSurfaceBudget> m_surface_budget { make_ref_counted<VideoSurfaceBudget>() };NonnullOwnPtr<FormatState> m_format_state;OwnPtr<Session> m_session;bool m_reached_end_of_stream { false };diff --git a/Libraries/LibMediaCodecs/VideoToolbox/VideoToolboxVideoDecoder.mm b/Libraries/LibMediaCodecs/VideoToolbox/VideoToolboxVideoDecoder.mmindex 9fd697a78e9..935f7353da2 100644--- a/Libraries/LibMediaCodecs/VideoToolbox/VideoToolboxVideoDecoder.mm+++ b/Libraries/LibMediaCodecs/VideoToolbox/VideoToolboxVideoDecoder.mm@@ -667,17 +667,12 @@ DecoderErrorOr<NonnullOwnPtr<VideoToolboxVideoDecoder>> VideoToolboxVideoDecoderif (codec_type_from_codec_id(codec_id) == 0)return DecoderError::format(DecoderErrorCategory::NotImplemented, "VideoToolbox has no decoder for codec {}", codec_id);- auto surface_pool_result = VideoFrameSurfacePool::create();- if (surface_pool_result.is_error())- return DecoderError::format(DecoderErrorCategory::Memory, "Failed to create a video surface pool: {}", surface_pool_result.release_error());-auto format_state = TRY(create_format_state(codec_id, codec_initialization_data));- return DECODER_TRY_ALLOC(adopt_nonnull_own_or_enomem(new (nothrow) VideoToolboxVideoDecoder(codec_id, surface_pool_result.release_value(), move(format_state))));+ return DECODER_TRY_ALLOC(adopt_nonnull_own_or_enomem(new (nothrow) VideoToolboxVideoDecoder(codec_id, move(format_state))));}-VideoToolboxVideoDecoder::VideoToolboxVideoDecoder(CodecID codec_id, NonnullRefPtr<VideoFrameSurfacePool> surface_pool, NonnullOwnPtr<FormatState> format_state)+VideoToolboxVideoDecoder::VideoToolboxVideoDecoder(CodecID codec_id, NonnullOwnPtr<FormatState> format_state): m_codec_id(codec_id)- , m_surface_pool(move(surface_pool)), m_format_state(move(format_state)){}@@ -687,8 +682,6 @@ VideoToolboxVideoDecoder::~VideoToolboxVideoDecoder()// Tearing down the session hands the media engine's remaining frames to the output callback, which touches// members that would otherwise already be gone by the time the session is destroyed.m_session.clear();-- m_surface_pool->shed_storage();}DecoderErrorOr<void> VideoToolboxVideoDecoder::ensure_session_for_frame(CodedFrame const& coded_frame)@@ -944,20 +937,16 @@ DecoderErrorOr<NonnullRefPtr<VideoFrame>> VideoToolboxVideoDecoder::adopt_output{auto const& output = m_outputs[index];- auto acquired_slot = m_surface_pool->try_acquire(output.surface, output.contents);- if (!acquired_slot.has_value())- return DecoderError::with_description(DecoderErrorCategory::TryAgain, "Every video frame slot is held elsewhere"sv);-- auto pool_slot_result = m_surface_pool->try_adopt_acquired_slot(*acquired_slot);- if (pool_slot_result.is_error())- return DecoderError::with_description(DecoderErrorCategory::Memory, "Failed to allocate a pooled frame slot reference"sv);+ auto storage = m_surface_budget->try_hold(output.surface, output.contents);+ if (!storage)+ return DecoderError::with_description(DecoderErrorCategory::TryAgain, "Every video surface the decoder may hand out is held elsewhere"sv);auto cicp = container_cicp;cicp.adopt_specified_values(output.cicp);return DECODER_TRY_ALLOC(try_make_ref_counted<VideoFrame>(output.timestamp, output.duration, output.size.to_type<u32>(),- output.bit_depth, output.subsampling, cicp, pool_slot_result.release_value()));+ output.bit_depth, output.subsampling, cicp, storage.release_nonnull()));}void VideoToolboxVideoDecoder::flush()diff --git a/Libraries/LibMediaCodecs/WindowsMediaFoundation/WindowsMediaFoundationVideoDecoder.cpp b/Libraries/LibMediaCodecs/WindowsMediaFoundation/WindowsMediaFoundationVideoDecoder.cppindex bdcc8982a98..5ff77098214 100644--- a/Libraries/LibMediaCodecs/WindowsMediaFoundation/WindowsMediaFoundationVideoDecoder.cpp+++ b/Libraries/LibMediaCodecs/WindowsMediaFoundation/WindowsMediaFoundationVideoDecoder.cpp@@ -605,9 +605,6 @@ DecoderErrorOr<NonnullRefPtr<VideoFrame>> WindowsMediaFoundationVideoDecoder::coauto acquired_slot = m_frame_pool->try_acquire(layout.total_byte_count);if (!acquired_slot.has_value())return DecoderError::with_description(DecoderErrorCategory::TryAgain, "Every video frame slot is held elsewhere"sv);- auto pool_slot_result = m_frame_pool->try_adopt_acquired_slot(*acquired_slot);- if (pool_slot_result.is_error())- return DecoderError::with_description(DecoderErrorCategory::Memory, "Failed to allocate a pooled frame slot reference"sv);ComPtr<IMFMediaBuffer> buffer;if (FAILED(output.sample->ConvertToContiguousBuffer(&buffer)))@@ -685,7 +682,7 @@ DecoderErrorOr<NonnullRefPtr<VideoFrame>> WindowsMediaFoundationVideoDecoder::co}}- return DECODER_TRY_ALLOC(try_make_ref_counted<VideoFrame>(output.timestamp, output.duration, format.aperture_size, format.bit_depth, subsampling, container_cicp, pool_slot_result.release_value()));+ return DECODER_TRY_ALLOC(try_make_ref_counted<VideoFrame>(output.timestamp, output.duration, format.aperture_size, format.bit_depth, subsampling, container_cicp, acquired_slot->storage));}void WindowsMediaFoundationVideoDecoder::flush()diff --git a/Services/Compositor/VideoFrameSkia.cpp b/Services/Compositor/VideoFrameSkia.cppindex ae88c529c0c..1012f7c41e3 100644--- a/Services/Compositor/VideoFrameSkia.cpp+++ b/Services/Compositor/VideoFrameSkia.cpp@@ -194,7 +194,6 @@ struct AK::Traits<Compositor::VideoSurfaceImageKey> : public DefaultTraits<Componamespace Compositor {static constexpr auto UNDRAWN_VIDEO_SURFACE_IMAGE_LIFETIME = AK::Duration::from_seconds(1);-// A sender may send a new surface with every frame, so only this many of each sender's images are kept.static constexpr size_t MAX_VIDEO_SURFACE_IMAGES_PER_SENDER = 32;static HashMap<VideoSurfaceImageKey, NonnullOwnPtr<VideoSurfaceImage>>& video_surface_images()@@ -258,9 +257,7 @@ static void make_room_for_video_surface_image(u64 sender_id)static sk_sp<SkImage> image_for_video_surface(Media::VideoFrame const& frame, Media::VideoSurface const& surface, Gfx::SkiaBackendContext& skia_backend_context){- u64 sender_id = 0;- if (auto const* storage = frame.received_storage())- sender_id = storage->sender_id();+ auto sender_id = frame.storage()->sender_id();VideoSurfaceImageKey key { sender_id, surface.id() };auto& images = video_surface_images();diff --git a/Tests/Compositor/TestVideoFrameHolds.cpp b/Tests/Compositor/TestVideoFrameHolds.cppindex d9639511f9d..a02fa985694 100644--- a/Tests/Compositor/TestVideoFrameHolds.cpp+++ b/Tests/Compositor/TestVideoFrameHolds.cpp@@ -18,8 +18,7 @@ static NonnullRefPtr<Media::VideoFrame> create_pooled_frame(Media::VideoFramePooauto subsampling = Media::Subsampling::yuv420();auto layout = MUST(Media::frame_plane_layout(frame_size, 8, subsampling));auto acquired = pool.try_acquire(layout.total_byte_count).release_value();- auto slot = MUST(pool.try_adopt_acquired_slot(acquired));- return make_ref_counted<Media::VideoFrame>(AK::Duration::zero(), AK::Duration::from_milliseconds(33), Gfx::Size<u32>(frame_size), 8, subsampling, Media::CodingIndependentCodePoints {}, move(slot));+ return make_ref_counted<Media::VideoFrame>(AK::Duration::zero(), AK::Duration::from_milliseconds(33), Gfx::Size<u32>(frame_size), 8, subsampling, Media::CodingIndependentCodePoints {}, move(acquired.storage));}// Every frame kept for a hold keeps its buffer open in the Compositor, so a WebContent holding one frame after anotherdiff --git a/Tests/LibMedia/TestDisplayingVideoSink.cpp b/Tests/LibMedia/TestDisplayingVideoSink.cppindex 84214bf840e..b25b3dc8312 100644--- a/Tests/LibMedia/TestDisplayingVideoSink.cpp+++ b/Tests/LibMedia/TestDisplayingVideoSink.cpp@@ -26,9 +26,7 @@ NonnullRefPtr<Media::VideoFrame> create_test_frame(Media::VideoFramePool& pool,auto plane_sizes = MUST(Gfx::YUVData::plane_sizes(frame_size, bit_depth, subsampling));auto acquired = pool.try_acquire(plane_sizes.total).release_value();- auto slot = MUST(pool.try_adopt_acquired_slot(acquired));-- return make_ref_counted<Media::VideoFrame>(timestamp, duration, Gfx::Size<u32>(frame_size), bit_depth, subsampling, Media::CodingIndependentCodePoints {}, move(slot));+ return make_ref_counted<Media::VideoFrame>(timestamp, duration, Gfx::Size<u32>(frame_size), bit_depth, subsampling, Media::CodingIndependentCodePoints {}, move(acquired.storage));}}diff --git a/Tests/LibMedia/TestRemoteVideoNode.cpp b/Tests/LibMedia/TestRemoteVideoNode.cppindex 9c58d223274..cce3918ac44 100644--- a/Tests/LibMedia/TestRemoteVideoNode.cpp+++ b/Tests/LibMedia/TestRemoteVideoNode.cpp@@ -163,7 +163,7 @@ struct VideoEdgeTestHarnessif (auto harness = weak.strong_ref())harness->sink->release_frame(lend_id);};- auto frame = MUST(create_received_video_frame(lent_frame.metadata, move(lent_frame.pixel_buffer), move(lent_frame.surface), 1, move(release)));+ auto frame = MUST(create_received_video_frame(lent_frame.metadata, move(lent_frame.pixels), 1, move(release)));consumer->receive_frame(lent_frame.lend_id, lent_frame.seek_id, move(frame));},[&](StatusMessage const& status) {@@ -213,16 +213,14 @@ NonnullRefPtr<VideoFrame> create_pooled_frame(VideoFramePool& pool, AK::Durationauto layout = MUST(frame_plane_layout(frame_size, bit_depth, subsampling));auto acquired = pool.try_acquire(layout.total_byte_count).release_value();- auto slot = MUST(pool.try_adopt_acquired_slot(acquired));-- return make_ref_counted<VideoFrame>(timestamp, duration, Gfx::Size<u32>(frame_size), bit_depth, subsampling, CodingIndependentCodePoints {}, move(slot));+ return make_ref_counted<VideoFrame>(timestamp, duration, Gfx::Size<u32>(frame_size), bit_depth, subsampling, CodingIndependentCodePoints {}, move(acquired.storage));}// A frame as the consumer receives it, which counts its release.NonnullRefPtr<VideoFrame> create_received_frame(VideoFramePool& pool, AK::Duration timestamp, Function<void()> on_release = [] { }){auto frame = create_pooled_frame(pool, timestamp, AK::Duration::from_milliseconds(100));- return MUST(create_received_video_frame(VideoFrameMetadata::for_frame(*frame), frame->pixel_buffer(), nullptr, 1, move(on_release)));+ return MUST(create_received_video_frame(VideoFrameMetadata::for_frame(*frame), frame->pixel_buffer(), 1, move(on_release)));}RemoteVideoProducer::Delegates make_consumer_delegates(size_t& upstream_seeks)diff --git a/Tests/LibMedia/TestVideoFramePool.cpp b/Tests/LibMedia/TestVideoFramePool.cppindex 59cb0b8d382..8c0df2318fe 100644--- a/Tests/LibMedia/TestVideoFramePool.cpp+++ b/Tests/LibMedia/TestVideoFramePool.cpp@@ -70,6 +70,11 @@ static Core::AnonymousBuffer received_copy_of(Core::AnonymousBuffer const& buffereturn MUST(Core::AnonymousBuffer::create_from_anon_fd(MUST(Core::System::dup(buffer.fd())), buffer.size()));}+static bool buffers_share_memory(Core::AnonymousBuffer const& a, Core::AnonymousBuffer const& b)+{+ return a.is_valid() && b.is_valid() && a.data<u8 const>() == b.data<u8 const>();+}+TEST_CASE(acquire_exhaustion_and_release){auto pool = make_pool();@@ -79,48 +84,46 @@ TEST_CASE(acquire_exhaustion_and_release)EXPECT(!pool->try_acquire(FRAME_BYTE_COUNT).has_value());- pool->release_hold(slots.take_last().index);+ slots.take_last();EXPECT(pool->try_acquire(FRAME_BYTE_COUNT).has_value());}-TEST_CASE(holds_prevent_recycling)+TEST_CASE(a_slot_stays_held_while_any_frame_shares_its_storage){auto pool = make_pool();- auto slot = pool->try_acquire(FRAME_BYTE_COUNT).release_value();- pool->add_hold(slot.index);-- // Dropping the adopted slot's hold still leaves the added hold outstanding.- {- auto adopted_slot = MUST(pool->try_adopt_acquired_slot(slot));- }+ auto slot = pool->try_acquire(FRAME_BYTE_COUNT);+ RefPtr<Media::VideoFrameStorage> second_reference = slot->storage;+ auto slot_buffer = slot->storage->pixel_buffer();+ slot.clear();+ Vector<Media::VideoFramePool::AcquiredSlot> other_slots;for (u32 i = 0; i < Media::VideoFramePool::MAX_SLOT_COUNT - 1; i++)- EXPECT(pool->try_acquire(FRAME_BYTE_COUNT).has_value());+ other_slots.append(pool->try_acquire(FRAME_BYTE_COUNT).release_value());EXPECT(!pool->try_acquire(FRAME_BYTE_COUNT).has_value());- pool->release_hold(slot.index);+ second_reference = nullptr;auto reacquired = pool->try_acquire(FRAME_BYTE_COUNT);EXPECT(reacquired.has_value());- EXPECT_EQ(reacquired->index, slot.index);+ EXPECT(buffers_share_memory(reacquired->storage->pixel_buffer(), slot_buffer));}TEST_CASE(buffers_are_reused_on_exact_capacity_match){auto pool = make_pool();- auto first = pool->try_acquire(FRAME_BYTE_COUNT).release_value();+ auto first = pool->try_acquire(FRAME_BYTE_COUNT);+ auto first_buffer = first->storage->pixel_buffer();auto allocated_after_first = pool->allocated_byte_count();- pool->release_hold(first.index);+ first.clear();// Reacquiring the same byte count reuses the free buffer without allocating.- auto reacquired = pool->try_acquire(FRAME_BYTE_COUNT).release_value();- EXPECT_EQ(reacquired.index, first.index);+ auto reacquired = pool->try_acquire(FRAME_BYTE_COUNT);+ EXPECT(buffers_share_memory(reacquired->storage->pixel_buffer(), first_buffer));EXPECT_EQ(pool->allocated_byte_count(), allocated_after_first);- pool->release_hold(reacquired.index);+ reacquired.clear();// A different byte count needs a buffer of its own.auto larger = pool->try_acquire(FRAME_BYTE_COUNT * 2).release_value();EXPECT(pool->allocated_byte_count() > allocated_after_first);- pool->release_hold(larger.index);}TEST_CASE(budget_always_allows_the_liveness_floor)@@ -134,7 +137,7 @@ TEST_CASE(budget_always_allows_the_liveness_floor)EXPECT(!pool->try_acquire(FRAME_BYTE_COUNT).has_value());- pool->release_hold(slots.take_last().index);+ slots.take_last();EXPECT(pool->try_acquire(FRAME_BYTE_COUNT).has_value());}@@ -144,28 +147,26 @@ TEST_CASE(excess_free_buffers_are_dropped_to_fit_the_budget)auto pool = make_pool(nullptr, slot_buffer_size * Media::VideoFramePool::MIN_SLOT_COUNT);// Fill the budget with free buffers.- Vector<Media::VideoFramePool::AcquiredSlot> slots;- for (u32 i = 0; i < Media::VideoFramePool::MIN_SLOT_COUNT; i++)- slots.append(pool->try_acquire(FRAME_BYTE_COUNT).release_value());- for (auto const& slot : slots)- pool->release_hold(slot.index);+ {+ Vector<Media::VideoFramePool::AcquiredSlot> slots;+ for (u32 i = 0; i < Media::VideoFramePool::MIN_SLOT_COUNT; i++)+ slots.append(pool->try_acquire(FRAME_BYTE_COUNT).release_value());+ }EXPECT_EQ(pool->allocated_byte_count(), slot_buffer_size * Media::VideoFramePool::MIN_SLOT_COUNT);// A larger allocation replaces one free buffer and sheds others to return to the budget.auto larger = pool->try_acquire(FRAME_BYTE_COUNT * 2).release_value();- (void)larger;EXPECT(pool->allocated_byte_count() <= slot_buffer_size * Media::VideoFramePool::MIN_SLOT_COUNT);}TEST_CASE(shed_storage_frees_all_but_held_slots){auto pool = make_pool();- auto held = pool->try_acquire(resolved_frame_byte_count()).release_value();- held.bytes.fill(0x42);- auto frame = MUST(Media::create_received_video_frame(make_metadata(), received_copy_of(pool->slot_buffer(held.index)), nullptr, 0, [] { }));+ auto held = pool->try_acquire(resolved_frame_byte_count());+ held->bytes.fill(0x42);+ auto frame = MUST(Media::create_received_video_frame(make_metadata(), received_copy_of(held->storage->pixel_buffer()), 0, [] { }));- auto released = pool->try_acquire(FRAME_BYTE_COUNT).release_value();- pool->release_hold(released.index);+ (void)pool->try_acquire(FRAME_BYTE_COUNT).release_value();pool->shed_storage();@@ -174,7 +175,7 @@ TEST_CASE(shed_storage_frees_all_but_held_slots)EXPECT_EQ(frame->yuv_data()->y_data()[0], 0x42);// The held buffer is freed once its last hold releases, while a frame received from it keeps reading it.- pool->release_hold(held.index);+ held.clear();EXPECT_EQ(pool->allocated_byte_count(), 0u);EXPECT_EQ(frame->yuv_data()->y_data()[0], 0x42);}@@ -182,28 +183,28 @@ TEST_CASE(shed_storage_frees_all_but_held_slots)TEST_CASE(acquisition_ends_shedding_of_held_buffers){auto pool = make_pool();- auto held = pool->try_acquire(FRAME_BYTE_COUNT).release_value();+ auto held = pool->try_acquire(FRAME_BYTE_COUNT);pool->shed_storage();// An acquisition returns the pool to service, so the buffer held through the shed is// recycled rather than freed when its hold releases.- auto reacquired = pool->try_acquire(FRAME_BYTE_COUNT).release_value();- pool->release_hold(held.index);+ auto reacquired = pool->try_acquire(FRAME_BYTE_COUNT);+ held.clear();EXPECT_EQ(pool->allocated_byte_count(), measured_slot_buffer_size(FRAME_BYTE_COUNT) * 2);- pool->release_hold(reacquired.index);+ reacquired.clear();EXPECT_EQ(pool->allocated_byte_count(), measured_slot_buffer_size(FRAME_BYTE_COUNT) * 2);}TEST_CASE(smaller_acquisitions_replace_oversized_buffers){auto pool = make_pool();- Vector<Media::VideoFramePool::AcquiredSlot> slots;- for (u32 i = 0; i < Media::VideoFramePool::MAX_SLOT_COUNT; i++)- slots.append(pool->try_acquire(FRAME_BYTE_COUNT * 2).release_value());- for (auto const& slot : slots)- pool->release_hold(slot.index);+ {+ Vector<Media::VideoFramePool::AcquiredSlot> slots;+ for (u32 i = 0; i < Media::VideoFramePool::MAX_SLOT_COUNT; i++)+ slots.append(pool->try_acquire(FRAME_BYTE_COUNT * 2).release_value());+ }// With every slot holding an oversized free buffer, an exact-size acquisition replaces one// rather than reusing the excess capacity.@@ -211,7 +212,6 @@ TEST_CASE(smaller_acquisitions_replace_oversized_buffers)EXPECT_EQ(pool->allocated_byte_count(),(measured_slot_buffer_size(FRAME_BYTE_COUNT * 2) * (Media::VideoFramePool::MAX_SLOT_COUNT - 1))+ measured_slot_buffer_size(FRAME_BYTE_COUNT));- pool->release_hold(exact.index);}TEST_CASE(slot_freed_callback_fires_when_a_slot_becomes_free)@@ -219,14 +219,14 @@ TEST_CASE(slot_freed_callback_fires_when_a_slot_becomes_free)size_t freed_count = 0;auto pool = make_pool([&freed_count] { freed_count++; });- auto slot = pool->try_acquire(FRAME_BYTE_COUNT).release_value();- pool->add_hold(slot.index);+ auto slot = pool->try_acquire(FRAME_BYTE_COUNT);+ RefPtr<Media::VideoFrameStorage> second_reference = slot->storage;- // Releasing a hold that leaves the slot held does not fire.- pool->release_hold(slot.index);+ // Dropping a reference that leaves the slot held does not fire.+ slot.clear();EXPECT_EQ(freed_count, 0u);- pool->release_hold(slot.index);+ second_reference = nullptr;EXPECT_EQ(freed_count, 1u);EXPECT(pool->try_acquire(FRAME_BYTE_COUNT).has_value());}@@ -250,13 +250,15 @@ TEST_CASE(slot_freed_callback_wakes_a_waiting_acquirer)slots.append(pool->try_acquire(FRAME_BYTE_COUNT).release_value());IGNORE_USE_IN_ESCAPING_LAMBDA Atomic<bool> started { false };- IGNORE_USE_IN_ESCAPING_LAMBDA Atomic<u32> acquired_index { 0 };- auto acquirer_thread = Threading::Thread::construct("PoolAcquirer"sv, [&pool, &waiter, &started, &acquired_index]() {+ IGNORE_USE_IN_ESCAPING_LAMBDA Mutex acquired_mutex;+ IGNORE_USE_IN_ESCAPING_LAMBDA Optional<Media::VideoFramePool::AcquiredSlot> acquired;+ auto acquirer_thread = Threading::Thread::construct("PoolAcquirer"sv, [&pool, &waiter, &started, &acquired_mutex, &acquired]() {MutexLocker locker { waiter.mutex };started.store(true);while (true) {if (auto slot = pool->try_acquire(FRAME_BYTE_COUNT); slot.has_value()) {- acquired_index.store(slot->index);+ MutexLocker acquired_locker { acquired_mutex };+ acquired = slot.release_value();return 0;}waiter.condition.wait();@@ -266,12 +268,13 @@ TEST_CASE(slot_freed_callback_wakes_a_waiting_acquirer)while (!started.load());- auto const released_index = slots.take_last().index;- pool->release_hold(released_index);+ auto released_buffer = slots.last().storage->pixel_buffer();+ slots.take_last();// If the release fails to wake the waiter, this join hangs the test.(void)acquirer_thread->join();- EXPECT_EQ(acquired_index.load(), released_index);+ MutexLocker acquired_locker { acquired_mutex };+ EXPECT(buffers_share_memory(acquired->storage->pixel_buffer(), released_buffer));}TEST_CASE(received_frames_read_their_buffer_and_release_it_once_dropped)@@ -282,12 +285,11 @@ TEST_CASE(received_frames_read_their_buffer_and_release_it_once_dropped)bool released = false;{- auto frame = MUST(Media::create_received_video_frame(make_metadata(), received_copy_of(pool->slot_buffer(slot.index)), nullptr, 7, [&] { released = true; }));+ auto frame = MUST(Media::create_received_video_frame(make_metadata(), received_copy_of(slot.storage->pixel_buffer()), 7, [&] { released = true; }));EXPECT_NE(frame->yuv_data()->y_data().data(), static_cast<u8 const*>(slot.bytes.data()));EXPECT_EQ(frame->yuv_data()->y_data()[0], 0x33);EXPECT_EQ(frame->timestamp(), AK::Duration::from_milliseconds(40));- EXPECT(frame->pool_slot() == nullptr);- EXPECT_EQ(frame->received_storage()->sender_id(), 7u);+ EXPECT_EQ(frame->storage()->sender_id(), 7u);EXPECT(!released);}EXPECT(released);@@ -302,14 +304,14 @@ TEST_CASE(received_frames_must_fit_their_storage)auto release_count = 0u;auto oversized = make_metadata();oversized.bit_depth = 10;- EXPECT(Media::create_received_video_frame(oversized, received_copy_of(pool->slot_buffer(slot.index)), nullptr, 0, [&] { release_count++; }).is_error());+ EXPECT(Media::create_received_video_frame(oversized, received_copy_of(slot.storage->pixel_buffer()), 0, [&] { release_count++; }).is_error());EXPECT_EQ(release_count, 1u);auto too_small = MUST(Core::AnonymousBuffer::create_with_size(16));- EXPECT(Media::create_received_video_frame(make_metadata(), too_small, nullptr, 0, [&] { release_count++; }).is_error());+ EXPECT(Media::create_received_video_frame(make_metadata(), too_small, 0, [&] { release_count++; }).is_error());EXPECT_EQ(release_count, 2u);- EXPECT(Media::create_received_video_frame(make_metadata(), {}, nullptr, 0, [&] { release_count++; }).is_error());+ EXPECT(Media::create_received_video_frame(make_metadata(), Core::AnonymousBuffer {}, 0, [&] { release_count++; }).is_error());EXPECT_EQ(release_count, 3u);}@@ -320,7 +322,7 @@ TEST_CASE(received_frames_must_be_ones_a_decoder_could_produce)auto pool = make_pool();auto slot = pool->try_acquire(MUST(Media::frame_plane_layout(RESOLVED_FRAME_SIZE, 12, Media::Subsampling::yuv444())).total_byte_count).release_value();auto receive = [&](Media::VideoFrameMetadata const& metadata) {- return Media::create_received_video_frame(metadata, received_copy_of(pool->slot_buffer(slot.index)), nullptr, 0, [] { });+ return Media::create_received_video_frame(metadata, received_copy_of(slot.storage->pixel_buffer()), 0, [] { });};EXPECT(!receive(make_metadata()).is_error());@@ -393,77 +395,60 @@ static NonnullRefPtr<Media::VideoSurfaceContents> make_contents()return make_contents(s_unwatched_live_count);}-// The decoder recycles surfaces it is no longer kept from using, and may free them after a while, so the pool lets go-// of a surface and its contents along with its last hold.-TEST_CASE(surface_pool_lets_go_of_a_surface_with_its_last_hold)+TEST_CASE(distinct_surfaces_have_distinct_ids)+{+ auto first_surface = make_surface();+ auto second_surface = make_surface();+ EXPECT_NE(first_surface->id(), second_surface->id());+}++// The decoder recycles surfaces it is no longer kept from using, and may free them after a while, so the budget lets+// go of a surface and its contents along with the last frame holding them.+TEST_CASE(surface_budget_lets_go_of_a_surface_with_its_last_hold){Atomic<u32> live_contents { 0 };- auto pool = MUST(Media::VideoFrameSurfacePool::create());+ auto budget = make_ref_counted<Media::VideoSurfaceBudget>();auto surface = make_surface();- auto first = pool->try_acquire(surface, make_contents(live_contents)).value();+ auto storage = budget->try_hold(surface, make_contents(live_contents));+ EXPECT_NE(storage, nullptr);+ EXPECT_EQ(storage->surface()->id(), surface->id());EXPECT_EQ(live_contents.load(), 1u);- pool->add_hold(first.index);- pool->release_hold(first.index);+ auto second_reference = storage;+ storage = nullptr;EXPECT_EQ(live_contents.load(), 1u);- pool->release_hold(first.index);+ second_reference = nullptr;EXPECT_EQ(live_contents.load(), 0u);EXPECT_EQ(surface->ref_count(), 1u);-- // A surface handed back while it is still held, as when a frame is shown a second time, takes a slot of its own.- auto second = pool->try_acquire(surface, make_contents(live_contents)).value();- auto again = pool->try_acquire(surface, make_contents(live_contents)).value();- EXPECT_NE(again.index, second.index);- EXPECT_EQ(live_contents.load(), 2u);}-TEST_CASE(surface_pool_gives_distinct_surfaces_distinct_slots)+TEST_CASE(surface_budget_refuses_to_exceed_its_held_surface_count){- auto pool = MUST(Media::VideoFrameSurfacePool::create());+ auto budget = make_ref_counted<Media::VideoSurfaceBudget>();- auto first_surface = make_surface();- auto second_surface = make_surface();- EXPECT_NE(first_surface->id(), second_surface->id());-- auto first = pool->try_acquire(first_surface, make_contents()).value();- auto second = pool->try_acquire(second_surface, make_contents()).value();- EXPECT_NE(second.index, first.index);-}--TEST_CASE(surface_pool_refuses_to_exceed_its_held_slot_count)-{- auto pool = MUST(Media::VideoFrameSurfacePool::create());-- // The platform allocator hands out surfaces without limit, so this pool's held slot count is what stops a decoder- // from running arbitrarily far ahead of whoever is displaying its frames.- Vector<NonnullRefPtr<Media::VideoSurface>> surfaces;- for (u32 index = 0; index < Media::VideoFrameSurfacePool::MAX_HELD_SLOT_COUNT; index++) {- surfaces.append(make_surface());- EXPECT(pool->try_acquire(surfaces.last(), make_contents()).has_value());- }+ // The platform allocator hands out surfaces without limit, so the budget is what stops a decoder from running+ // arbitrarily far ahead of whoever is displaying its frames.+ Vector<NonnullRefPtr<Media::VideoFrameStorage>> held;+ for (u32 index = 0; index < Media::VideoSurfaceBudget::MAX_HELD_SURFACE_COUNT; index++)+ held.append(budget->try_hold(make_surface(), make_contents()).release_nonnull());auto surface_too_many = make_surface();- EXPECT(!pool->try_acquire(surface_too_many, make_contents()).has_value());+ EXPECT_EQ(budget->try_hold(surface_too_many, make_contents()), nullptr);// A held surface handed back again counts as another frame in flight.- EXPECT(!pool->try_acquire(surfaces.first(), make_contents()).has_value());+ EXPECT_EQ(budget->try_hold(held.first()->surface().release_nonnull(), make_contents()), nullptr);- pool->release_hold(0);- EXPECT(pool->try_acquire(surface_too_many, make_contents()).has_value());+ held.remove(0);+ EXPECT_NE(budget->try_hold(surface_too_many, make_contents()), nullptr);}# ifdef AK_OS_MACOS-TEST_CASE(surface_slots_survive_a_mach_port_round_trip)+TEST_CASE(surfaces_survive_a_mach_port_round_trip){- auto pool = MUST(Media::VideoFrameSurfacePool::create());auto surface = make_surface();- auto acquired = pool->try_acquire(surface, make_contents()).value();- auto lent_surface = pool->slot_surface(acquired.index);- EXPECT_NE(lent_surface, nullptr);-- auto reimported = MUST(Core::IOSurfaceHandle::from_mach_port(lent_surface->create_mach_port()));+ auto reimported = MUST(Core::IOSurfaceHandle::from_mach_port(surface->create_mach_port()));EXPECT_EQ(static_cast<u64>(reimported.id()), surface->id());EXPECT_EQ(reimported.width(), 16u);EXPECT_EQ(reimported.height(), 16u);@@ -476,31 +461,28 @@ TEST_CASE(received_surface_frames_read_their_surface)auto metadata = make_metadata();metadata.size = { 16, 16 };- auto frame = MUST(Media::create_received_video_frame(metadata, {}, surface, 0, [] { }));+ auto frame = MUST(Media::create_received_video_frame(metadata, surface, 0, [] { }));EXPECT_EQ(frame->surface()->id(), surface->id());// The planes of a surface-backed frame are in the surface, so no view into a buffer is offered.EXPECT(!frame->yuv_data().has_value());auto larger_than_the_surface = metadata;larger_than_the_surface.size = { 32, 16 };- EXPECT(Media::create_received_video_frame(larger_than_the_surface, {}, surface, 0, [] { }).is_error());-- auto buffer = MUST(Core::AnonymousBuffer::create_with_size(4096));- EXPECT(Media::create_received_video_frame(metadata, buffer, surface, 0, [] { }).is_error());+ EXPECT(Media::create_received_video_frame(larger_than_the_surface, surface, 0, [] { }).is_error());}-TEST_CASE(surface_slots_hold_and_free_through_the_shared_ledger)+TEST_CASE(surface_budget_reports_each_released_surface){auto freed_count = 0u;- auto pool = MUST(Media::VideoFrameSurfacePool::create());- pool->set_slot_freed_callback([&] { freed_count++; });- auto acquired = pool->try_acquire(make_surface(), make_contents()).value();+ auto budget = make_ref_counted<Media::VideoSurfaceBudget>();+ budget->set_storage_freed_callback([&] { freed_count++; });+ auto storage = budget->try_hold(make_surface(), make_contents());- pool->add_hold(acquired.index);- pool->release_hold(acquired.index);+ auto second_reference = storage;+ storage = nullptr;EXPECT_EQ(freed_count, 0u);- pool->release_hold(acquired.index);+ second_reference = nullptr;EXPECT_EQ(freed_count, 1u);}diff --git a/Tests/LibMedia/TestVideoToolboxDecode.cpp b/Tests/LibMedia/TestVideoToolboxDecode.cppindex 87b2a791fa8..8ace16aec49 100644--- a/Tests/LibMedia/TestVideoToolboxDecode.cpp+++ b/Tests/LibMedia/TestVideoToolboxDecode.cpp@@ -125,7 +125,7 @@ TEST_CASE(surfaces_are_not_reused_while_their_frames_are_held)// one in use. Were that claim missing, these frames would be a handful of surfaces overwriting one another.Vector<NonnullRefPtr<Media::VideoFrame>> held_frames;HashTable<u32> held_surface_ids;- while (held_frames.size() < Media::VideoFrameSurfacePool::MAX_HELD_SLOT_COUNT) {+ while (held_frames.size() < Media::VideoSurfaceBudget::MAX_HELD_SURFACE_COUNT) {auto frame_result = decoding.next_frame();if (frame_result.is_error() && decoding_is_unavailable(frame_result.error()))return;@@ -143,7 +143,7 @@ TEST_CASE(storage_runs_out_while_every_frame_is_held)auto decoding = open_decoding("./vp9_in_webm.webm"sv, Media::CodecID::VP9);Vector<NonnullRefPtr<Media::VideoFrame>> held_frames;- while (held_frames.size() < Media::VideoFrameSurfacePool::MAX_HELD_SLOT_COUNT) {+ while (held_frames.size() < Media::VideoSurfaceBudget::MAX_HELD_SURFACE_COUNT) {auto frame_result = decoding.next_frame();if (frame_result.is_error() && decoding_is_unavailable(frame_result.error()))return;@@ -154,7 +154,7 @@ TEST_CASE(storage_runs_out_while_every_frame_is_held)EXPECT(exhausted_result.is_error());EXPECT_EQ(exhausted_result.error().category(), Media::DecoderErrorCategory::TryAgain);- // Letting the first frame go returns its slot to the pool.+ // Letting the first frame go makes room for another.held_frames.remove(0);EXPECT(!decoding.next_frame().is_error());}diff --git a/Tests/LibMedia/WithholdingVideoDecoder.h b/Tests/LibMedia/WithholdingVideoDecoder.hindex 7bb1e423cf3..e8cd40fd14e 100644--- a/Tests/LibMedia/WithholdingVideoDecoder.h+++ b/Tests/LibMedia/WithholdingVideoDecoder.h@@ -201,13 +201,10 @@ public:auto acquired_slot = m_frame_pool->try_acquire(byte_count);if (!acquired_slot.has_value())return Media::DecoderError::with_description(Media::DecoderErrorCategory::TryAgain, "Every video frame slot is held elsewhere"sv);- auto pool_slot = m_frame_pool->try_adopt_acquired_slot(*acquired_slot);- if (pool_slot.is_error())- return Media::DecoderError::with_description(Media::DecoderErrorCategory::Memory, "Failed to adopt a pooled frame slot"sv);auto output = m_withheld_outputs->m_released.take_first();m_withheld_outputs->m_handed_out_count++;- return make_ref_counted<Media::VideoFrame>(output.timestamp, output.duration, FRAME_SIZE, 8, Media::Subsampling::yuv420(), container_cicp, pool_slot.release_value());+ return make_ref_counted<Media::VideoFrame>(output.timestamp, output.duration, FRAME_SIZE, 8, Media::Subsampling::yuv420(), container_cicp, move(acquired_slot->storage));}virtual void flush() override