Skip to content

Truly independent web browser

LibMediaCodecs+Everywhere: Let the frame slot keep surface pixels alive

Zaggy1024a6fa829608d5
diff --git a/Libraries/LibMediaCodecs/Forward.h b/Libraries/LibMediaCodecs/Forward.h
index 712935e7e62..d52917b681e 100644
--- a/Libraries/LibMediaCodecs/Forward.h
+++ b/Libraries/LibMediaCodecs/Forward.h
@@ -13,5 +13,7 @@ class DecoderError;
class VideoDecoder;
class VideoDecoderServerConnection;
class VideoFrame;
+class VideoSurface;
+class VideoSurfaceContents;
}
diff --git a/Libraries/LibMediaCodecs/VideoDecoderServerConnection.cpp b/Libraries/LibMediaCodecs/VideoDecoderServerConnection.cpp
index 5975d3b98d2..b41d1cd6aca 100644
--- a/Libraries/LibMediaCodecs/VideoDecoderServerConnection.cpp
+++ b/Libraries/LibMediaCodecs/VideoDecoderServerConnection.cpp
@@ -369,12 +369,12 @@ void VideoDecoderServerConnection::die()
entry.value->exit_and_join();
m_sessions.clear();
- HashMap<HeldSlot, NonnullRefPtr<VideoFrame>, HeldSlotTraits> held_frames;
+ HashMap<HeldSlot, Vector<NonnullRefPtr<VideoFrame>>, HeldSlotTraits> held_frames_by_slot;
{
MutexLocker locker { m_held_frames_mutex };
- held_frames = move(m_held_frames);
+ held_frames_by_slot = move(m_held_frames_by_slot);
}
- held_frames.clear();
+ held_frames_by_slot.clear();
if (on_death)
on_death();
@@ -456,10 +456,15 @@ void VideoDecoderServerConnection::flush(u64 decoder_id, u32 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;
+ RefPtr<VideoFrame> frame;
{
MutexLocker locker { m_held_frames_mutex };
- frame = m_held_frames.take({ pool_id, slot_index });
+ auto held_frames = m_held_frames_by_slot.find({ pool_id, slot_index });
+ if (held_frames == m_held_frames_by_slot.end())
+ return;
+ frame = held_frames->value.take_last();
+ if (held_frames->value.is_empty())
+ m_held_frames_by_slot.remove(held_frames);
}
}
@@ -469,7 +474,7 @@ void VideoDecoderServerConnection::hold_frame_until_released(NonnullRefPtr<Video
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));
+ m_held_frames_by_slot.ensure(slot).append(move(frame));
}
bool VideoDecoderServerConnection::should_close_after_decoding_frame()
diff --git a/Libraries/LibMediaCodecs/VideoDecoderServerConnection.h b/Libraries/LibMediaCodecs/VideoDecoderServerConnection.h
index 39da37bce11..6894e34f6a2 100644
--- a/Libraries/LibMediaCodecs/VideoDecoderServerConnection.h
+++ b/Libraries/LibMediaCodecs/VideoDecoderServerConnection.h
@@ -23,7 +23,7 @@ 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.
+// it out of a shared-memory ring. Every frame handed out of a slot stays held here until the client releases it.
class MEDIACODECS_API VideoDecoderServerConnection final
: public IPC::ConnectionFromClient<VideoDecoderClientEndpoint, VideoDecoderServerEndpoint>
, public ThreadSafeWeakable<VideoDecoderServerConnection> {
@@ -73,7 +73,7 @@ private:
HashMap<u64, NonnullRefPtr<DecoderSession>> m_sessions;
Mutex m_held_frames_mutex;
- HashMap<HeldSlot, NonnullRefPtr<VideoFrame>, HeldSlotTraits> m_held_frames;
+ HashMap<HeldSlot, Vector<NonnullRefPtr<VideoFrame>>, HeldSlotTraits> m_held_frames_by_slot;
Atomic<u32> m_frames_until_close { 0 };
};
diff --git a/Libraries/LibMediaCodecs/VideoFrame.cpp b/Libraries/LibMediaCodecs/VideoFrame.cpp
index 3dcd2916fe4..5eec5939308 100644
--- a/Libraries/LibMediaCodecs/VideoFrame.cpp
+++ b/Libraries/LibMediaCodecs/VideoFrame.cpp
@@ -4,6 +4,7 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+#include <LibGfx/Bitmap.h>
#include <LibMediaCodecs/VideoFramePool.h>
#include <LibMediaCodecs/VideoSurface.h>
@@ -48,6 +49,16 @@ Optional<Gfx::YUVData> VideoFrame::yuv_data() const
return yuv_data.release_value();
}
+ErrorOr<NonnullRefPtr<Gfx::Bitmap>> VideoFrame::to_bitmap() const
+{
+ if (auto surface = this->surface())
+ return surface->read_back_bitmap(m_cicp);
+ auto yuv_data = this->yuv_data();
+ if (!yuv_data.has_value())
+ return Error::from_string_literal("Video frame has no pixels to read");
+ return yuv_data->to_bitmap();
+}
+
VideoFrame::~VideoFrame() = default;
PooledVideoFrameSlot const* VideoFrame::pool_slot() const
diff --git a/Libraries/LibMediaCodecs/VideoFrame.h b/Libraries/LibMediaCodecs/VideoFrame.h
index 9e222e95f5a..80efb93d165 100644
--- a/Libraries/LibMediaCodecs/VideoFrame.h
+++ b/Libraries/LibMediaCodecs/VideoFrame.h
@@ -60,6 +60,9 @@ public:
// The platform surface holding the frame's pixels, null when they live in the backing slot's buffer.
RefPtr<VideoSurface> surface() const;
+ // Converts the pixels to RGBA in memory, wherever they are, if this process can read them.
+ ErrorOr<NonnullRefPtr<Gfx::Bitmap>> to_bitmap() const;
+
PooledVideoFrameSlot const* pool_slot() const;
ResolvedVideoFrameSlot const* resolved_slot() const;
diff --git a/Libraries/LibMediaCodecs/VideoFramePool.cpp b/Libraries/LibMediaCodecs/VideoFramePool.cpp
index 9b5502b89e6..0b23aade8c9 100644
--- a/Libraries/LibMediaCodecs/VideoFramePool.cpp
+++ b/Libraries/LibMediaCodecs/VideoFramePool.cpp
@@ -150,8 +150,6 @@ ErrorOr<NonnullRefPtr<PooledVideoFrameSlot>> VideoFramePool::try_adopt_acquired_
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_acquisition_id;
}
@@ -236,17 +234,21 @@ void VideoFrameEntryLedger::add_hold(u32 slot_index)
void VideoFrameEntryLedger::release_hold(u32 slot_index)
{
+ // The 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<VideoSurfaceContents> released_contents;
{
MutexLocker locker { m_mutex };
auto& slot = m_slots[slot_index];
VERIFY(slot.hold_count > 0);
if (--slot.hold_count > 0)
return;
- // The decoder is free to hand this surface back now, and the slot is still here to recognize it by.
- slot.surface_use = {};
+ // The slot keeps the surface itself, to recognize it by when the decoder hands it back.
+ released_contents = move(slot.contents);
if (m_shed_storage_on_release)
drop_slot_storage_while_locked(slot);
}
+ released_contents = nullptr;
if (m_slot_freed_callback)
m_slot_freed_callback();
@@ -271,12 +273,23 @@ ErrorOr<NonnullRefPtr<VideoFrameSurfacePool>> VideoFrameSurfacePool::create()
return adopt_nonnull_ref_or_enomem(new (nothrow) VideoFrameSurfacePool());
}
-Optional<VideoFrameSurfacePool::AcquiredSlot> VideoFrameSurfacePool::try_acquire(NonnullRefPtr<VideoSurface> const& surface)
+Optional<VideoFrameSurfacePool::AcquiredSlot> VideoFrameSurfacePool::try_acquire(NonnullRefPtr<VideoSurface> const& surface, NonnullRefPtr<VideoSurfaceContents> contents)
{
MutexLocker locker { m_mutex };
auto slot_index = m_slot_indices_by_surface_id.get(surface->id()).copy();
+ if (slot_index.has_value() && m_slots[*slot_index].hold_count != 0) {
+ // The surface's pixels have not changed while it was held, so the contents already held are the same ones.
+ auto& held_slot = m_slots[*slot_index];
+ held_slot.hold_count++;
+ return AcquiredSlot {
+ .index = *slot_index,
+ .slot_acquisition_id = held_slot.last_slot_acquisition_id,
+ .allocated_buffer_id = held_slot.allocated_buffer_id,
+ };
+ }
+
if (!slot_index.has_value()) {
Optional<u32> unused_slot_index;
Optional<u32> evictable_slot_index;
@@ -315,8 +328,8 @@ Optional<VideoFrameSurfacePool::AcquiredSlot> VideoFrameSurfacePool::try_acquire
}
auto& slot = m_slots[*slot_index];
- VERIFY(slot.hold_count == 0);
slot.surface = surface;
+ slot.contents = move(contents);
publish_acquisition_while_locked(slot);
return AcquiredSlot {
@@ -339,13 +352,13 @@ ErrorOr<NonnullRefPtr<PooledVideoFrameSlot>> VideoFrameSurfacePool::try_adopt_ac
return 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)
+ErrorOr<NonnullRefPtr<VideoFrameRelayPool>> VideoFrameRelayPool::create(AdoptionReleasedCallback adoption_released_callback)
{
- return adopt_nonnull_ref_or_enomem(new (nothrow) VideoFrameRelayPool(move(slot_released_callback)));
+ return adopt_nonnull_ref_or_enomem(new (nothrow) VideoFrameRelayPool(move(adoption_released_callback)));
}
-VideoFrameRelayPool::VideoFrameRelayPool(SlotReleasedCallback slot_released_callback)
- : m_slot_released_callback(move(slot_released_callback))
+VideoFrameRelayPool::VideoFrameRelayPool(AdoptionReleasedCallback adoption_released_callback)
+ : m_adoption_released_callback(move(adoption_released_callback))
{
}
@@ -357,8 +370,10 @@ ErrorOr<void> VideoFrameRelayPool::set_slot_storage(u32 slot_index, Core::Anonym
return Error::from_string_literal("Relayed video frame slot buffer is too small");
MutexLocker locker { m_mutex };
- while (m_slots.size() <= slot_index)
+ while (m_slots.size() <= slot_index) {
+ TRY(m_adoption_counts_by_slot.try_append(0));
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");
@@ -378,11 +393,16 @@ ErrorOr<NonnullRefPtr<PooledVideoFrameSlot>> VideoFrameRelayPool::try_adopt_publ
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);
+ if (slot.hold_count != 0) {
+ if (slot.last_slot_acquisition_id != slot_acquisition_id)
+ return Error::from_string_literal("Relayed video frame refers to a slot that is still held for an earlier acquisition");
+ slot.hold_count++;
+ } else {
+ 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);
+ }
+ m_adoption_counts_by_slot[slot_index]++;
allocated_buffer_id = slot.allocated_buffer_id;
}
return try_adopt_slot(slot_index, slot_acquisition_id, allocated_buffer_id);
@@ -396,7 +416,13 @@ void VideoFrameRelayPool::drop_slot_storage_while_locked(Slot& slot)
void VideoFrameRelayPool::did_free_slot(u32 slot_index)
{
- m_slot_released_callback(slot_index);
+ u32 adoption_count = 0;
+ {
+ MutexLocker locker { m_mutex };
+ adoption_count = exchange(m_adoption_counts_by_slot[slot_index], 0u);
+ }
+ for (u32 adoption = 0; adoption < adoption_count; adoption++)
+ m_adoption_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)
@@ -407,10 +433,6 @@ ResolvedVideoFrameSlot::ResolvedVideoFrameSlot(Core::AnonymousBuffer slot_buffer
, m_slot_acquisition_id(slot_acquisition_id)
, m_on_release(move(on_release))
{
- // The slot this was resolved from can be released from under it, so this is what keeps the pixels it reads from
- // being decoded into again.
- if (m_surface != nullptr)
- m_surface_use = m_surface->begin_use();
}
ResolvedVideoFrameSlot::~ResolvedVideoFrameSlot()
diff --git a/Libraries/LibMediaCodecs/VideoFramePool.h b/Libraries/LibMediaCodecs/VideoFramePool.h
index 9d77c537989..cd4344b2008 100644
--- a/Libraries/LibMediaCodecs/VideoFramePool.h
+++ b/Libraries/LibMediaCodecs/VideoFramePool.h
@@ -57,9 +57,9 @@ protected:
struct Slot {
Core::AnonymousBuffer buffer;
// A slot keeps its surface once it has one, so that the decoder handing the same one back is recognized.
- // Only the use says the pixels are live, and only a held slot has one.
+ // Only a held slot has contents, which the decoder gave with the surface and which go with the last hold.
RefPtr<VideoSurface> surface;
- VideoSurfaceUse surface_use;
+ RefPtr<VideoSurfaceContents> contents;
u64 last_slot_acquisition_id { 0 };
u64 allocated_buffer_id { 0 };
u32 hold_count { 0 };
@@ -134,7 +134,9 @@ public:
u64 allocated_buffer_id { 0 };
};
// Gets the slot already representing this surface, or a free one, so that a recycled surface keeps its identity.
- Optional<AcquiredSlot> try_acquire(NonnullRefPtr<VideoSurface> const&);
+ // A surface handed back while its slot is still held, as a frame shown a second time is, gets another hold on
+ // the acquisition it already has, and the contents given with it are dropped in favor of the ones held.
+ Optional<AcquiredSlot> try_acquire(NonnullRefPtr<VideoSurface> const&, NonnullRefPtr<VideoSurfaceContents>);
ErrorOr<NonnullRefPtr<PooledVideoFrameSlot>> try_adopt_acquired_slot(AcquiredSlot const&);
private:
@@ -146,27 +148,32 @@ private:
};
// 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.
+// publishes each acquisition in the slot's buffer and holds the slot once for each frame it hands out of it, until
+// this pool releases that hold, so this pool tracks holds without publishing anything. Holds taken here beyond the
+// adoptions, by lending a frame onward, are this process's own, so they are not released to the other process.
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);
+ // Called once for each adoption of a slot, once the slot is no longer held here at all.
+ using AdoptionReleasedCallback = Function<void(u32 slot_index)>;
+ static ErrorOr<NonnullRefPtr<VideoFrameRelayPool>> create(AdoptionReleasedCallback);
// 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.
+ // Holds a slot for an acquisition the other process published in the slot's buffer, or holds it once more for
+ // the acquisition it is already held for.
ErrorOr<NonnullRefPtr<PooledVideoFrameSlot>> try_adopt_published_slot(u32 slot_index, u64 slot_acquisition_id);
private:
- explicit VideoFrameRelayPool(SlotReleasedCallback);
+ explicit VideoFrameRelayPool(AdoptionReleasedCallback);
virtual void drop_slot_storage_while_locked(Slot&) override;
virtual void did_free_slot(u32 slot_index) override;
- SlotReleasedCallback m_slot_released_callback;
+ AdoptionReleasedCallback m_adoption_released_callback;
+ // How many times each slot was adopted since it was last free, indexed like the slots.
+ Vector<u32> m_adoption_counts_by_slot;
};
// A strong reference to a slot in a frame pool to be used within a single process.
@@ -214,7 +221,6 @@ public:
private:
Core::AnonymousBuffer m_slot_buffer;
RefPtr<VideoSurface> m_surface;
- VideoSurfaceUse m_surface_use;
VideoFramePoolID m_pool_id { 0 };
u32 m_slot_index { 0 };
u64 m_slot_acquisition_id { 0 };
diff --git a/Libraries/LibMediaCodecs/VideoSurface.cpp b/Libraries/LibMediaCodecs/VideoSurface.cpp
index d156018471e..09fb6f0b4ae 100644
--- a/Libraries/LibMediaCodecs/VideoSurface.cpp
+++ b/Libraries/LibMediaCodecs/VideoSurface.cpp
@@ -4,34 +4,29 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+#include <LibGfx/Bitmap.h>
#include <LibIPC/Decoder.h>
#include <LibIPC/Encoder.h>
#include <LibMediaCodecs/VideoSurface.h>
-namespace Media {
-
#ifdef AK_OS_MACOS
+# include <LibGfx/VideoSurfaceImage.h>
+#endif
-VideoSurface::~VideoSurface() = default;
+namespace Media {
-bool VideoSurface::is_in_use() const
-{
- return m_io_surface.is_in_use();
-}
+VideoSurface::~VideoSurface() = default;
-VideoSurfaceUse::VideoSurfaceUse(VideoSurface& surface)
- : m_surface(surface)
+ErrorOr<NonnullRefPtr<Gfx::Bitmap>> VideoSurface::read_back_bitmap([[maybe_unused]] CodingIndependentCodePoints const& cicp) const
{
- m_surface->m_io_surface.increment_use_count();
+#ifdef AK_OS_MACOS
+ return Gfx::bitmap_from_video_surface(m_io_surface, cicp);
+#else
+ return Error::from_string_literal("This process cannot read the video surface's pixels back");
+#endif
}
-void VideoSurfaceUse::release()
-{
- if (m_surface == nullptr)
- return;
- m_surface->m_io_surface.decrement_use_count();
- m_surface = nullptr;
-}
+#ifdef AK_OS_MACOS
ErrorOr<NonnullRefPtr<VideoSurface>> VideoSurface::create(Core::IOSurfaceHandle io_surface)
{
@@ -44,50 +39,16 @@ ErrorOr<NonnullRefPtr<VideoSurface>> VideoSurface::create_from_mach_port(Core::M
return create(TRY(Core::IOSurfaceHandle::from_mach_port(port)));
}
-#else
-
-VideoSurface::~VideoSurface() = default;
-
-bool VideoSurface::is_in_use() const
-{
- return false;
-}
-
-VideoSurfaceUse::VideoSurfaceUse(VideoSurface& surface)
- : m_surface(surface)
-{
-}
-
-void VideoSurfaceUse::release()
-{
- m_surface = nullptr;
-}
-
#endif
-VideoSurfaceUse VideoSurface::begin_use()
-{
- return VideoSurfaceUse { *this };
-}
+#ifdef AK_OS_LINUX
-VideoSurfaceUse::VideoSurfaceUse(VideoSurfaceUse&& other)
- : m_surface(move(other.m_surface))
+ErrorOr<NonnullRefPtr<VideoSurface>> VideoSurface::create_from_dma_buf(u32 id, Gfx::LinuxDmaBufHandle dma_buf)
{
+ return adopt_nonnull_ref_or_enomem(new (nothrow) VideoSurface(id, move(dma_buf)));
}
-VideoSurfaceUse& VideoSurfaceUse::operator=(VideoSurfaceUse&& other)
-{
- if (this != &other) {
- release();
- m_surface = move(other.m_surface);
- }
- return *this;
-}
-
-VideoSurfaceUse::~VideoSurfaceUse()
-{
- release();
-}
+#endif
}
@@ -100,9 +61,13 @@ ErrorOr<void> encode(Encoder& encoder, RefPtr<Media::VideoSurface> const& surfac
if (surface == nullptr)
return {};
-#ifdef AK_OS_MACOS
+#if defined(AK_OS_MACOS)
TRY(encoder.append_attachment(Attachment::from_mach_port(surface->create_mach_port(), Core::MachPort::MessageRight::MoveSend)));
return {};
+#elif defined(AK_OS_LINUX)
+ TRY(encoder.encode(surface->id()));
+ TRY(encoder.encode(surface->dma_buf()));
+ return {};
#else
return Error::from_string_literal("This platform has no video surfaces to encode");
#endif
@@ -114,11 +79,15 @@ ErrorOr<RefPtr<Media::VideoSurface>> decode(Decoder& decoder)
if (!TRY(decoder.decode<bool>()))
return RefPtr<Media::VideoSurface> {};
-#ifdef AK_OS_MACOS
+#if defined(AK_OS_MACOS)
auto attachment = TRY(decoder.attachments().try_dequeue());
if (attachment.message_right() != Core::MachPort::MessageRight::MoveSend)
return Error::from_string_literal("VideoSurface attachment is not a moved send right");
return TRY(Media::VideoSurface::create_from_mach_port(attachment.release_mach_port()));
+#elif defined(AK_OS_LINUX)
+ auto id = TRY(decoder.decode<u32>());
+ auto dma_buf = TRY(decoder.decode<Gfx::LinuxDmaBufHandle>());
+ return TRY(Media::VideoSurface::create_from_dma_buf(id, move(dma_buf)));
#else
return Error::from_string_literal("This platform has no video surfaces to decode");
#endif
diff --git a/Libraries/LibMediaCodecs/VideoSurface.h b/Libraries/LibMediaCodecs/VideoSurface.h
index 57f2a21b954..2f35459d9de 100644
--- a/Libraries/LibMediaCodecs/VideoSurface.h
+++ b/Libraries/LibMediaCodecs/VideoSurface.h
@@ -10,29 +10,38 @@
#include <AK/Error.h>
#include <AK/NonnullRefPtr.h>
#include <AK/Platform.h>
+#include <LibGfx/Forward.h>
#include <LibIPC/Forward.h>
+#include <LibMediaCodecs/Color/CodingIndependentCodePoints.h>
#include <LibMediaCodecs/Export.h>
#ifdef AK_OS_MACOS
# include <LibCore/IOSurface.h>
#endif
+#ifdef AK_OS_LINUX
+# include <LibGfx/LinuxDmaBufHandle.h>
+#endif
namespace Media {
-class VideoSurfaceUse;
+// What the process that decoded into a surface holds to keep those pixels from being decoded over, for as long as
+// the frame slot they were handed out in is held anywhere.
+class VideoSurfaceContents : public AtomicRefCounted<VideoSurfaceContents> {
+public:
+ virtual ~VideoSurfaceContents() = default;
+};
// 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 can be recognized by. Holding one keeps it alive
-// and keeps that identity unambiguous, which is what lets a recycled surface be recognized as the one it was;
-// begin_use() is what says its pixels are being read or written.
+// 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.
class MEDIACODECS_API VideoSurface : public AtomicRefCounted<VideoSurface> {
public:
~VideoSurface();
u32 id() const { return m_id; }
- [[nodiscard]] VideoSurfaceUse begin_use();
- bool is_in_use() const;
+ // Reads the pixels back into memory, which works only where the platform lets this process map the surface.
+ ErrorOr<NonnullRefPtr<Gfx::Bitmap>> read_back_bitmap(CodingIndependentCodePoints const&) const;
#ifdef AK_OS_MACOS
static ErrorOr<NonnullRefPtr<VideoSurface>> create(Core::IOSurfaceHandle);
@@ -41,9 +50,15 @@ public:
Core::IOSurfaceHandle const& io_surface() const { return m_io_surface; }
#endif
-private:
- friend class VideoSurfaceUse;
+#ifdef AK_OS_LINUX
+ // The decoder assigns the ID, since the memory behind an image can be exported as any number of file
+ // descriptors. The size is the image's, which can exceed the frames decoded into it.
+ static ErrorOr<NonnullRefPtr<VideoSurface>> create_from_dma_buf(u32 id, Gfx::LinuxDmaBufHandle);
+
+ Gfx::LinuxDmaBufHandle const& dma_buf() const { return m_dma_buf; }
+#endif
+private:
#ifdef AK_OS_MACOS
VideoSurface(Core::IOSurfaceHandle io_surface, u32 id)
: m_io_surface(move(io_surface))
@@ -54,27 +69,17 @@ private:
Core::IOSurfaceHandle m_io_surface;
#endif
- u32 m_id { 0 };
-};
-
-// Says that a surface's pixels are being read or written for as long as it exists. The decoder that allocated the
-// surface will not decode into it again while any of these are alive.
-class MEDIACODECS_API VideoSurfaceUse {
- AK_MAKE_NONCOPYABLE(VideoSurfaceUse);
-
-public:
- VideoSurfaceUse() = default;
- VideoSurfaceUse(VideoSurfaceUse&&);
- VideoSurfaceUse& operator=(VideoSurfaceUse&&);
- ~VideoSurfaceUse();
-
-private:
- friend class VideoSurface;
+#ifdef AK_OS_LINUX
+ VideoSurface(u32 id, Gfx::LinuxDmaBufHandle dma_buf)
+ : m_dma_buf(move(dma_buf))
+ , m_id(id)
+ {
+ }
- explicit VideoSurfaceUse(VideoSurface&);
- void release();
+ Gfx::LinuxDmaBufHandle m_dma_buf;
+#endif
- RefPtr<VideoSurface> m_surface;
+ u32 m_id { 0 };
};
}
diff --git a/Libraries/LibMediaCodecs/VideoToolbox/VideoToolboxVideoDecoder.h b/Libraries/LibMediaCodecs/VideoToolbox/VideoToolboxVideoDecoder.h
index 90921f85af7..a6640b0f50a 100644
--- a/Libraries/LibMediaCodecs/VideoToolbox/VideoToolboxVideoDecoder.h
+++ b/Libraries/LibMediaCodecs/VideoToolbox/VideoToolboxVideoDecoder.h
@@ -50,9 +50,9 @@ private:
struct Session;
struct DecodedOutput {
NonnullRefPtr<VideoSurface> surface;
- // An output waiting on the reorder window is not in a slot yet, so this is what keeps the media engine from
- // decoding over it before it is.
- VideoSurfaceUse surface_use;
+ // Keeps the media engine from decoding over the surface, from the reorder window until the slot the frame
+ // goes out in is released.
+ NonnullRefPtr<VideoSurfaceContents> contents;
AK::Duration timestamp;
AK::Duration duration;
Gfx::IntSize size;
diff --git a/Libraries/LibMediaCodecs/VideoToolbox/VideoToolboxVideoDecoder.mm b/Libraries/LibMediaCodecs/VideoToolbox/VideoToolboxVideoDecoder.mm
index b46bdace98b..f4be635a0da 100644
--- a/Libraries/LibMediaCodecs/VideoToolbox/VideoToolboxVideoDecoder.mm
+++ b/Libraries/LibMediaCodecs/VideoToolbox/VideoToolboxVideoDecoder.mm
@@ -81,6 +81,19 @@ private:
T m_ref { nullptr };
};
+// The media engine recycles a pixel buffer once nothing retains it, so retaining it is what keeps its surface's
+// pixels in place while they are shown.
+class PixelBufferContents final : public VideoSurfaceContents {
+public:
+ explicit PixelBufferContents(CVPixelBufferRef pixel_buffer)
+ : m_pixel_buffer(CVPixelBufferRetain(pixel_buffer))
+ {
+ }
+
+private:
+ RetainedRef<CVPixelBufferRef> m_pixel_buffer;
+};
+
// How many frames the media engine may be decoding before it has to hand one back.
constexpr size_t MAXIMUM_FRAMES_IN_FLIGHT = 4;
@@ -785,12 +798,13 @@ void VideoToolboxVideoDecoder::enqueue_decoded_output_while_locked(CodingIndepen
if (m_decode_failure.has_value())
return;
- auto surface = surface_or_error.release_value();
- auto surface_use = surface->begin_use();
+ auto contents_or_error = try_make_ref_counted<PixelBufferContents>(pixel_buffer);
+ if (contents_or_error.is_error())
+ return;
DecodedOutput output {
- .surface = move(surface),
- .surface_use = move(surface_use),
+ .surface = surface_or_error.release_value(),
+ .contents = contents_or_error.release_value(),
.timestamp = timestamp,
.duration = duration,
.size = { static_cast<int>(CVPixelBufferGetWidth(pixel_buffer)), static_cast<int>(CVPixelBufferGetHeight(pixel_buffer)) },
@@ -930,7 +944,7 @@ DecoderErrorOr<NonnullRefPtr<VideoFrame>> VideoToolboxVideoDecoder::adopt_output
{
auto const& output = m_outputs[index];
- auto acquired_slot = m_surface_pool->try_acquire(output.surface);
+ 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);
diff --git a/Libraries/LibWeb/HTML/HTMLVideoElement.cpp b/Libraries/LibWeb/HTML/HTMLVideoElement.cpp
index 111b44dc962..d339aa8a1a3 100644
--- a/Libraries/LibWeb/HTML/HTMLVideoElement.cpp
+++ b/Libraries/LibWeb/HTML/HTMLVideoElement.cpp
@@ -9,10 +9,7 @@
#include <LibGC/Heap.h>
#include <LibGfx/Bitmap.h>
#include <LibGfx/DecodedImageFrame.h>
-#include <LibGfx/VideoSurfaceImage.h>
-#include <LibGfx/YUVData.h>
#include <LibMediaCodecs/VideoFrame.h>
-#include <LibMediaCodecs/VideoSurface.h>
#include <LibWeb/Bindings/Wrappable.h>
#include <LibWeb/Bindings/WrapperWorld.h>
#include <LibWeb/CSS/ElementBoxKind.h>
@@ -404,16 +401,7 @@ Optional<Gfx::DecodedImageFrame> HTMLVideoElement::current_decoded_image_frame()
if (!current_frame)
return {};
- auto bitmap_or_error = [&] -> ErrorOr<NonnullRefPtr<Gfx::Bitmap>> {
-#ifdef AK_OS_MACOS
- if (auto surface = current_frame->surface())
- return Gfx::bitmap_from_video_surface(surface->io_surface(), current_frame->cicp());
-#endif
- auto yuv_data = current_frame->yuv_data();
- if (!yuv_data.has_value())
- return Error::from_string_literal("Video frame has no pixels to read");
- return yuv_data->to_bitmap();
- }();
+ auto bitmap_or_error = current_frame->to_bitmap();
if (bitmap_or_error.is_error()) {
dbgln("Could not convert video frame to bitmap: {}", bitmap_or_error.release_error());
return {};
diff --git a/Services/Compositor/DisplayListRasterCache.cpp b/Services/Compositor/DisplayListRasterCache.cpp
index a595c661878..e13bb141511 100644
--- a/Services/Compositor/DisplayListRasterCache.cpp
+++ b/Services/Compositor/DisplayListRasterCache.cpp
@@ -16,7 +16,6 @@
#include <LibGfx/Font/Font.h>
#include <LibGfx/SkiaBackendContext.h>
#include <LibGfx/SkiaUtils.h>
-#include <LibGfx/VideoSurfaceImage.h>
#include <LibGfx/YUVData.h>
#include <LibMediaCodecs/VideoFrame.h>
#include <LibMediaCodecs/VideoFrameHandle.h>
@@ -58,9 +57,9 @@ struct DisplayListRasterCache::VideoSinkImage {
// A surface-backed image samples the surface where it lies, so it stays valid for every frame decoded into
// that surface rather than only for the one acquisition.
u32 surface_id { 0 };
- // Drawing is recorded here but read by the GPU afterwards, so the surface stays in use until a different one
- // is drawn in its place.
- Media::VideoSurfaceUse surface_use;
+ // Drawing is recorded here but read by the GPU afterwards, so the frame stays held, and its surface's pixels
+ // with it, until a different frame is drawn in its place.
+ RefPtr<Media::VideoFrame const> drawn_frame;
RefPtr<Gfx::SkiaBackendContext> skia_backend_context;
sk_sp<SkImage> image;
};
@@ -210,16 +209,16 @@ sk_sp<SkImage> DisplayListRasterCache::image_for_video_sink(DisplayListResourceS
return false;
return true;
}();
- if (cached_image_matches)
+ if (cached_image_matches) {
+ cached_image.drawn_frame = frame;
return cached_image.image;
+ }
sk_sp<SkImage> image;
auto* gr_context = skia_backend_context ? skia_backend_context->sk_context() : nullptr;
-#ifdef AK_OS_MACOS
if (surface != nullptr && skia_backend_context)
- image = sk_image_from_video_surface(surface->io_surface(), frame->cicp(), *skia_backend_context);
-#endif
+ image = sk_image_from_video_surface(*surface, frame->cicp(), *skia_backend_context);
auto yuv_data = image ? Optional<Gfx::YUVData> {} : frame->yuv_data();
if (!image && !yuv_data.has_value() && surface == nullptr)
@@ -239,14 +238,8 @@ sk_sp<SkImage> DisplayListRasterCache::image_for_video_sink(DisplayListResourceS
}
if (!image) {
- auto bitmap_or_error = [&] -> ErrorOr<NonnullRefPtr<Gfx::Bitmap>> {
-#ifdef AK_OS_MACOS
- // Without a GPU to sample the surface on, its pixels have to be read back into memory to be drawn.
- if (surface != nullptr)
- return Gfx::bitmap_from_video_surface(surface->io_surface(), frame->cicp());
-#endif
- return yuv_data->to_bitmap();
- }();
+ // Without a GPU to sample a surface on, its pixels have to be read back into memory to be drawn.
+ auto bitmap_or_error = frame->to_bitmap();
if (bitmap_or_error.is_error()) {
dbgln("Could not convert video frame to bitmap: {}", bitmap_or_error.release_error());
return nullptr;
@@ -268,7 +261,7 @@ sk_sp<SkImage> DisplayListRasterCache::image_for_video_sink(DisplayListResourceS
cached_image.slot_index = handle.slot_index;
cached_image.slot_acquisition_id = handle.slot_acquisition_id;
cached_image.surface_id = surface_id;
- cached_image.surface_use = surface ? surface->begin_use() : Media::VideoSurfaceUse {};
+ cached_image.drawn_frame = frame;
cached_image.skia_backend_context = skia_backend_context;
cached_image.image = image;
return image;
diff --git a/Services/Compositor/VideoFrameSkia.cpp b/Services/Compositor/VideoFrameSkia.cpp
index 030824f526f..bfba508e471 100644
--- a/Services/Compositor/VideoFrameSkia.cpp
+++ b/Services/Compositor/VideoFrameSkia.cpp
@@ -6,12 +6,20 @@
#include <Compositor/VideoFrameSkia.h>
#include <LibGfx/YUVData.h>
+#include <LibMediaCodecs/VideoSurface.h>
#include <core/SkYUVAInfo.h>
#include <core/SkYUVAPixmaps.h>
namespace Compositor {
+#ifndef AK_OS_MACOS
+sk_sp<SkImage> sk_image_from_video_surface(Media::VideoSurface const&, Media::CodingIndependentCodePoints, Gfx::SkiaBackendContext&)
+{
+ return nullptr;
+}
+#endif
+
SkYUVColorSpace skia_yuv_color_space(Media::CodingIndependentCodePoints cicp)
{
bool full_range = cicp.video_full_range_flag() == Media::VideoFullRangeFlag::Full;
diff --git a/Services/Compositor/VideoFrameSkia.h b/Services/Compositor/VideoFrameSkia.h
index 73b326dbbaa..a5fe7f67ca2 100644
--- a/Services/Compositor/VideoFrameSkia.h
+++ b/Services/Compositor/VideoFrameSkia.h
@@ -6,13 +6,9 @@
#pragma once
-#include <AK/Platform.h>
#include <LibGfx/Forward.h>
#include <LibMediaCodecs/Color/CodingIndependentCodePoints.h>
-
-#ifdef AK_OS_MACOS
-# include <LibCore/IOSurface.h>
-#endif
+#include <LibMediaCodecs/Forward.h>
class SkImage;
class SkYUVAPixmaps;
@@ -28,10 +24,9 @@ SkYUVColorSpace skia_yuv_color_space(Media::CodingIndependentCodePoints);
// Views the planes of the YUV data as Skia pixmaps. Samples deeper than 8 bits are copied and stretched to 16 bits.
SkYUVAPixmaps make_yuva_pixmaps(Gfx::YUVData const&);
-#ifdef AK_OS_MACOS
// Views a decoder's surface as a GPU image, sampling its planes where they already are instead of uploading a copy.
-// Returns null for a surface whose layout is not one the platform decoder produces.
-sk_sp<SkImage> sk_image_from_video_surface(Core::IOSurfaceHandle const&, Media::CodingIndependentCodePoints, Gfx::SkiaBackendContext&);
-#endif
+// Returns null for a surface whose layout is not one the platform decoder produces, or on a platform that cannot
+// sample its surfaces yet.
+sk_sp<SkImage> sk_image_from_video_surface(Media::VideoSurface const&, Media::CodingIndependentCodePoints, Gfx::SkiaBackendContext&);
}
diff --git a/Services/Compositor/VideoFrameSkia.mm b/Services/Compositor/VideoFrameSkia.mm
index 6060fcb9998..b0a7b949e28 100644
--- a/Services/Compositor/VideoFrameSkia.mm
+++ b/Services/Compositor/VideoFrameSkia.mm
@@ -10,6 +10,7 @@
#include <LibGfx/SkiaBackendContext.h>
#include <LibGfx/SkiaUtils.h>
#include <LibGfx/VideoSurfaceImage.h>
+#include <LibMediaCodecs/VideoSurface.h>
#include <core/SkColorSpace.h>
#include <core/SkImage.h>
@@ -24,12 +25,14 @@
namespace Compositor {
-sk_sp<SkImage> sk_image_from_video_surface(Core::IOSurfaceHandle const& io_surface, Media::CodingIndependentCodePoints cicp, Gfx::SkiaBackendContext& skia_backend_context)
+sk_sp<SkImage> sk_image_from_video_surface(Media::VideoSurface const& surface, Media::CodingIndependentCodePoints cicp, Gfx::SkiaBackendContext& skia_backend_context)
{
auto* gr_context = skia_backend_context.sk_context();
if (!gr_context)
return nullptr;
+ auto const& io_surface = surface.io_surface();
+
auto bit_depth = Gfx::biplanar_bit_depth_for_pixel_format(io_surface.pixel_format());
if (!bit_depth.has_value() || io_surface.plane_count() != 2)
return nullptr;
diff --git a/Tests/Compositor/TestVideoSurfaceImage.mm b/Tests/Compositor/TestVideoSurfaceImage.mm
index 947466b9b05..6d780c5fbc2 100644
--- a/Tests/Compositor/TestVideoSurfaceImage.mm
+++ b/Tests/Compositor/TestVideoSurfaceImage.mm
@@ -13,6 +13,7 @@
#include <LibGfx/MetalContext.h>
#include <LibGfx/SkiaBackendContext.h>
#include <LibGfx/VideoSurfaceImage.h>
+#include <LibMediaCodecs/VideoSurface.h>
#include <LibTest/TestCase.h>
#include <LibGfx/YUVData.h>
@@ -200,7 +201,7 @@ TEST_CASE(imports_an_eight_bit_surface_as_a_gpu_image)
auto surface = create_decoder_shaped_surface(64, 48, kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange);
VERIFY(surface.has_value());
- auto image = Compositor::sk_image_from_video_surface(*surface, {}, *context);
+ auto image = Compositor::sk_image_from_video_surface(MUST(Media::VideoSurface::create(surface.release_value())), {}, *context);
EXPECT(image != nullptr);
EXPECT_EQ(image->width(), 64);
EXPECT_EQ(image->height(), 48);
@@ -217,7 +218,7 @@ TEST_CASE(imports_a_ten_bit_surface_as_a_gpu_image)
auto surface = create_decoder_shaped_surface(64, 48, kCVPixelFormatType_420YpCbCr10BiPlanarVideoRange);
VERIFY(surface.has_value());
- auto image = Compositor::sk_image_from_video_surface(*surface, {}, *context);
+ auto image = Compositor::sk_image_from_video_surface(MUST(Media::VideoSurface::create(surface.release_value())), {}, *context);
EXPECT(image != nullptr);
EXPECT_EQ(image->width(), 64);
EXPECT_EQ(image->height(), 48);
@@ -231,7 +232,7 @@ TEST_CASE(refuses_a_surface_that_holds_no_video_planes)
return;
}
- auto surface = Core::IOSurfaceHandle::create(16, 16);
+ auto surface = MUST(Media::VideoSurface::create(Core::IOSurfaceHandle::create(16, 16)));
EXPECT(Compositor::sk_image_from_video_surface(surface, {}, *context) == nullptr);
}
@@ -248,7 +249,7 @@ TEST_CASE(a_surface_and_separate_planes_of_the_same_samples_render_alike)
VERIFY(surface.has_value());
fill_biplanar_surface(*surface, TEST_SAMPLE);
- auto surface_image = Compositor::sk_image_from_video_surface(*surface, {}, *context);
+ auto surface_image = Compositor::sk_image_from_video_surface(MUST(Media::VideoSurface::create(surface.release_value())), {}, *context);
VERIFY(surface_image != nullptr);
auto surface_color = center_pixel_of(surface_image, gr_context);
VERIFY(surface_color.has_value());
diff --git a/Tests/LibMedia/CMakeLists.txt b/Tests/LibMedia/CMakeLists.txt
index 64a4396c589..410db642f88 100644
--- a/Tests/LibMedia/CMakeLists.txt
+++ b/Tests/LibMedia/CMakeLists.txt
@@ -74,7 +74,7 @@ target_link_libraries(TestOggDemuxer PRIVATE LibThreading LibGfx)
target_link_libraries(TestWAVDemuxer PRIVATE LibThreading)
target_link_libraries(TestISOBMFF PRIVATE LibThreading)
target_link_libraries(TestMediaTime PRIVATE LibThreading)
-target_link_libraries(TestVideoFramePool PRIVATE LibThreading)
+target_link_libraries(TestVideoFramePool PRIVATE LibThreading LibIPC)
target_link_libraries(TestIncrementallyPopulatedStream PRIVATE LibThreading)
target_link_libraries(TestRemoteVideoDecoder PRIVATE LibThreading LibIPC LibMediaCodecs)
target_link_libraries(TestRemoteVideoNode PRIVATE LibThreading LibGfx LibIPC)
diff --git a/Tests/LibMedia/TestVideoFramePool.cpp b/Tests/LibMedia/TestVideoFramePool.cpp
index 83dd175d304..cfc623b229e 100644
--- a/Tests/LibMedia/TestVideoFramePool.cpp
+++ b/Tests/LibMedia/TestVideoFramePool.cpp
@@ -568,11 +568,69 @@ TEST_CASE(recycle_versus_hold_stress)
(void)consumer_thread->join();
}
-#ifdef AK_OS_MACOS
+// A frame shown a second time arrives as a second hold on the acquisition its slot is already held for, which must
+// not be mistaken for a slot given away while held.
+TEST_CASE(relay_pool_holds_a_slot_again_for_the_acquisition_it_already_holds)
+{
+ auto source_pool = MUST(Media::VideoFramePool::create());
+ auto acquired = source_pool->try_acquire(resolved_frame_byte_count()).release_value();
+
+ auto release_count = 0u;
+ auto relay_pool = MUST(Media::VideoFrameRelayPool::create([&](u32) { release_count++; }));
+ MUST(relay_pool->set_slot_storage(acquired.index, source_pool->slot_buffer(acquired.index), nullptr));
+
+ RefPtr<Media::PooledVideoFrameSlot> first_hold = MUST(relay_pool->try_adopt_published_slot(acquired.index, acquired.slot_acquisition_id));
+ RefPtr<Media::PooledVideoFrameSlot> second_hold = MUST(relay_pool->try_adopt_published_slot(acquired.index, acquired.slot_acquisition_id));
+ EXPECT(relay_pool->try_adopt_published_slot(acquired.index, acquired.slot_acquisition_id + 1).is_error());
+ // A frame lent onward holds the slot as well, which the other process never hears of.
+ relay_pool->add_hold(acquired.index);
+
+ first_hold = nullptr;
+ EXPECT_EQ(release_count, 0u);
+ second_hold = nullptr;
+ EXPECT_EQ(release_count, 0u);
+ // The other process holds the slot once per frame, so each of those holds is released to it once the slot is free.
+ relay_pool->release_hold(acquired.index);
+ EXPECT_EQ(release_count, 2u);
+}
+
+#if defined(AK_OS_MACOS) || defined(AK_OS_LINUX)
+
+// Stands in for what a decoder gives with a surface to keep its pixels in place, counting how many are alive.
+class TestSurfaceContents final : public Media::VideoSurfaceContents {
+public:
+ explicit TestSurfaceContents(Atomic<u32>& live_count)
+ : m_live_count(live_count)
+ {
+ m_live_count++;
+ }
+ virtual ~TestSurfaceContents() override { m_live_count--; }
+
+private:
+ Atomic<u32>& m_live_count;
+};
static NonnullRefPtr<Media::VideoSurface> make_surface()
{
+# ifdef AK_OS_MACOS
return MUST(Media::VideoSurface::create(Core::IOSurfaceHandle::create(16, 16)));
+# else
+ static u32 s_next_surface_id = 1;
+ Gfx::LinuxDmaBufHandle dma_buf;
+ dma_buf.size = { 16, 16 };
+ return MUST(Media::VideoSurface::create_from_dma_buf(s_next_surface_id++, move(dma_buf)));
+# endif
+}
+
+static NonnullRefPtr<Media::VideoSurfaceContents> make_contents(Atomic<u32>& live_count)
+{
+ return make_ref_counted<TestSurfaceContents>(live_count);
+}
+
+static NonnullRefPtr<Media::VideoSurfaceContents> make_contents()
+{
+ static Atomic<u32> s_unwatched_live_count { 0 };
+ return make_contents(s_unwatched_live_count);
}
TEST_CASE(surface_pool_keeps_a_recycled_surface_on_its_slot)
@@ -580,9 +638,9 @@ TEST_CASE(surface_pool_keeps_a_recycled_surface_on_its_slot)
auto pool = MUST(Media::VideoFrameSurfacePool::create());
auto surface = make_surface();
- auto first = pool->try_acquire(surface).value();
+ auto first = pool->try_acquire(surface, make_contents()).value();
pool->release_hold(first.index);
- auto second = pool->try_acquire(surface).value();
+ auto second = pool->try_acquire(surface, make_contents()).value();
// Announcement is keyed on the slot's buffer generation, so a recycled surface must not appear to be a new one.
EXPECT_EQ(second.index, first.index);
@@ -590,79 +648,73 @@ TEST_CASE(surface_pool_keeps_a_recycled_surface_on_its_slot)
EXPECT_NE(second.slot_acquisition_id, first.slot_acquisition_id);
}
-TEST_CASE(surface_pool_stops_using_a_surface_once_its_holds_run_out)
+TEST_CASE(surface_pool_drops_the_contents_with_the_last_hold)
{
+ Atomic<u32> live_contents { 0 };
auto pool = MUST(Media::VideoFrameSurfacePool::create());
auto surface = make_surface();
- auto first = pool->try_acquire(surface).value();
- EXPECT(surface->is_in_use());
+ auto first = pool->try_acquire(surface, make_contents(live_contents)).value();
+ EXPECT_EQ(live_contents.load(), 1u);
+ pool->add_hold(first.index);
pool->release_hold(first.index);
+ EXPECT_EQ(live_contents.load(), 1u);
- // The decoder is free to decode into it again, which it can only be recognized for having done because the
- // slot kept hold of the surface through it.
- EXPECT(!surface->is_in_use());
+ // The decoder is free to decode into the surface again, which the slot recognizes it for having done because
+ // it kept the surface through the release.
+ pool->release_hold(first.index);
+ EXPECT_EQ(live_contents.load(), 0u);
- auto second = pool->try_acquire(surface).value();
- EXPECT(surface->is_in_use());
+ auto second = pool->try_acquire(surface, make_contents(live_contents)).value();
+ EXPECT_EQ(live_contents.load(), 1u);
EXPECT_EQ(second.index, first.index);
EXPECT_EQ(second.allocated_buffer_id, first.allocated_buffer_id);
}
-TEST_CASE(a_resolved_frame_keeps_using_a_surface_its_slot_has_released)
+// A decoder can hand a surface back while it is held, as when a frame is shown a second time. The pixels are the
+// ones the slot already keeps, so the frame joins the acquisition instead of starting one.
+TEST_CASE(surface_pool_holds_a_held_surface_again_when_it_is_handed_back)
{
+ Atomic<u32> live_contents { 0 };
auto pool = MUST(Media::VideoFrameSurfacePool::create());
auto surface = make_surface();
- auto acquired = pool->try_acquire(surface).value();
-
- auto directory = Media::VideoFrameSlotDirectory::create();
- directory->notify_slot_announced(pool->id(), acquired.index, pool->slot_buffer(acquired.index), pool->slot_surface(acquired.index));
-
- auto handle = Media::VideoFrameHandle {
- .pool_id = pool->id(),
- .slot_index = acquired.index,
- .slot_acquisition_id = acquired.slot_acquisition_id,
- .timestamp = AK::Duration::from_milliseconds(40),
- .duration = AK::Duration::from_milliseconds(20),
- .size = { 16, 16 },
- .bit_depth = 8,
- .subsampling = Media::Subsampling(true, true),
- .cicp = {},
- };
- auto frame = directory->resolve_frame(handle, [] { });
- EXPECT(frame != nullptr);
- // A lend can be released from under a frame, so the frame is what has to say it is still reading the pixels.
- pool->release_hold(acquired.index);
- EXPECT(surface->is_in_use());
+ auto first = pool->try_acquire(surface, make_contents(live_contents)).value();
+ auto again = pool->try_acquire(surface, make_contents(live_contents)).value();
+ EXPECT_EQ(again.index, first.index);
+ EXPECT_EQ(again.slot_acquisition_id, first.slot_acquisition_id);
+ EXPECT_EQ(live_contents.load(), 1u);
- frame = nullptr;
- EXPECT(!surface->is_in_use());
+ pool->release_hold(first.index);
+ EXPECT_EQ(live_contents.load(), 1u);
+ pool->release_hold(first.index);
+ EXPECT_EQ(live_contents.load(), 0u);
}
TEST_CASE(shed_storage_releases_surfaces_as_their_holds_run_out)
{
+ Atomic<u32> live_contents { 0 };
auto pool = MUST(Media::VideoFrameSurfacePool::create());
auto held_surface = make_surface();
auto free_surface = make_surface();
- auto held = pool->try_acquire(held_surface).value();
- auto freed = pool->try_acquire(free_surface).value();
+ auto held = pool->try_acquire(held_surface, make_contents(live_contents)).value();
+ auto freed = pool->try_acquire(free_surface, make_contents(live_contents)).value();
pool->release_hold(freed.index);
pool->shed_storage();
- // Nothing but this test refers to a surface the pool has let go of, while the held one is still being read.
+ // Nothing but this test refers to a surface the pool has let go of, while the held one's pixels are still kept.
EXPECT_EQ(free_surface->ref_count(), 1u);
- EXPECT(held_surface->is_in_use());
+ EXPECT_EQ(live_contents.load(), 1u);
pool->release_hold(held.index);
EXPECT_EQ(held_surface->ref_count(), 1u);
- EXPECT(!held_surface->is_in_use());
+ EXPECT_EQ(live_contents.load(), 0u);
// The identities went with them, so a surface the pool held through the shed is a stranger to it again.
- auto reacquired = pool->try_acquire(held_surface).value();
+ auto reacquired = pool->try_acquire(held_surface, make_contents(live_contents)).value();
EXPECT_NE(reacquired.allocated_buffer_id, held.allocated_buffer_id);
}
@@ -674,8 +726,8 @@ TEST_CASE(surface_pool_gives_distinct_surfaces_distinct_slots)
auto second_surface = make_surface();
EXPECT_NE(first_surface->id(), second_surface->id());
- auto first = pool->try_acquire(first_surface).value();
- auto second = pool->try_acquire(second_surface).value();
+ 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);
}
@@ -688,14 +740,14 @@ TEST_CASE(surface_pool_refuses_to_exceed_its_slot_count)
Vector<NonnullRefPtr<Media::VideoSurface>> surfaces;
for (u32 index = 0; index < Media::VideoFrameSurfacePool::MAX_SLOT_COUNT; index++) {
surfaces.append(make_surface());
- EXPECT(pool->try_acquire(surfaces.last()).has_value());
+ EXPECT(pool->try_acquire(surfaces.last(), make_contents()).has_value());
}
auto surface_too_many = make_surface();
- EXPECT(!pool->try_acquire(surface_too_many).has_value());
+ EXPECT(!pool->try_acquire(surface_too_many, make_contents()).has_value());
pool->release_hold(0);
- EXPECT(pool->try_acquire(surface_too_many).has_value());
+ EXPECT(pool->try_acquire(surface_too_many, make_contents()).has_value());
}
TEST_CASE(surface_pool_evicts_the_least_recently_acquired_identity_when_full)
@@ -706,33 +758,34 @@ TEST_CASE(surface_pool_evicts_the_least_recently_acquired_identity_when_full)
Vector<Media::VideoFrameSurfacePool::AcquiredSlot> acquisitions;
for (u32 index = 0; index < Media::VideoFrameSurfacePool::MAX_SLOT_COUNT; index++) {
surfaces.append(make_surface());
- acquisitions.append(pool->try_acquire(surfaces.last()).value());
+ acquisitions.append(pool->try_acquire(surfaces.last(), make_contents()).value());
}
for (auto const& acquisition : acquisitions)
pool->release_hold(acquisition.index);
// Every slot remembers a surface, so a surface the pool has never seen has to displace one of them.
auto new_surface = make_surface();
- auto acquired = pool->try_acquire(new_surface).value();
+ auto acquired = pool->try_acquire(new_surface, make_contents()).value();
EXPECT_EQ(acquired.index, acquisitions.first().index);
EXPECT_NE(acquired.allocated_buffer_id, acquisitions.first().allocated_buffer_id);
pool->release_hold(acquired.index);
// The surface that was displaced is a stranger again, while the ones still on their slots are not.
- auto reacquired_evicted = pool->try_acquire(surfaces.first()).value();
+ auto reacquired_evicted = pool->try_acquire(surfaces.first(), make_contents()).value();
EXPECT_NE(reacquired_evicted.allocated_buffer_id, acquisitions.first().allocated_buffer_id);
pool->release_hold(reacquired_evicted.index);
- auto reacquired_kept = pool->try_acquire(surfaces.last()).value();
+ auto reacquired_kept = pool->try_acquire(surfaces.last(), make_contents()).value();
EXPECT_EQ(reacquired_kept.index, acquisitions.last().index);
EXPECT_EQ(reacquired_kept.allocated_buffer_id, acquisitions.last().allocated_buffer_id);
}
+# ifdef AK_OS_MACOS
TEST_CASE(surface_slots_survive_a_mach_port_round_trip)
{
auto pool = MUST(Media::VideoFrameSurfacePool::create());
auto surface = make_surface();
- auto acquired = pool->try_acquire(surface).value();
+ auto acquired = pool->try_acquire(surface, make_contents()).value();
auto lent_surface = pool->slot_surface(acquired.index);
EXPECT_NE(lent_surface, nullptr);
@@ -742,12 +795,13 @@ TEST_CASE(surface_slots_survive_a_mach_port_round_trip)
EXPECT_EQ(reimported.width(), 16u);
EXPECT_EQ(reimported.height(), 16u);
}
+# endif
TEST_CASE(directory_resolves_an_announced_surface_slot)
{
auto pool = MUST(Media::VideoFrameSurfacePool::create());
auto surface = make_surface();
- auto acquired = pool->try_acquire(surface).value();
+ auto acquired = pool->try_acquire(surface, make_contents()).value();
auto directory = Media::VideoFrameSlotDirectory::create();
directory->notify_slot_announced(pool->id(), acquired.index, pool->slot_buffer(acquired.index), pool->slot_surface(acquired.index));
@@ -778,7 +832,7 @@ TEST_CASE(surface_slots_hold_and_free_through_the_shared_ledger)
auto freed_count = 0u;
auto pool = MUST(Media::VideoFrameSurfacePool::create());
pool->set_slot_freed_callback([&] { freed_count++; });
- auto acquired = pool->try_acquire(make_surface()).value();
+ auto acquired = pool->try_acquire(make_surface(), make_contents()).value();
pool->add_hold(acquired.index);
pool->release_hold(acquired.index);