Skip to content

Truly independent web browser

LibMedia+LibMediaCodecs+Compositor: Lend video frames in messages

Zaggy1024909c77808f60
diff --git a/Libraries/LibMedia/CMakeLists.txt b/Libraries/LibMedia/CMakeLists.txt
index 2f986435392..ac71f85154e 100644
--- a/Libraries/LibMedia/CMakeLists.txt
+++ b/Libraries/LibMedia/CMakeLists.txt
@@ -66,7 +66,6 @@ set(SOURCES
Sinks/RemoteVideoSink.cpp
TimeRanges.cpp
Track.cpp
- VideoEdgeQueue.cpp
VideoPresentation/VideoPresentationClientConnection.cpp
VideoPresentation/VideoPresentationServerConnection.cpp
)
diff --git a/Libraries/LibMedia/Producers/RemoteVideoProducer.cpp b/Libraries/LibMedia/Producers/RemoteVideoProducer.cpp
index b63bd600550..033968424ab 100644
--- a/Libraries/LibMedia/Producers/RemoteVideoProducer.cpp
+++ b/Libraries/LibMedia/Producers/RemoteVideoProducer.cpp
@@ -9,103 +9,59 @@
namespace Media {
-struct RemoteVideoProducer::LentSlotReleaser : public AtomicRefCounted<LentSlotReleaser> {
- explicit LentSlotReleaser(Function<void(VideoFramePoolID, u32 slot_index)> release_slot)
- : release_slot(move(release_slot))
- {
- }
-
- Function<void(VideoFramePoolID, u32 slot_index)> release_slot;
-};
-
-NonnullRefPtr<RemoteVideoProducer> RemoteVideoProducer::create(VideoEdgeQueue edge, NonnullRefPtr<VideoFrameSlotDirectory> slot_directory, Delegates delegates)
+NonnullRefPtr<RemoteVideoProducer> RemoteVideoProducer::create(Delegates delegates)
{
VERIFY(delegates.request_start);
VERIFY(delegates.request_seek);
- VERIFY(delegates.release_slot);
- VERIFY(delegates.notify_space_available);
- auto producer = adopt_ref(*new RemoteVideoProducer(move(edge), move(slot_directory), move(delegates)));
- // A queued frame may have failed to resolve before its announcement arrived, so retry promptly.
- producer->m_slot_directory->set_on_slots_changed([weak = producer->make_weak_ref()] {
- if (auto strong = weak.strong_ref())
- strong->m_wake_handler.dispatch();
- });
- return producer;
+ return adopt_ref(*new RemoteVideoProducer(move(delegates)));
}
-RemoteVideoProducer::RemoteVideoProducer(VideoEdgeQueue edge, NonnullRefPtr<VideoFrameSlotDirectory> slot_directory, Delegates delegates)
- : m_edge(move(edge))
- , m_slot_directory(move(slot_directory))
- , m_lent_slot_releaser(adopt_ref(*new LentSlotReleaser(move(delegates.release_slot))))
+RemoteVideoProducer::RemoteVideoProducer(Delegates delegates)
+ : m_delegates(move(delegates))
{
- m_delegates = move(delegates);
}
RemoteVideoProducer::~RemoteVideoProducer() = default;
void RemoteVideoProducer::stop_consuming()
{
- if (m_current_frame) {
- m_current_frame = nullptr;
- m_edge.consume();
- }
+ m_queued_frames.clear();
m_has_stopped_consuming = true;
}
-void RemoteVideoProducer::notify_data_available()
+void RemoteVideoProducer::receive_frame(u64 lend_id, u32 seek_id, NonnullRefPtr<VideoFrame> frame)
{
- if (m_has_stopped_consuming)
+ m_newest_received_lend_id = max(m_newest_received_lend_id, lend_id);
+ if (m_has_stopped_consuming || seek_id != m_expected_seek_id)
return;
- release_ring_contents_if_suspended();
+ if (m_queued_frames.size() >= MAX_QUEUED_FRAME_COUNT) {
+ dbgln("RemoteVideoProducer: Releasing a frame received past the limit of {} queued frames", MAX_QUEUED_FRAME_COUNT);
+ return;
+ }
+ m_queued_frames.append(move(frame));
m_wake_handler.dispatch();
}
-void RemoteVideoProducer::release_ring_contents_if_suspended()
+void RemoteVideoProducer::receive_status(PipelineStatus status, u32 seek_id)
{
- auto status = m_edge.status();
- if (!status.has_value() || status->seek_id != m_expected_seek_id || status->status != PipelineStatus::Suspended)
+ if (m_has_stopped_consuming)
return;
-
- release_all_ring_frames();
- m_slot_directory->notify_all_pools_retired();
-}
-
-void RemoteVideoProducer::discard_ring_head(VideoEdgeItem const& head)
-{
- // A head already resolved into the current frame releases its lend through that frame instead.
- if (m_current_frame)
- m_current_frame = nullptr;
- else
- release_lent_slot(head.handle.pool_id, head.handle.slot_index);
- m_edge.consume();
-}
-
-void RemoteVideoProducer::discard_stale_ring_heads()
-{
- auto discarded_any_frames = false;
- while (true) {
- auto head = m_edge.peek();
- if (!head.has_value() || (head->seek_id == m_expected_seek_id && head->handle.is_valid()))
- break;
- discard_ring_head(*head);
- discarded_any_frames = true;
- }
- if (discarded_any_frames)
- m_delegates.notify_space_available();
+ // A peer can send any value for the status.
+ if (to_underlying(status) > to_underlying(PipelineStatus::Error))
+ status = PipelineStatus::Error;
+ m_status = ReceivedStatus { status, seek_id };
+
+ // A suspended producer has let go of its decoder, and resuming seeks past the frames it lent anyway.
+ if (status == PipelineStatus::Suspended && seek_id == m_expected_seek_id)
+ m_queued_frames.clear();
+ m_wake_handler.dispatch();
}
-void RemoteVideoProducer::release_all_ring_frames()
+void RemoteVideoProducer::notify_clock_resumed()
{
- auto released_any_frames = false;
- while (true) {
- auto head = m_edge.peek();
- if (!head.has_value())
- break;
- discard_ring_head(*head);
- released_any_frames = true;
- }
- if (released_any_frames)
- m_delegates.notify_space_available();
+ if (m_has_stopped_consuming)
+ return;
+ m_wake_handler.dispatch();
}
void RemoteVideoProducer::start()
@@ -122,80 +78,46 @@ void RemoteVideoProducer::seek(AK::Duration timestamp, InvalidateHeldData invali
{
if (m_has_stopped_consuming)
return;
- discard_stale_ring_heads();
-
- // Announced before the ring is consulted, paired with the fence in the pump before it consumes an enqueued frame
- // from its input: either the look below sees the frame, or the pump sees the request and leaves the frame in its
- // input for the seek to find. A locally satisfied seek withdraws the announcement; the pump is woken by the
- // consume that follows.
- auto requested_seek_id = m_expected_seek_id + 1;
- m_edge.set_requested_seek_id(requested_seek_id);
- AK::atomic_thread_fence(AK::MemoryOrder::memory_order_seq_cst);
- if (invalidate_held_data == InvalidateHeldData::No && can_satisfy_seek_locally(timestamp)) {
- m_edge.set_requested_seek_id(m_expected_seek_id);
+ if (invalidate_held_data == InvalidateHeldData::No && can_satisfy_seek_locally(timestamp))
return;
- }
- m_expected_seek_id = requested_seek_id;
- m_delegates.request_seek(timestamp, invalidate_held_data);
- discard_stale_ring_heads();
+ // Released only after the request, so that the sink hears of the seek before their storage is decoded into again.
+ auto stale_frames = move(m_queued_frames);
+ m_expected_seek_id++;
+ m_delegates.request_seek(timestamp, invalidate_held_data, m_newest_received_lend_id);
+ stale_frames.clear();
+}
+
+bool RemoteVideoProducer::has_end_of_stream_status() const
+{
+ return m_status.has_value() && m_status->seek_id == m_expected_seek_id && m_status->status == PipelineStatus::EndOfStream;
}
bool RemoteVideoProducer::can_satisfy_seek_locally(AK::Duration timestamp) const
{
- // The lookahead is the ring itself, from its head to the conservative end of its newest frame. Only this side
- // moves the head, so the two reads describe one snapshot of the ring.
- auto head = m_edge.peek();
- if (!head.has_value() || head->seek_id != m_expected_seek_id || timestamp < head->handle.timestamp)
+ if (m_queued_frames.is_empty() || timestamp < m_queued_frames.first()->timestamp())
return false;
- auto newest = m_edge.peek_newest();
- if (!newest.has_value() || !newest->handle.is_valid())
- return false;
- if (timestamp < newest->handle.conservative_end())
+ if (timestamp < m_queued_frames.last()->conservative_end())
return true;
- auto status = m_edge.status();
- return status.has_value() && status->seek_id == m_expected_seek_id && status->status == PipelineStatus::EndOfStream;
+ return has_end_of_stream_status();
}
VideoProducerOutput RemoteVideoProducer::peek()
{
if (m_has_stopped_consuming)
return { nullptr, PipelineStatus::Pending };
- discard_stale_ring_heads();
- auto head = m_edge.peek();
- if (!head.has_value()) {
- auto status = m_edge.status();
- if (!status.has_value() || status->seek_id != m_expected_seek_id)
- return { nullptr, PipelineStatus::Pending };
- return { nullptr, status->status };
- }
-
- if (!m_current_frame)
- m_current_frame = resolve(head->handle);
- if (!m_current_frame)
+ if (!m_queued_frames.is_empty())
+ return { m_queued_frames.first(), PipelineStatus::HaveData };
+ if (!m_status.has_value() || m_status->seek_id != m_expected_seek_id)
return { nullptr, PipelineStatus::Pending };
- return { m_current_frame, PipelineStatus::HaveData };
+ return { nullptr, m_status->status };
}
void RemoteVideoProducer::consume()
{
- if (m_has_stopped_consuming)
+ if (m_has_stopped_consuming || m_queued_frames.is_empty())
return;
- m_current_frame = nullptr;
- m_edge.consume();
- m_delegates.notify_space_available();
-}
-
-void RemoteVideoProducer::release_lent_slot(VideoFramePoolID pool_id, u32 slot_index) const
-{
- m_lent_slot_releaser->release_slot(pool_id, slot_index);
-}
-
-RefPtr<VideoFrame> RemoteVideoProducer::resolve(VideoFrameHandle const& handle)
-{
- return m_slot_directory->resolve_frame(handle, [releaser = m_lent_slot_releaser, pool_id = handle.pool_id, slot_index = handle.slot_index] {
- releaser->release_slot(pool_id, slot_index);
- });
+ m_queued_frames.remove(0);
}
}
diff --git a/Libraries/LibMedia/Producers/RemoteVideoProducer.h b/Libraries/LibMedia/Producers/RemoteVideoProducer.h
index 7adbd774b05..d9404d86f22 100644
--- a/Libraries/LibMedia/Producers/RemoteVideoProducer.h
+++ b/Libraries/LibMedia/Producers/RemoteVideoProducer.h
@@ -11,35 +11,34 @@
#include <AK/RefPtr.h>
#include <AK/ThreadSafeWeakable.h>
#include <AK/Time.h>
+#include <AK/Vector.h>
#include <LibMedia/Export.h>
#include <LibMedia/Forward.h>
#include <LibMedia/Producers/VideoProducer.h>
#include <LibMedia/SynchronizedWakeHandler.h>
-#include <LibMedia/VideoEdgeQueue.h>
-#include <LibMediaCodecs/VideoFrameHandle.h>
-#include <LibMediaCodecs/VideoFramePool.h>
namespace Media {
-// The consumer end of a cross-process video edge: reads frame handles through a shared memory VideoEdgeQueue, resolves
-// them through the edge's VideoFrameSlotDirectory, and presents them through the VideoProducer interface, so a
-// DisplayingVideoSink consumes it exactly as it would a local producer. Communication crosses the process boundary
-// through delegates that relay messages over IPC.
+// The consumer end of a cross-process video edge.
class MEDIA_API RemoteVideoProducer final
: public VideoProducer
, public ThreadSafeWeakable<RemoteVideoProducer> {
public:
+ // A frame arriving past this is released.
+ static constexpr size_t MAX_QUEUED_FRAME_COUNT = 32;
+
struct Delegates {
Function<void()> request_start;
- Function<void(AK::Duration, InvalidateHeldData)> request_seek;
- Function<void(VideoFramePoolID, u32 slot_index)> release_slot;
- Function<void()> notify_space_available;
+ Function<void(AK::Duration, InvalidateHeldData, u64 newest_received_lend_id)> request_seek;
};
- static NonnullRefPtr<RemoteVideoProducer> create(VideoEdgeQueue, NonnullRefPtr<VideoFrameSlotDirectory>, Delegates);
+ static NonnullRefPtr<RemoteVideoProducer> create(Delegates);
virtual ~RemoteVideoProducer() override;
- void notify_data_available();
+ // Dropping the frame releases it back to the sink.
+ void receive_frame(u64 lend_id, u32 seek_id, NonnullRefPtr<VideoFrame>);
+ void receive_status(PipelineStatus, u32 seek_id);
+ void notify_clock_resumed();
void stop_consuming();
@@ -50,26 +49,24 @@ public:
virtual void seek(AK::Duration timestamp, InvalidateHeldData = InvalidateHeldData::No) override;
private:
- RemoteVideoProducer(VideoEdgeQueue, NonnullRefPtr<VideoFrameSlotDirectory>, Delegates);
+ explicit RemoteVideoProducer(Delegates);
- RefPtr<VideoFrame> resolve(VideoFrameHandle const&);
- void release_lent_slot(VideoFramePoolID, u32 slot_index) const;
- bool can_satisfy_seek_locally(AK::Duration timestamp) const;
- void release_ring_contents_if_suspended();
- void discard_ring_head(VideoEdgeItem const&);
- void discard_stale_ring_heads();
- void release_all_ring_frames();
+ struct ReceivedStatus {
+ PipelineStatus status { PipelineStatus::Pending };
+ u32 seek_id { 0 };
+ };
- struct LentSlotReleaser;
+ bool can_satisfy_seek_locally(AK::Duration timestamp) const;
+ bool has_end_of_stream_status() const;
- VideoEdgeQueue m_edge;
- NonnullRefPtr<VideoFrameSlotDirectory> m_slot_directory;
Delegates m_delegates;
- NonnullRefPtr<LentSlotReleaser> m_lent_slot_releaser;
bool m_has_stopped_consuming { false };
u32 m_expected_seek_id { 0 };
- RefPtr<VideoFrame> m_current_frame;
+ u64 m_newest_received_lend_id { 0 };
+ // Received under the expected seek, oldest first.
+ Vector<NonnullRefPtr<VideoFrame>> m_queued_frames;
+ Optional<ReceivedStatus> m_status;
SynchronizedWakeHandler m_wake_handler;
};
diff --git a/Libraries/LibMedia/Sinks/RemoteVideoSink.cpp b/Libraries/LibMedia/Sinks/RemoteVideoSink.cpp
index 5a51995d788..19192d6a2ec 100644
--- a/Libraries/LibMedia/Sinks/RemoteVideoSink.cpp
+++ b/Libraries/LibMedia/Sinks/RemoteVideoSink.cpp
@@ -8,8 +8,9 @@
#include <AK/ConditionVariable.h>
#include <AK/HashMap.h>
#include <AK/Mutex.h>
+#include <AK/QuickSort.h>
+#include <LibMedia/Producers/VideoProducer.h>
#include <LibMedia/Sinks/RemoteVideoSink.h>
-#include <LibMedia/VideoEdgeQueue.h>
#include <LibMediaCodecs/VideoFrame.h>
#include <LibMediaCodecs/VideoSurface.h>
#include <LibThreading/Thread.h>
@@ -18,55 +19,39 @@ namespace Media {
class RemoteVideoSink::ThreadData : public AtomicRefCounted<RemoteVideoSink::ThreadData> {
public:
- ThreadData(VideoEdgeQueue, Delegates);
+ explicit ThreadData(Delegates);
~ThreadData();
- VideoEdgeQueue const& edge() const { return m_edge; }
ErrorOr<void> connect_input(NonnullRefPtr<VideoProducer> const&);
void disconnect_input(NonnullRefPtr<VideoProducer> const&);
- void ring_data_available() const;
+ void notify_clock_resumed() const;
void transmit_seek(InvalidateHeldData) const;
void transmit_time_reader(MediaTimeReader const&) const;
- void seek_upstream(AK::Duration timestamp, InvalidateHeldData);
+ void seek_upstream(AK::Duration timestamp, InvalidateHeldData, u64 newest_received_lend_id);
void seek_input_directly(AK::Duration timestamp);
void start_input();
- void notify_space_available();
- void release_slot(VideoFramePoolID, u32 slot_index);
+ void release_frame(u64 lend_id);
void pump_thread_loop();
void request_exit();
- void stop_and_reclaim_unconsumed_frames();
- bool has_lent_slots() const;
- void release_all_lends();
+ void stop();
+ bool has_lent_frames() const;
private:
- struct LentPool {
- NonnullRefPtr<VideoFrameEntryLedger> ledger;
- HashMap<u32, u32> lend_counts_by_slot_index;
- HashMap<u32, u64> announced_allocated_buffer_ids_by_slot_index;
- u64 outstanding_lend_count { 0 };
- };
-
- struct LentSlot {
- VideoFramePoolID pool_id;
- u32 slot_index { 0 };
+ struct PublishedStatus {
+ PipelineStatus status { PipelineStatus::Pending };
+ u32 seek_id { 0 };
- bool operator==(LentSlot const&) const = default;
- };
- struct LentSlotTraits : public DefaultTraits<LentSlot> {
- static unsigned hash(LentSlot const& slot) { return pair_int_hash(u64_hash(slot.pool_id.value()), slot.slot_index); }
- };
- struct LentFrameRange {
- AK::Duration timestamp;
- AK::Duration conservative_end;
+ bool operator==(PublishedStatus const&) const = default;
};
- void enqueue_frame(VideoFrame const&, u32 seek_id);
- void lend_slot(VideoFrame const&);
+ void lend_frame(NonnullRefPtr<VideoFrame> const&, u32 seek_id);
+ void publish_status(PublishedStatus);
bool consumer_may_satisfy_seek_locally(AK::Duration timestamp) const;
+ Vector<NonnullRefPtr<VideoFrame>> frames_lent_after_holding(u64 newest_received_lend_id, AK::Duration timestamp) const;
void wait_on_pump_thread(MutexLocker<Mutex>&);
+ void wake_pump_thread();
- VideoEdgeQueue m_edge;
Delegates m_delegates;
mutable Mutex m_mutex;
@@ -78,23 +63,25 @@ private:
u32 m_actual_seek_id { 0 };
// A seek the input was given directly, whose request from the consumer has yet to arrive.
Optional<AK::Duration> m_direct_seek_timestamp;
- // The frame the pump has taken from the input and has yet to lend.
- Optional<LentFrameRange> m_peeked_frame_range;
-
- mutable Mutex m_lent_pools_mutex;
- HashMap<VideoFramePoolID, LentPool> m_lent_pools;
- HashMap<LentSlot, LentFrameRange, LentSlotTraits> m_lent_frame_ranges;
+ // Still in the input until it has been lent.
+ RefPtr<VideoFrame> m_peeked_frame;
+ // Lent again under the next seek's stamp before anything newer is taken from the input.
+ Vector<NonnullRefPtr<VideoFrame>> m_frames_to_lend_again;
+ Optional<PublishedStatus> m_published_status;
+
+ mutable Mutex m_lent_frames_mutex;
+ OrderedHashMap<u64, NonnullRefPtr<VideoFrame>> m_lent_frames;
+ u64 m_next_lend_id { 1 };
};
ErrorOr<NonnullRefPtr<RemoteVideoSink>> RemoteVideoSink::create(Delegates delegates)
{
- VERIFY(delegates.ring_data_available);
+ VERIFY(delegates.send_frame);
+ VERIFY(delegates.send_status);
+ VERIFY(delegates.notify_clock_resumed);
VERIFY(delegates.transmit_seek);
VERIFY(delegates.transmit_time_reader);
- VERIFY(delegates.announce_slot);
- VERIFY(delegates.retire_pool);
- auto edge = TRY(VideoEdgeQueue::create());
- auto thread_data = TRY(adopt_nonnull_ref_or_enomem(new (nothrow) ThreadData(move(edge), move(delegates))));
+ auto thread_data = TRY(adopt_nonnull_ref_or_enomem(new (nothrow) ThreadData(move(delegates))));
auto sink = TRY(adopt_nonnull_ref_or_enomem(new (nothrow) RemoteVideoSink(thread_data)));
auto thread = Threading::Thread::construct("Video Pump"sv, [thread_data]() -> intptr_t {
thread_data->pump_thread_loop();
@@ -115,8 +102,6 @@ RemoteVideoSink::~RemoteVideoSink()
m_thread_data->request_exit();
}
-VideoEdgeQueue const& RemoteVideoSink::edge() const { return m_thread_data->edge(); }
-
ErrorOr<void> RemoteVideoSink::connect_input(NonnullRefPtr<VideoProducer> const& producer) { return m_thread_data->connect_input(producer); }
void RemoteVideoSink::disconnect_input(NonnullRefPtr<VideoProducer> const& producer) { m_thread_data->disconnect_input(producer); }
@@ -126,8 +111,8 @@ void RemoteVideoSink::seek(AK::Duration timestamp, InvalidateHeldData invalidate
m_thread_data->seek_input_directly(timestamp);
m_thread_data->transmit_seek(invalidate_held_data);
}
-void RemoteVideoSink::notify_clock_resumed() { m_thread_data->ring_data_available(); }
-void RemoteVideoSink::seek_upstream(AK::Duration timestamp, InvalidateHeldData invalidate_held_data) { m_thread_data->seek_upstream(timestamp, invalidate_held_data); }
+void RemoteVideoSink::notify_clock_resumed() { m_thread_data->notify_clock_resumed(); }
+void RemoteVideoSink::seek_upstream(AK::Duration timestamp, InvalidateHeldData invalidate_held_data, u64 newest_received_lend_id) { m_thread_data->seek_upstream(timestamp, invalidate_held_data, newest_received_lend_id); }
void RemoteVideoSink::set_time_reader(MediaTimeReader time_reader)
{
@@ -157,29 +142,20 @@ void RemoteVideoSink::report_remote_resize(Gfx::Size<u32> size)
}
void RemoteVideoSink::start_input() { m_thread_data->start_input(); }
-void RemoteVideoSink::notify_space_available() { m_thread_data->notify_space_available(); }
-void RemoteVideoSink::release_slot(VideoFramePoolID pool_id, u32 slot_index) { m_thread_data->release_slot(pool_id, slot_index); }
-void RemoteVideoSink::stop_and_reclaim_unconsumed_frames() { m_thread_data->stop_and_reclaim_unconsumed_frames(); }
-bool RemoteVideoSink::has_lent_slots() const { return m_thread_data->has_lent_slots(); }
-
-RemoteVideoSink::ThreadData::ThreadData(VideoEdgeQueue edge, Delegates delegates)
- : m_edge(move(edge))
- , m_delegates(move(delegates))
-{
-}
+void RemoteVideoSink::release_frame(u64 lend_id) { m_thread_data->release_frame(lend_id); }
+void RemoteVideoSink::stop() { m_thread_data->stop(); }
+bool RemoteVideoSink::has_lent_frames() const { return m_thread_data->has_lent_frames(); }
-RemoteVideoSink::ThreadData::~ThreadData()
+RemoteVideoSink::ThreadData::ThreadData(Delegates delegates)
+ : m_delegates(move(delegates))
{
- release_all_lends();
}
+RemoteVideoSink::ThreadData::~ThreadData() = default;
+
ErrorOr<void> RemoteVideoSink::ThreadData::connect_input(NonnullRefPtr<VideoProducer> const& producer)
{
- producer->set_wake_handler([this] {
- MutexLocker locker { m_mutex };
- m_wake_pending = true;
- m_wait_condition.broadcast();
- });
+ producer->set_wake_handler([this] { wake_pump_thread(); });
MutexLocker locker { m_mutex };
VERIFY(m_input == nullptr);
m_input = producer;
@@ -197,9 +173,9 @@ void RemoteVideoSink::ThreadData::disconnect_input(NonnullRefPtr<VideoProducer>
m_direct_seek_timestamp = {};
}
-void RemoteVideoSink::ThreadData::ring_data_available() const
+void RemoteVideoSink::ThreadData::notify_clock_resumed() const
{
- m_delegates.ring_data_available();
+ m_delegates.notify_clock_resumed();
}
void RemoteVideoSink::ThreadData::transmit_seek(InvalidateHeldData invalidate_held_data) const
@@ -212,44 +188,71 @@ void RemoteVideoSink::ThreadData::transmit_time_reader(MediaTimeReader const& ti
m_delegates.transmit_time_reader(time_reader);
}
-void RemoteVideoSink::ThreadData::seek_upstream(AK::Duration timestamp, InvalidateHeldData invalidate_held_data)
+Vector<NonnullRefPtr<VideoFrame>> RemoteVideoSink::ThreadData::frames_lent_after_holding(u64 newest_received_lend_id, AK::Duration timestamp) const
+{
+ // A frame lent again for an earlier seek is lent twice.
+ Vector<NonnullRefPtr<VideoFrame>> frames;
+ {
+ MutexLocker locker { m_lent_frames_mutex };
+ for (auto const& [lend_id, frame] : m_lent_frames) {
+ if (lend_id <= newest_received_lend_id)
+ continue;
+ if (!frames.contains_slow(frame))
+ frames.append(frame);
+ }
+ }
+ quick_sort(frames, [](auto const& a, auto const& b) { return a->timestamp() < b->timestamp(); });
+ if (frames.is_empty() || timestamp < frames.first()->timestamp() || timestamp >= frames.last()->conservative_end())
+ return {};
+
+ // The frame still in the input is lent again by taking it from the input.
+ frames.remove_all_matching([&](auto const& frame) {
+ return frame->end() <= timestamp || frame.ptr() == m_peeked_frame.ptr();
+ });
+ return frames;
+}
+
+void RemoteVideoSink::ThreadData::seek_upstream(AK::Duration timestamp, InvalidateHeldData invalidate_held_data, u64 newest_received_lend_id)
{
MutexLocker locker { m_mutex };
auto direct_seek_timestamp = m_direct_seek_timestamp;
m_direct_seek_timestamp = {};
- auto seek_was_given_directly = direct_seek_timestamp == timestamp && invalidate_held_data == InvalidateHeldData::No;
- if (m_input && !seek_was_given_directly)
- m_input->seek(timestamp, invalidate_held_data);
+ m_frames_to_lend_again.clear();
m_actual_seek_id++;
+
+ auto seek_was_given_directly = direct_seek_timestamp == timestamp && invalidate_held_data == InvalidateHeldData::No;
+ if (!seek_was_given_directly) {
+ if (invalidate_held_data == InvalidateHeldData::No)
+ m_frames_to_lend_again = frames_lent_after_holding(newest_received_lend_id, timestamp);
+ if (m_frames_to_lend_again.is_empty() && m_input)
+ m_input->seek(timestamp, invalidate_held_data);
+ }
m_wake_pending = true;
m_wait_condition.broadcast();
}
bool RemoteVideoSink::ThreadData::consumer_may_satisfy_seek_locally(AK::Duration timestamp) const
{
- // Everything the consumer could resolve the seek from is lent across the edge: the frames it shows and the ring,
- // and the frame on its way into the ring.
Optional<AK::Duration> earliest_timestamp;
Optional<AK::Duration> latest_end;
- auto include_range = [&](LentFrameRange const& range) {
- if (!earliest_timestamp.has_value() || range.timestamp < *earliest_timestamp)
- earliest_timestamp = range.timestamp;
- if (!latest_end.has_value() || range.conservative_end > *latest_end)
- latest_end = range.conservative_end;
+ auto include_frame = [&](VideoFrame const& frame) {
+ if (!earliest_timestamp.has_value() || frame.timestamp() < earliest_timestamp.value())
+ earliest_timestamp = frame.timestamp();
+ if (!latest_end.has_value() || frame.conservative_end() > latest_end.value())
+ latest_end = frame.conservative_end();
};
{
- MutexLocker locker { m_lent_pools_mutex };
- for (auto const& [slot, range] : m_lent_frame_ranges)
- include_range(range);
+ MutexLocker locker { m_lent_frames_mutex };
+ for (auto const& [lend_id, frame] : m_lent_frames)
+ include_frame(*frame);
}
- if (m_peeked_frame_range.has_value())
- include_range(*m_peeked_frame_range);
- if (!earliest_timestamp.has_value() || timestamp < *earliest_timestamp)
+ if (m_peeked_frame)
+ include_frame(*m_peeked_frame);
+ if (!earliest_timestamp.has_value() || timestamp < earliest_timestamp.value())
return false;
- if (timestamp < *latest_end)
+ if (timestamp < latest_end.value())
return true;
- auto status = m_edge.status();
- return status.has_value() && status->seek_id == m_actual_seek_id && status->status == PipelineStatus::EndOfStream;
+ return m_published_status.has_value() && m_published_status->seek_id == m_actual_seek_id && m_published_status->status == PipelineStatus::EndOfStream;
}
void RemoteVideoSink::ThreadData::seek_input_directly(AK::Duration timestamp)
@@ -257,9 +260,6 @@ void RemoteVideoSink::ThreadData::seek_input_directly(AK::Duration timestamp)
MutexLocker locker { m_mutex };
if (m_input == nullptr || m_direct_seek_timestamp.has_value() || consumer_may_satisfy_seek_locally(timestamp))
return;
- // A request already on its way will seek the input to its own target, undoing this one.
- if (m_edge.requested_seek_id() != m_actual_seek_id)
- return;
// Pumping stops until the consumer's request for this seek arrives, so that no frame of the new position is
// stamped with the seek before it.
m_direct_seek_timestamp = timestamp;
@@ -277,7 +277,21 @@ void RemoteVideoSink::ThreadData::start_input()
input->start();
}
-void RemoteVideoSink::ThreadData::notify_space_available()
+void RemoteVideoSink::ThreadData::release_frame(u64 lend_id)
+{
+ // The frame is dropped outside the lock, since releasing its storage may wake its decoder.
+ Optional<NonnullRefPtr<VideoFrame>> released_frame;
+ {
+ MutexLocker locker { m_lent_frames_mutex };
+ released_frame = m_lent_frames.take(lend_id);
+ }
+ if (!released_frame.has_value())
+ return;
+ released_frame.clear();
+ wake_pump_thread();
+}
+
+void RemoteVideoSink::ThreadData::wake_pump_thread()
{
MutexLocker locker { m_mutex };
m_wake_pending = true;
@@ -291,6 +305,7 @@ void RemoteVideoSink::ThreadData::request_exit()
MutexLocker locker { m_mutex };
m_exit_requested = true;
input = move(m_input);
+ m_frames_to_lend_again.clear();
m_wake_pending = true;
m_wait_condition.broadcast();
}
@@ -298,25 +313,18 @@ void RemoteVideoSink::ThreadData::request_exit()
input->set_wake_handler(nullptr);
}
-void RemoteVideoSink::ThreadData::stop_and_reclaim_unconsumed_frames()
+void RemoteVideoSink::ThreadData::stop()
{
request_exit();
- {
- MutexLocker locker { m_mutex };
- while (!m_pump_thread_exited)
- m_wait_condition.wait();
- }
-
- for (auto item = m_edge.peek(); item.has_value(); item = m_edge.peek()) {
- release_slot(item->handle.pool_id, item->handle.slot_index);
- m_edge.consume();
- }
+ MutexLocker locker { m_mutex };
+ while (!m_pump_thread_exited)
+ m_wait_condition.wait();
}
-bool RemoteVideoSink::ThreadData::has_lent_slots() const
+bool RemoteVideoSink::ThreadData::has_lent_frames() const
{
- MutexLocker locker { m_lent_pools_mutex };
- return !m_lent_pools.is_empty();
+ MutexLocker locker { m_lent_frames_mutex };
+ return !m_lent_frames.is_empty();
}
void RemoteVideoSink::ThreadData::wait_on_pump_thread(MutexLocker<Mutex>&)
@@ -326,152 +334,115 @@ void RemoteVideoSink::ThreadData::wait_on_pump_thread(MutexLocker<Mutex>&)
m_wake_pending = false;
}
-void RemoteVideoSink::ThreadData::pump_thread_loop()
+void RemoteVideoSink::ThreadData::publish_status(PublishedStatus status)
{
- Optional<VideoEdgeStatus> published_status;
- auto publish_status = [&](VideoEdgeStatus status) {
- if (published_status == status)
- return false;
- published_status = status;
- m_edge.set_status(status.status, status.seek_id);
- return true;
+ {
+ MutexLocker locker { m_mutex };
+ if (m_published_status == status)
+ return;
+ m_published_status = status;
+ }
+ m_delegates.send_status(status.status, status.seek_id);
+}
+
+void RemoteVideoSink::ThreadData::lend_frame(NonnullRefPtr<VideoFrame> const& frame, u32 seek_id)
+{
+ u64 lend_id = 0;
+ {
+ MutexLocker locker { m_lent_frames_mutex };
+ lend_id = m_next_lend_id++;
+ m_lent_frames.set(lend_id, frame);
+ }
+
+ LentFrame lent_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));
+}
- // The seek ID a frame was enqueued under, while it has yet to be consumed from the input.
- Optional<u32> enqueued_frame_seek_id;
+void RemoteVideoSink::ThreadData::pump_thread_loop()
+{
+ // The seek ID a frame was lent under, while it has yet to be consumed from the input.
+ Optional<u32> lent_frame_seek_id;
while (true) {
- if (enqueued_frame_seek_id.has_value()) {
+ if (lent_frame_seek_id.has_value()) {
{
MutexLocker locker { m_mutex };
- m_peeked_frame_range = {};
+ m_peeked_frame = nullptr;
if (m_exit_requested)
break;
- // Paired with the fence in RemoteVideoProducer::seek(): either that seek's look at the ring saw this
- // frame, or its request is visible here and the frame stays in the input for the seek to find.
- AK::atomic_thread_fence(AK::MemoryOrder::memory_order_seq_cst);
- if (m_actual_seek_id != *enqueued_frame_seek_id) {
- // A seek was applied since the peek, so the input's head is re-peeked; if unchanged, it is
- // re-pumped under the new stamp and the consumer drops the old copy.
- enqueued_frame_seek_id = {};
+ if (m_actual_seek_id != lent_frame_seek_id.value()) {
+ // A seek was applied since the peek, so the input's head is re-peeked; if unchanged, it is lent
+ // again under the new stamp and the consumer drops the old copy.
+ lent_frame_seek_id = {};
continue;
}
- if (m_edge.requested_seek_id() != m_actual_seek_id || m_direct_seek_timestamp.has_value()) {
+ if (m_direct_seek_timestamp.has_value()) {
wait_on_pump_thread(locker);
continue;
}
if (m_input)
m_input->consume();
}
- publish_status({ PipelineStatus::Pending, *enqueued_frame_seek_id });
- enqueued_frame_seek_id = {};
- m_delegates.ring_data_available();
+ publish_status({ PipelineStatus::Pending, lent_frame_seek_id.value() });
+ lent_frame_seek_id = {};
continue;
}
- u32 seek_id;
+ u32 seek_id = 0;
+ Vector<NonnullRefPtr<VideoFrame>> frames_to_lend_again;
VideoProducerOutput output;
{
MutexLocker locker { m_mutex };
if (m_exit_requested)
break;
- auto seek_request_is_pending = m_edge.requested_seek_id() != m_actual_seek_id || m_direct_seek_timestamp.has_value();
- if (m_input == nullptr || !m_edge.can_enqueue() || seek_request_is_pending) {
- wait_on_pump_thread(locker);
- continue;
- }
seek_id = m_actual_seek_id;
- output = m_input->peek();
- if (output.status == PipelineStatus::HaveData)
- m_peeked_frame_range = LentFrameRange { output.frame->timestamp(), output.frame->conservative_end() };
+ frames_to_lend_again = move(m_frames_to_lend_again);
+ if (frames_to_lend_again.is_empty()) {
+ auto may_lend_another_frame = [&] {
+ MutexLocker lent_frames_locker { m_lent_frames_mutex };
+ return m_lent_frames.size() < MAX_LENT_FRAME_COUNT;
+ }();
+ if (m_input == nullptr || !may_lend_another_frame || m_direct_seek_timestamp.has_value()) {
+ wait_on_pump_thread(locker);
+ continue;
+ }
+ output = m_input->peek();
+ if (output.status == PipelineStatus::HaveData)
+ m_peeked_frame = output.frame;
+ }
+ }
+
+ if (!frames_to_lend_again.is_empty()) {
+ for (auto const& frame : frames_to_lend_again)
+ lend_frame(frame, seek_id);
+ publish_status({ PipelineStatus::Pending, seek_id });
+ continue;
}
if (output.status == PipelineStatus::HaveData) {
VERIFY(output.frame);
- enqueue_frame(*output.frame, seek_id);
- enqueued_frame_seek_id = seek_id;
+ lend_frame(*output.frame, seek_id);
+ lent_frame_seek_id = seek_id;
continue;
}
- if (publish_status({ output.status, seek_id }) && (output.status == PipelineStatus::Suspended || is_terminal(output.status)))
- m_delegates.ring_data_available();
+ publish_status({ output.status, seek_id });
MutexLocker locker { m_mutex };
wait_on_pump_thread(locker);
}
MutexLocker locker { m_mutex };
+ m_peeked_frame = nullptr;
m_pump_thread_exited = true;
m_wait_condition.broadcast();
}
-void RemoteVideoSink::ThreadData::enqueue_frame(VideoFrame const& frame, u32 seek_id)
-{
- lend_slot(frame);
- MUST(m_edge.enqueue(VideoFrameHandle::for_frame(frame), seek_id));
-}
-
-void RemoteVideoSink::ThreadData::lend_slot(VideoFrame const& frame)
-{
- auto const* pool_slot = frame.pool_slot();
- VERIFY(pool_slot != nullptr);
- auto& ledger = pool_slot->ledger();
- auto slot_index = pool_slot->slot_index();
- ledger.add_hold(slot_index);
- MutexLocker locker { m_lent_pools_mutex };
- m_lent_frame_ranges.set({ ledger.id(), slot_index }, { frame.timestamp(), frame.conservative_end() });
- auto& lent_pool = m_lent_pools.ensure(ledger.id(), [&] {
- return LentPool { .ledger = ledger, .lend_counts_by_slot_index = {}, .announced_allocated_buffer_ids_by_slot_index = {}, .outstanding_lend_count = 0 };
- });
-
- // Each new buffer backing the slot is announced exactly once, before the first handle that refers to it.
- auto announced_buffer_id = lent_pool.announced_allocated_buffer_ids_by_slot_index.get(slot_index);
- if (!announced_buffer_id.has_value() || *announced_buffer_id != pool_slot->allocated_buffer_id()) {
- m_delegates.announce_slot(ledger.id(), slot_index, ledger.slot_buffer(slot_index), ledger.slot_surface(slot_index));
- lent_pool.announced_allocated_buffer_ids_by_slot_index.set(slot_index, pool_slot->allocated_buffer_id());
- }
-
- lent_pool.lend_counts_by_slot_index.ensure(slot_index, [] { return 0u; })++;
- lent_pool.outstanding_lend_count++;
-}
-
-void RemoteVideoSink::ThreadData::release_slot(VideoFramePoolID pool_id, u32 slot_index)
-{
- RefPtr<VideoFrameEntryLedger> ledger;
- {
- MutexLocker locker { m_lent_pools_mutex };
- auto lent_pool = m_lent_pools.get(pool_id);
- if (!lent_pool.has_value())
- return;
- auto count = lent_pool->lend_counts_by_slot_index.get(slot_index);
- if (!count.has_value() || *count == 0)
- return;
- ledger = lent_pool->ledger;
- if (--*count == 0) {
- lent_pool->lend_counts_by_slot_index.remove(slot_index);
- m_lent_frame_ranges.remove({ pool_id, slot_index });
- }
- if (--lent_pool->outstanding_lend_count == 0) {
- m_lent_pools.remove(pool_id);
- m_delegates.retire_pool(pool_id);
- }
- }
- ledger->release_hold(slot_index);
-}
-
-void RemoteVideoSink::ThreadData::release_all_lends()
-{
- HashMap<VideoFramePoolID, LentPool> lent_pools;
- {
- MutexLocker locker { m_lent_pools_mutex };
- lent_pools = move(m_lent_pools);
- m_lent_frame_ranges.clear();
- }
- for (auto& entry : lent_pools) {
- for (auto& [slot_index, lend_count] : entry.value.lend_counts_by_slot_index) {
- for (u32 release = 0; release < lend_count; release++)
- entry.value.ledger->release_hold(slot_index);
- }
- }
-}
-
}
diff --git a/Libraries/LibMedia/Sinks/RemoteVideoSink.h b/Libraries/LibMedia/Sinks/RemoteVideoSink.h
index 31d60da2db7..3eae771c28e 100644
--- a/Libraries/LibMedia/Sinks/RemoteVideoSink.h
+++ b/Libraries/LibMedia/Sinks/RemoteVideoSink.h
@@ -16,44 +16,49 @@
#include <LibMedia/MediaTime.h>
#include <LibMedia/Sinks/VideoSink.h>
#include <LibMediaCodecs/VideoFrameHandle.h>
-#include <LibMediaCodecs/VideoFramePool.h>
+#include <LibMediaCodecs/VideoSurface.h>
#include <LibThreading/Forward.h>
namespace Media {
-class VideoEdgeQueue;
-
-// The pump end of a cross-process video edge. Video frames are converted to handles and sent over a shared-memory
-// queue across the boundary. When a frame with a new pool is sent, its pool is announced so that the other end can
-// resolve it and any subsequent frames.
+// The pump end of a cross-process video edge.
class MEDIA_API RemoteVideoSink final : public VideoSink {
public:
+ static constexpr size_t MAX_LENT_FRAME_COUNT = 32;
+
+ struct LentFrame {
+ 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;
+ };
+
struct Delegates {
- // Rung when newly enqueued data, a status change or a resumed clock may need the consumer woken.
- Function<void()> ring_data_available;
+ // Called from the pump thread, in the order the frames are lent.
+ Function<void(LentFrame)> send_frame;
+ // Called from the pump thread, after the frames the status follows.
+ Function<void(PipelineStatus, u32 seek_id)> send_status;
+ Function<void()> notify_clock_resumed;
// A seek reaches the far-end consumer so that its cached frames are consulted. Unless the frames lent to it
// could satisfy the seek, the input is seeked before the seek is transmitted, and the consumer's request for
// the same seek, which passes through the RemoteVideoProducer and across the edge, is then already answered.
Function<void(InvalidateHeldData)> transmit_seek;
// Relays a replacement time reader (e.g. after audio is disabled) to the consumer; the initial one rides video_edge_ready.
Function<void(MediaTimeReader const&)> transmit_time_reader;
- // Called to lend each new buffer backing a slot to the other side, before the first handle that refers to it.
- Function<void(VideoFramePoolID, u32 slot_index, Core::AnonymousBuffer, RefPtr<VideoSurface>)> announce_slot;
- // Called when a pool's last lent slot is released, so the other side can drop its slot buffers.
- Function<void(VideoFramePoolID)> retire_pool;
};
static ErrorOr<NonnullRefPtr<RemoteVideoSink>> create(Delegates);
virtual ~RemoteVideoSink() override;
- VideoEdgeQueue const& edge() const;
-
virtual ErrorOr<void> connect_input(NonnullRefPtr<VideoProducer> const&) override;
virtual void disconnect_input(NonnullRefPtr<VideoProducer> const&) override;
virtual void seek(AK::Duration timestamp, InvalidateHeldData = InvalidateHeldData::No) override;
virtual void notify_clock_resumed() override;
- void seek_upstream(AK::Duration timestamp, InvalidateHeldData = InvalidateHeldData::No);
+ // The newest received lend ID is the last one the consumer had seen when it asked for the seek.
+ void seek_upstream(AK::Duration timestamp, InvalidateHeldData, u64 newest_received_lend_id);
virtual void set_time_reader(MediaTimeReader) override;
virtual void set_state_change_handler(PipelineStateChangeHandler) override;
virtual void set_resize_handler(PipelineResizeHandler) override;
@@ -63,11 +68,11 @@ public:
void report_remote_resize(Gfx::Size<u32>);
// Callable from any thread.
- void notify_space_available();
- void release_slot(VideoFramePoolID, u32 slot_index);
+ void release_frame(u64 lend_id);
- void stop_and_reclaim_unconsumed_frames();
- bool has_lent_slots() const;
+ // The frames already lent stay lent until they are released.
+ void stop();
+ bool has_lent_frames() const;
private:
class ThreadData;
diff --git a/Libraries/LibMedia/VideoEdgeQueue.cpp b/Libraries/LibMedia/VideoEdgeQueue.cpp
deleted file mode 100644
index 6720558571b..00000000000
--- a/Libraries/LibMedia/VideoEdgeQueue.cpp
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibIPC/Decoder.h>
-#include <LibIPC/Encoder.h>
-#include <LibIPC/File.h>
-#include <LibMedia/VideoEdgeQueue.h>
-
-namespace IPC {
-
-template<>
-ErrorOr<void> encode(Encoder& encoder, Media::VideoEdgeQueue const& edge)
-{
- TRY(encoder.encode(TRY(File::clone_fd(edge.ring_fd()))));
- TRY(encoder.encode(edge.header_buffer()));
- return {};
-}
-
-template<>
-ErrorOr<Media::VideoEdgeQueue> decode(Decoder& decoder)
-{
- auto ring_fd = TRY(decoder.decode<File>());
- auto header_buffer = TRY(decoder.decode<Core::AnonymousBuffer>());
- return Media::VideoEdgeQueue::create(ring_fd.take_fd(), move(header_buffer));
-}
-
-}
diff --git a/Libraries/LibMedia/VideoEdgeQueue.h b/Libraries/LibMedia/VideoEdgeQueue.h
deleted file mode 100644
index 210963d3ded..00000000000
--- a/Libraries/LibMedia/VideoEdgeQueue.h
+++ /dev/null
@@ -1,128 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Atomic.h>
-#include <AK/Error.h>
-#include <AK/Optional.h>
-#include <AK/SeqLock.h>
-#include <AK/StdLibExtras.h>
-#include <AK/Time.h>
-#include <AK/Types.h>
-#include <LibCore/AnonymousBuffer.h>
-#include <LibCore/SharedCircularQueue.h>
-#include <LibIPC/Forward.h>
-#include <LibMedia/Export.h>
-#include <LibMedia/PipelineStatus.h>
-#include <LibMediaCodecs/VideoFrameHandle.h>
-
-namespace Media {
-
-// One decoded frame as it crosses the producer->consumer edge: a pool handle tagged with the seek ID it was decoded
-// under, so the consumer can drain superseded frames after a seek.
-struct VideoEdgeItem {
- VideoFrameHandle handle;
- u32 seek_id { 0 };
-};
-static_assert(IsTriviallyCopyable<VideoEdgeItem>);
-
-// The producer's pipeline status, stamped with the seek ID it reflects, so the consumer can ignore a status
-// left over from before a seek (which would otherwise resolve the seek with no frame).
-struct VideoEdgeStatus {
- PipelineStatus status { PipelineStatus::Pending };
- u32 seek_id { 0 };
-
- bool operator==(VideoEdgeStatus const&) const = default;
-};
-static_assert(IsTriviallyCopyable<VideoEdgeStatus>);
-
-// The shared-memory edge between a RemoteVideoSink (producer) and a RemoteVideoProducer (consumer).
-// Holds an SPSC queue of video frame handles and the status to produce when the queue runs dry. The queue's contents
-// are also the consumer's lookahead: a seek that lands between its head and its newest frame resolves without
-// going upstream.
-class VideoEdgeQueue {
-public:
- static constexpr size_t QUEUE_SIZE = 16;
- using Ring = Core::SharedSingleProducerCircularQueue<VideoEdgeItem, QUEUE_SIZE>;
-
- static ErrorOr<VideoEdgeQueue> create()
- {
- auto ring = TRY(Ring::create());
- auto header_buffer = TRY(Core::AnonymousBuffer::create_with_size(sizeof(Header)));
- auto* header = new (header_buffer.data<void>()) Header;
- return VideoEdgeQueue { move(ring), move(header_buffer), header };
- }
-
- static ErrorOr<VideoEdgeQueue> create(int ring_fd, Core::AnonymousBuffer header_buffer)
- {
- auto ring = TRY(Ring::create(ring_fd));
- if (!header_buffer.is_valid() || header_buffer.size() < sizeof(Header))
- return Error::from_string_literal("Invalid video edge header buffer");
- auto* header = reinterpret_cast<Header*>(header_buffer.data<void>());
- return VideoEdgeQueue { move(ring), move(header_buffer), header };
- }
-
- // Handed to the consumer at edge setup.
- int ring_fd() const { return m_ring.fd(); }
- Core::AnonymousBuffer const& header_buffer() const { return m_header_buffer; }
-
- // Producer side.
- ErrorOr<void> enqueue(VideoFrameHandle handle, u32 seek_id)
- {
- if (m_ring.enqueue({ handle, seek_id }).is_error())
- return Error::from_string_literal("Video edge queue is full");
- return {};
- }
- bool can_enqueue() const { return m_ring.can_enqueue(); }
- void set_status(PipelineStatus status, u32 seek_id) { m_header->status.store({ status, seek_id }); }
- u32 requested_seek_id() const { return m_header->requested_seek_id.load(AK::MemoryOrder::memory_order_relaxed); }
-
- // Consumer side. The status is consulted only when the ring is empty.
- Optional<VideoEdgeItem> peek() const { return m_ring.peek(); }
- Optional<VideoEdgeItem> peek_newest() const { return m_ring.peek_newest(); }
- void consume() { (void)m_ring.dequeue(); }
- Optional<VideoEdgeStatus> status() const
- {
- auto status = m_header->status.read();
- if (status.has_value() && to_underlying(status->status) > to_underlying(PipelineStatus::Error))
- status->status = PipelineStatus::Error;
- return status;
- }
- void set_requested_seek_id(u32 seek_id) { m_header->requested_seek_id.store(seek_id, AK::MemoryOrder::memory_order_relaxed); }
-
-private:
- struct Header {
- SeqLock<VideoEdgeStatus> status;
- // The seek the consumer is deciding on or has sent upstream. The producer side stops pumping while it has
- // yet to apply it, so the frames the seek may land in stay upstream where its fast path can find them. The
- // accesses are relaxed; the seq_cst fences on both sides order them against the ring.
- Atomic<u32> requested_seek_id { 0 };
- };
-
- VideoEdgeQueue(Ring ring, Core::AnonymousBuffer header_buffer, Header* header)
- : m_ring(move(ring))
- , m_header_buffer(move(header_buffer))
- , m_header(header)
- {
- }
-
- Ring m_ring;
- Core::AnonymousBuffer m_header_buffer;
- Header* m_header { nullptr };
-};
-
-}
-
-namespace IPC {
-
-template<>
-MEDIA_API ErrorOr<void> encode(Encoder&, Media::VideoEdgeQueue const&);
-
-template<>
-MEDIA_API ErrorOr<Media::VideoEdgeQueue> decode(Decoder&);
-
-}
diff --git a/Libraries/LibMedia/VideoPresentation/VideoPresentationClient.ipc b/Libraries/LibMedia/VideoPresentation/VideoPresentationClient.ipc
index d2fec3ff504..5d644860d0e 100644
--- a/Libraries/LibMedia/VideoPresentation/VideoPresentationClient.ipc
+++ b/Libraries/LibMedia/VideoPresentation/VideoPresentationClient.ipc
@@ -1,14 +1,15 @@
#include <LibMedia/InvalidateHeldData.h>
#include <LibMedia/MediaTime.h>
-#include <LibMedia/VideoEdgeQueue.h>
-#include <LibMediaCodecs/VideoFramePool.h>
+#include <LibMedia/PipelineStatus.h>
+#include <LibMediaCodecs/VideoFrameHandle.h>
#include <LibMediaCodecs/VideoSurface.h>
endpoint VideoPresentationClient {
- video_edge_ready(u64 edge_id, Media::VideoEdgeQueue edge, Media::MediaTimeReader time_reader) =|
+ video_edge_ready(u64 edge_id, Media::MediaTimeReader time_reader) =|
update_edge_time_reader(u64 edge_id, Media::MediaTimeReader time_reader) =|
- announce_video_frame_slot(u64 edge_id, Media::VideoFramePoolID pool_id, u32 slot_index, Core::AnonymousBuffer slot_buffer, RefPtr<Media::VideoSurface> surface) =|
- retire_video_frame_pool(u64 edge_id, Media::VideoFramePoolID pool_id) =|
- notify_data_available(u64 edge_id) =|
+ lend_frame(u64 edge_id, u64 lend_id, u32 seek_id, Media::VideoFrameMetadata metadata, Core::AnonymousBuffer pixel_buffer, RefPtr<Media::VideoSurface> surface) =|
+ // 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) =|
seek_sink(u64 edge_id, u32 requested_seek_id, Media::InvalidateHeldData invalidate_held_data) =|
}
diff --git a/Libraries/LibMedia/VideoPresentation/VideoPresentationClientConnection.cpp b/Libraries/LibMedia/VideoPresentation/VideoPresentationClientConnection.cpp
index 2cb1e8aba9d..56e75f9d2cf 100644
--- a/Libraries/LibMedia/VideoPresentation/VideoPresentationClientConnection.cpp
+++ b/Libraries/LibMedia/VideoPresentation/VideoPresentationClientConnection.cpp
@@ -4,14 +4,21 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+#include <AK/Atomic.h>
#include <LibGfx/Size.h>
#include <LibMedia/MediaTime.h>
#include <LibMedia/PipelineStatus.h>
-#include <LibMedia/VideoEdgeQueue.h>
#include <LibMedia/VideoPresentation/VideoPresentationClientConnection.h>
+#include <LibMediaCodecs/VideoFramePool.h>
namespace Media {
+static u64 allocate_sender_id()
+{
+ static Atomic<u64> s_next_sender_id { 1 };
+ return s_next_sender_id.fetch_add(1, AK::MemoryOrder::memory_order_relaxed);
+}
+
VideoPresentationClientConnection::VideoPresentationClientConnection(NonnullOwnPtr<IPC::Transport> transport)
: IPC::ConnectionToServer<VideoPresentationClientEndpoint, VideoPresentationServerEndpoint>(*this, move(transport))
{
@@ -33,7 +40,7 @@ ErrorOr<void> VideoPresentationClientConnection::create_edge(VideoSinkHandle han
if (m_edge_states.size() >= MAX_EDGE_COUNT)
return Error::from_string_literal("Too many video edges");
auto edge_id = m_next_edge_id++;
- m_edge_states.set(edge_id, EdgeState { handle, move(on_ready), nullptr, nullptr, {} });
+ m_edge_states.set(edge_id, EdgeState { .handle = handle, .on_ready = move(on_ready), .consumer = nullptr, .sink = nullptr, .time_reader = {}, .sender_id = allocate_sender_id(), .expected_requested_seek_id = 0 });
async_create_video_edge(handle, edge_id);
return {};
}
@@ -55,7 +62,7 @@ void VideoPresentationClientConnection::release_edge(VideoSinkHandle handle)
async_release_video_edge(*edge_id_to_release);
}
-void VideoPresentationClientConnection::video_edge_ready(u64 edge_id, VideoEdgeQueue edge, MediaTimeReader time_reader)
+void VideoPresentationClientConnection::video_edge_ready(u64 edge_id, MediaTimeReader time_reader)
{
auto edge_state = m_edge_states.get(edge_id);
if (!edge_state.has_value())
@@ -68,22 +75,12 @@ void VideoPresentationClientConnection::video_edge_ready(u64 edge_id, VideoEdgeQ
connection.async_request_start(edge_id);
});
};
- consumer_delegates.request_seek = [weak_connection, edge_id](AK::Duration timestamp, InvalidateHeldData invalidate_held_data) {
- weak_connection.with_target([&](auto& connection) {
- connection.async_request_seek(edge_id, timestamp, invalidate_held_data);
- });
- };
- consumer_delegates.release_slot = [weak_connection, edge_id](VideoFramePoolID pool_id, u32 slot_index) {
+ consumer_delegates.request_seek = [weak_connection, edge_id](AK::Duration timestamp, InvalidateHeldData invalidate_held_data, u64 newest_received_lend_id) {
weak_connection.with_target([&](auto& connection) {
- connection.async_release_slot(edge_id, pool_id, slot_index);
+ connection.async_request_seek(edge_id, timestamp, invalidate_held_data, newest_received_lend_id);
});
};
- consumer_delegates.notify_space_available = [weak_connection, edge_id] {
- weak_connection.with_target([&](auto& connection) {
- connection.async_notify_space_available(edge_id);
- });
- };
- auto consumer = RemoteVideoProducer::create(move(edge), edge_state->slot_directory, move(consumer_delegates));
+ auto consumer = RemoteVideoProducer::create(move(consumer_delegates));
auto sink = MUST(DisplayingVideoSink::try_create(time_reader));
edge_state->time_reader = time_reader;
@@ -120,22 +117,38 @@ void VideoPresentationClientConnection::update_edge_time_reader(u64 edge_id, Med
edge_state->sink->set_time_reader(move(time_reader));
}
-void VideoPresentationClientConnection::announce_video_frame_slot(u64 edge_id, VideoFramePoolID pool_id, u32 slot_index, Core::AnonymousBuffer slot_buffer, RefPtr<VideoSurface> surface)
+void VideoPresentationClientConnection::lend_frame(u64 edge_id, u64 lend_id, u32 seek_id, VideoFrameMetadata metadata, Core::AnonymousBuffer pixel_buffer, RefPtr<VideoSurface> surface)
{
- if (auto edge_state = m_edge_states.get(edge_id); edge_state.has_value())
- edge_state->slot_directory->notify_slot_announced(pool_id, slot_index, move(slot_buffer), move(surface));
+ // The frame may be dropped on any thread.
+ auto release = [weak_connection = make_weak_ref(), edge_id, lend_id] {
+ weak_connection.with_target([&](auto& connection) {
+ connection.async_release_frame(edge_id, lend_id);
+ });
+ };
+
+ auto edge_state = m_edge_states.get(edge_id);
+ if (!edge_state.has_value() || !edge_state->consumer) {
+ release();
+ return;
+ }
+ auto frame_or_error = create_received_video_frame(metadata, move(pixel_buffer), move(surface), 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;
+ }
+ edge_state->consumer->receive_frame(lend_id, seek_id, frame_or_error.release_value());
}
-void VideoPresentationClientConnection::retire_video_frame_pool(u64 edge_id, VideoFramePoolID pool_id)
+void VideoPresentationClientConnection::edge_status_changed(u64 edge_id, PipelineStatus status, u32 seek_id)
{
- if (auto edge_state = m_edge_states.get(edge_id); edge_state.has_value())
- edge_state->slot_directory->notify_pool_retired(pool_id);
+ if (auto edge_state = m_edge_states.get(edge_id); edge_state.has_value() && edge_state->consumer)
+ edge_state->consumer->receive_status(status, seek_id);
}
-void VideoPresentationClientConnection::notify_data_available(u64 edge_id)
+void VideoPresentationClientConnection::notify_clock_resumed(u64 edge_id)
{
if (auto edge_state = m_edge_states.get(edge_id); edge_state.has_value() && edge_state->consumer)
- edge_state->consumer->notify_data_available();
+ edge_state->consumer->notify_clock_resumed();
}
void VideoPresentationClientConnection::seek_sink(u64 edge_id, u32 requested_seek_id, InvalidateHeldData invalidate_held_data)
diff --git a/Libraries/LibMedia/VideoPresentation/VideoPresentationClientConnection.h b/Libraries/LibMedia/VideoPresentation/VideoPresentationClientConnection.h
index 2f6b2a4b165..6318795800d 100644
--- a/Libraries/LibMedia/VideoPresentation/VideoPresentationClientConnection.h
+++ b/Libraries/LibMedia/VideoPresentation/VideoPresentationClientConnection.h
@@ -31,7 +31,6 @@ class MEDIA_API VideoPresentationClientConnection final
C_OBJECT_ABSTRACT(VideoPresentationClientConnection);
public:
- // Each edge keeps as many buffers mapped here as it has slots, so a client may only have this many edges at once.
static constexpr size_t MAX_EDGE_COUNT = 64;
explicit VideoPresentationClientConnection(NonnullOwnPtr<IPC::Transport>);
@@ -45,11 +44,11 @@ public:
private:
virtual void die() override;
- virtual void video_edge_ready(u64 edge_id, Media::VideoEdgeQueue edge, Media::MediaTimeReader time_reader) override;
+ 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 announce_video_frame_slot(u64 edge_id, Media::VideoFramePoolID pool_id, u32 slot_index, Core::AnonymousBuffer slot_buffer, RefPtr<Media::VideoSurface> surface) override;
- virtual void retire_video_frame_pool(u64 edge_id, Media::VideoFramePoolID pool_id) override;
- virtual void notify_data_available(u64 edge_id) 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 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;
struct EdgeState {
@@ -58,7 +57,8 @@ private:
RefPtr<RemoteVideoProducer> consumer;
RefPtr<DisplayingVideoSink> sink;
Optional<MediaTimeReader> time_reader;
- NonnullRefPtr<VideoFrameSlotDirectory> slot_directory { VideoFrameSlotDirectory::create() };
+ // 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/VideoPresentationServer.ipc b/Libraries/LibMedia/VideoPresentation/VideoPresentationServer.ipc
index 1943db52f45..0b0cb2128b5 100644
--- a/Libraries/LibMedia/VideoPresentation/VideoPresentationServer.ipc
+++ b/Libraries/LibMedia/VideoPresentation/VideoPresentationServer.ipc
@@ -1,7 +1,6 @@
#include <AK/Time.h>
#include <LibMedia/InvalidateHeldData.h>
#include <LibMedia/PipelineStatus.h>
-#include <LibMediaCodecs/VideoFramePool.h>
#include <LibMedia/VideoSinkHandle.h>
endpoint VideoPresentationServer {
@@ -9,9 +8,8 @@ endpoint VideoPresentationServer {
release_video_edge(u64 edge_id) =|
request_start(u64 edge_id) =|
- request_seek(u64 edge_id, AK::Duration timestamp, Media::InvalidateHeldData invalidate_held_data) =|
- release_slot(u64 edge_id, Media::VideoFramePoolID pool_id, u32 slot_index) =|
- notify_space_available(u64 edge_id) =|
+ request_seek(u64 edge_id, AK::Duration timestamp, Media::InvalidateHeldData invalidate_held_data, u64 newest_received_lend_id) =|
+ release_frame(u64 edge_id, u64 lend_id) =|
notify_sink_status(u64 edge_id, Media::PipelineStatus status, u32 requested_seek_id) =|
notify_sink_resize(u64 edge_id, u32 width, u32 height) =|
diff --git a/Libraries/LibMedia/VideoPresentation/VideoPresentationServerConnection.cpp b/Libraries/LibMedia/VideoPresentation/VideoPresentationServerConnection.cpp
index f9687814025..d94309c8a36 100644
--- a/Libraries/LibMedia/VideoPresentation/VideoPresentationServerConnection.cpp
+++ b/Libraries/LibMedia/VideoPresentation/VideoPresentationServerConnection.cpp
@@ -7,7 +7,6 @@
#include <AK/Debug.h>
#include <LibGfx/Size.h>
#include <LibMedia/VideoPresentation/VideoPresentationServerConnection.h>
-#include <LibMediaCodecs/VideoFramePool.h>
namespace Media {
@@ -27,7 +26,7 @@ void VideoPresentationServerConnection::die()
for (auto& entry : m_edge_states)
PlaybackManager::release_video_edge({}, entry.value.handle, *entry.value.pump);
m_edge_states.clear();
- m_released_edge_pumps_with_lent_slots.clear();
+ m_released_edge_pumps_with_lent_frames.clear();
}
void VideoPresentationServerConnection::create_video_edge(VideoSinkHandle video_sink_handle, u64 edge_id)
@@ -72,9 +71,19 @@ void VideoPresentationServerConnection::create_registered_video_edge(VideoSinkHa
auto weak_connection = make_weak_ref();
RemoteVideoSink::Delegates delegates;
- delegates.ring_data_available = [weak_connection, edge_id] {
+ delegates.send_frame = [weak_connection, edge_id](RemoteVideoSink::LentFrame lent_frame) {
weak_connection.with_target([&](auto& connection) {
- connection.async_notify_data_available(edge_id);
+ 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));
+ });
+ };
+ delegates.send_status = [weak_connection, edge_id](PipelineStatus status, u32 seek_id) {
+ weak_connection.with_target([&](auto& connection) {
+ connection.async_edge_status_changed(edge_id, status, seek_id);
+ });
+ };
+ delegates.notify_clock_resumed = [weak_connection, edge_id] {
+ weak_connection.with_target([&](auto& connection) {
+ connection.async_notify_clock_resumed(edge_id);
});
};
delegates.transmit_seek = [weak_connection, edge_id](InvalidateHeldData invalidate_held_data) {
@@ -95,16 +104,6 @@ void VideoPresentationServerConnection::create_registered_video_edge(VideoSinkHa
connection.async_update_edge_time_reader(edge_id, time_reader);
});
};
- delegates.announce_slot = [weak_connection, edge_id](VideoFramePoolID pool_id, u32 slot_index, Core::AnonymousBuffer slot_buffer, RefPtr<VideoSurface> surface) {
- weak_connection.with_target([&](auto& connection) {
- connection.async_announce_video_frame_slot(edge_id, pool_id, slot_index, move(slot_buffer), move(surface));
- });
- };
- delegates.retire_pool = [weak_connection, edge_id](VideoFramePoolID pool_id) {
- weak_connection.with_target([&](auto& connection) {
- connection.async_retire_video_frame_pool(edge_id, pool_id);
- });
- };
auto remote_edge_or_error = PlaybackManager::create_video_edge({}, video_sink_handle, move(delegates));
if (remote_edge_or_error.is_error()) {
@@ -114,7 +113,7 @@ void VideoPresentationServerConnection::create_registered_video_edge(VideoSinkHa
auto remote_edge = remote_edge_or_error.release_value();
m_edge_states.set(edge_id, EdgeState { remote_edge.sink, video_sink_handle });
- async_video_edge_ready(edge_id, remote_edge.sink->edge(), remote_edge.time_reader);
+ async_video_edge_ready(edge_id, remote_edge.time_reader);
PlaybackManager::attach_video_edge({}, video_sink_handle, remote_edge.sink);
}
@@ -129,9 +128,9 @@ void VideoPresentationServerConnection::release_video_edge(u64 edge_id)
m_edge_states.remove(it);
PlaybackManager::release_video_edge({}, handle, *pump);
- pump->stop_and_reclaim_unconsumed_frames();
- if (pump->has_lent_slots())
- m_released_edge_pumps_with_lent_slots.set(edge_id, move(pump));
+ pump->stop();
+ if (pump->has_lent_frames())
+ m_released_edge_pumps_with_lent_frames.set(edge_id, move(pump));
}
void VideoPresentationServerConnection::request_start(u64 edge_id)
@@ -140,30 +139,24 @@ void VideoPresentationServerConnection::request_start(u64 edge_id)
it->value.pump->start_input();
}
-void VideoPresentationServerConnection::request_seek(u64 edge_id, AK::Duration timestamp, InvalidateHeldData invalidate_held_data)
+void VideoPresentationServerConnection::request_seek(u64 edge_id, AK::Duration timestamp, InvalidateHeldData invalidate_held_data, u64 newest_received_lend_id)
{
if (auto it = m_edge_states.find(edge_id); it != m_edge_states.end())
- it->value.pump->seek_upstream(timestamp, invalidate_held_data);
+ it->value.pump->seek_upstream(timestamp, invalidate_held_data, newest_received_lend_id);
}
-void VideoPresentationServerConnection::release_slot(u64 edge_id, VideoFramePoolID pool_id, u32 slot_index)
+void VideoPresentationServerConnection::release_frame(u64 edge_id, u64 lend_id)
{
if (auto it = m_edge_states.find(edge_id); it != m_edge_states.end()) {
- it->value.pump->release_slot(pool_id, slot_index);
+ it->value.pump->release_frame(lend_id);
return;
}
- auto released_pump = m_released_edge_pumps_with_lent_slots.get(edge_id);
+ auto released_pump = m_released_edge_pumps_with_lent_frames.get(edge_id);
if (!released_pump.has_value())
return;
- (*released_pump)->release_slot(pool_id, slot_index);
- if (!(*released_pump)->has_lent_slots())
- m_released_edge_pumps_with_lent_slots.remove(edge_id);
-}
-
-void VideoPresentationServerConnection::notify_space_available(u64 edge_id)
-{
- if (auto it = m_edge_states.find(edge_id); it != m_edge_states.end())
- it->value.pump->notify_space_available();
+ released_pump.value()->release_frame(lend_id);
+ if (!released_pump.value()->has_lent_frames())
+ m_released_edge_pumps_with_lent_frames.remove(edge_id);
}
void VideoPresentationServerConnection::notify_sink_status(u64 edge_id, PipelineStatus status, u32 requested_seek_id)
diff --git a/Libraries/LibMedia/VideoPresentation/VideoPresentationServerConnection.h b/Libraries/LibMedia/VideoPresentation/VideoPresentationServerConnection.h
index 22293c7429e..6cc634bb3e5 100644
--- a/Libraries/LibMedia/VideoPresentation/VideoPresentationServerConnection.h
+++ b/Libraries/LibMedia/VideoPresentation/VideoPresentationServerConnection.h
@@ -41,9 +41,8 @@ private:
virtual void create_video_edge(VideoSinkHandle video_sink_handle, u64 edge_id) override;
virtual void release_video_edge(u64 edge_id) override;
virtual void request_start(u64 edge_id) override;
- virtual void request_seek(u64 edge_id, AK::Duration timestamp, InvalidateHeldData) override;
- virtual void release_slot(u64 edge_id, VideoFramePoolID pool_id, u32 slot_index) override;
- virtual void notify_space_available(u64 edge_id) override;
+ virtual void request_seek(u64 edge_id, AK::Duration timestamp, InvalidateHeldData, u64 newest_received_lend_id) override;
+ virtual void release_frame(u64 edge_id, u64 lend_id) override;
virtual void notify_sink_status(u64 edge_id, PipelineStatus status, u32 requested_seek_id) override;
virtual void notify_sink_resize(u64 edge_id, u32 width, u32 height) override;
@@ -56,7 +55,7 @@ private:
void create_registered_video_edge(VideoSinkHandle, u64 edge_id);
HashMap<u64, EdgeState> m_edge_states;
- HashMap<u64, NonnullRefPtr<RemoteVideoSink>> m_released_edge_pumps_with_lent_slots;
+ HashMap<u64, NonnullRefPtr<RemoteVideoSink>> m_released_edge_pumps_with_lent_frames;
HashMap<u64, VideoSinkHandle> m_pending_edge_handles_by_edge_id;
};
diff --git a/Libraries/LibMediaCodecs/FFmpeg/FFmpegVulkanVideoDecoder.cpp b/Libraries/LibMediaCodecs/FFmpeg/FFmpegVulkanVideoDecoder.cpp
index fe2b0f65309..e6f5ea0636a 100644
--- a/Libraries/LibMediaCodecs/FFmpeg/FFmpegVulkanVideoDecoder.cpp
+++ b/Libraries/LibMediaCodecs/FFmpeg/FFmpegVulkanVideoDecoder.cpp
@@ -4,10 +4,10 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <AK/Atomic.h>
#include <AK/Diagnostics.h>
#include <AK/HashMap.h>
#include <AK/NeverDestroyed.h>
+#include <AK/Random.h>
#include <AK/ScopeGuard.h>
#include <LibIPC/File.h>
#include <LibMediaCodecs/CodedFrame.h>
@@ -41,9 +41,6 @@ constexpr u32 DRM_FORMAT_P010 = drm_fourcc('P', '0', '1', '0');
constexpr AK::Duration DEVICE_WORK_STALL_UNTIL_TREATED_AS_FAILED = AK::Duration::from_seconds(5);
-// Surfaces are told apart by ID in every process that sees them, and each decoder's images are distinct.
-Atomic<u32> s_next_surface_id { 1 };
-
char const* decoder_name_for(CodecID codec_id)
{
switch (codec_id) {
@@ -726,7 +723,7 @@ DecoderErrorOr<NonnullRefPtr<VideoSurface>> FFmpegVulkanVideoDecoder::surface_fo
}
}
- auto surface = VideoSurface::create_from_dma_buf(s_next_surface_id.fetch_add(1, AK::MemoryOrder::memory_order_relaxed), move(dma_buf));
+ auto surface = VideoSurface::create_from_dma_buf(get_random<u64>(), move(dma_buf));
if (surface.is_error())
return DecoderError::format(DecoderErrorCategory::Memory, "Could not create a surface for a decoded image: {}", surface.error());
DECODER_TRY_ALLOC(m_surfaces_by_image.try_set(image_key, surface.value()));
diff --git a/Libraries/LibMediaCodecs/VideoFrame.cpp b/Libraries/LibMediaCodecs/VideoFrame.cpp
index 5eec5939308..b6a3a3dbcf2 100644
--- a/Libraries/LibMediaCodecs/VideoFrame.cpp
+++ b/Libraries/LibMediaCodecs/VideoFrame.cpp
@@ -4,6 +4,7 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+#include <AK/Atomic.h>
#include <LibGfx/Bitmap.h>
#include <LibMediaCodecs/VideoFramePool.h>
#include <LibMediaCodecs/VideoSurface.h>
@@ -12,6 +13,12 @@
namespace Media {
+static u64 next_frame_id()
+{
+ static Atomic<u64> s_next_id { 1 };
+ return s_next_id.fetch_add(1, AK::MemoryOrder::memory_order_relaxed);
+}
+
VideoFrame::VideoFrame(
AK::Duration timestamp,
AK::Duration duration,
@@ -20,7 +27,8 @@ VideoFrame::VideoFrame(
Subsampling subsampling,
CodingIndependentCodePoints cicp,
BackingStorage backing_storage)
- : m_timestamp(timestamp)
+ : m_id(next_frame_id())
+ , m_timestamp(timestamp)
, m_duration(duration)
, m_size(size)
, m_bit_depth(bit_depth)
@@ -34,16 +42,23 @@ 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<ResolvedVideoFrameSlot> const& slot) -> RefPtr<VideoSurface> { return slot->surface(); });
+ [](NonnullRefPtr<ReceivedVideoFrameStorage> const& storage) -> RefPtr<VideoSurface> { return storage->surface(); });
}
-Optional<Gfx::YUVData> VideoFrame::yuv_data() const
+Core::AnonymousBuffer VideoFrame::pixel_buffer() const
{
- auto slot_buffer = m_backing_storage.visit(
- [](NonnullRefPtr<PooledVideoFrameSlot> const& slot) { return slot->ledger().slot_buffer(slot->slot_index()); },
- [](NonnullRefPtr<ResolvedVideoFrameSlot> const& slot) { return slot->slot_buffer(); });
+ 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(); });
+}
- auto yuv_data = yuv_data_in_slot_buffer(slot_buffer, m_size.to_type<int>(), m_bit_depth, m_subsampling, m_cicp);
+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);
if (yuv_data.is_error())
return {};
return yuv_data.release_value();
@@ -68,18 +83,11 @@ PooledVideoFrameSlot const* VideoFrame::pool_slot() const
return m_backing_storage.get<NonnullRefPtr<PooledVideoFrameSlot>>().ptr();
}
-ResolvedVideoFrameSlot const* VideoFrame::resolved_slot() const
+ReceivedVideoFrameStorage const* VideoFrame::received_storage() const
{
- if (auto const* resolved = m_backing_storage.get_pointer<NonnullRefPtr<ResolvedVideoFrameSlot>>())
- return resolved->ptr();
+ if (auto const* storage = m_backing_storage.get_pointer<NonnullRefPtr<ReceivedVideoFrameStorage>>())
+ return storage->ptr();
return nullptr;
}
-bool VideoFrame::revalidate_backing() const
-{
- if (auto const* resolved_slot = m_backing_storage.get_pointer<NonnullRefPtr<ResolvedVideoFrameSlot>>())
- return (*resolved_slot)->revalidate();
- return true;
-}
-
}
diff --git a/Libraries/LibMediaCodecs/VideoFrame.h b/Libraries/LibMediaCodecs/VideoFrame.h
index 80efb93d165..21059ef23cf 100644
--- a/Libraries/LibMediaCodecs/VideoFrame.h
+++ b/Libraries/LibMediaCodecs/VideoFrame.h
@@ -21,13 +21,13 @@
namespace Media {
class PooledVideoFrameSlot;
-class ResolvedVideoFrameSlot;
+class ReceivedVideoFrameStorage;
class VideoSurface;
class MEDIACODECS_API VideoFrame final : public AtomicRefCounted<VideoFrame> {
public:
- using BackingStorage = Variant<NonnullRefPtr<PooledVideoFrameSlot>, NonnullRefPtr<ResolvedVideoFrameSlot>>;
+ using BackingStorage = Variant<NonnullRefPtr<PooledVideoFrameSlot>, NonnullRefPtr<ReceivedVideoFrameStorage>>;
VideoFrame(
AK::Duration timestamp,
@@ -39,6 +39,9 @@ public:
BackingStorage backing_storage);
~VideoFrame();
+ // Tells this frame apart from every other frame in this process, including ones whose storage it shares.
+ u64 id() const { return m_id; }
+
AK::Duration timestamp() const { return m_timestamp; }
AK::Duration duration() const { return m_duration; }
AK::Duration end() const { return m_timestamp + m_duration; }
@@ -60,17 +63,17 @@ public:
// The platform surface holding the frame's pixels, null when they live in the backing slot's buffer.
RefPtr<VideoSurface> surface() const;
+ // The shared memory 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;
PooledVideoFrameSlot const* pool_slot() const;
- ResolvedVideoFrameSlot const* resolved_slot() const;
-
- // Confirms the viewed pixels were not recycled while being consumed. Only frames resolved
- // from a VideoFrameHandle can fail this.
- bool revalidate_backing() const;
+ ReceivedVideoFrameStorage const* received_storage() const;
private:
+ u64 m_id { 0 };
AK::Duration m_timestamp;
AK::Duration m_duration;
Gfx::Size<u32> m_size;
diff --git a/Libraries/LibMediaCodecs/VideoFrameHandle.cpp b/Libraries/LibMediaCodecs/VideoFrameHandle.cpp
index cc37ba67fa0..a54bfaf7166 100644
--- a/Libraries/LibMediaCodecs/VideoFrameHandle.cpp
+++ b/Libraries/LibMediaCodecs/VideoFrameHandle.cpp
@@ -39,9 +39,9 @@ ErrorOr<FramePlaneLayout> frame_plane_layout(Gfx::IntSize size, u8 bit_depth, Su
};
}
-bool VideoFrameHandle::is_valid() const
+bool VideoFrameMetadata::is_valid() const
{
- if (duration.value().is_negative())
+ if (duration.is_negative())
return false;
if (bit_depth != 8 && bit_depth != 10 && bit_depth != 12)
return false;
@@ -54,28 +54,44 @@ bool VideoFrameHandle::is_valid() const
return cicp.is_valid_or_unspecified();
}
+VideoFrameMetadata VideoFrameMetadata::for_frame(VideoFrame const& frame)
+{
+ return VideoFrameMetadata {
+ .timestamp = frame.timestamp(),
+ .duration = frame.duration(),
+ .size = frame.size().to_type<int>(),
+ .bit_depth = frame.bit_depth(),
+ .subsampling = frame.subsampling(),
+ .cicp = frame.cicp(),
+ };
+}
+
+bool VideoFrameHandle::is_valid() const
+{
+ return metadata().is_valid();
+}
+
+VideoFrameMetadata VideoFrameHandle::metadata() const
+{
+ return VideoFrameMetadata {
+ .timestamp = timestamp.value(),
+ .duration = duration.value(),
+ .size = size,
+ .bit_depth = bit_depth,
+ .subsampling = subsampling.value(),
+ .cicp = cicp,
+ };
+}
+
VideoFrameHandle VideoFrameHandle::for_frame(VideoFrame const& frame)
{
- // Owner-backed (a held pool slot) or consumer-backed (resolved from a handle); both carry the slot identity.
- VideoFramePoolID pool_id { 0 };
- u32 slot_index = 0;
- u64 slot_acquisition_id = 0;
- if (auto const* pool_slot = frame.pool_slot()) {
- pool_id = pool_slot->ledger().id();
- slot_index = pool_slot->slot_index();
- slot_acquisition_id = pool_slot->slot_acquisition_id();
- } else {
- auto const* resolved_slot = frame.resolved_slot();
- VERIFY(resolved_slot != nullptr);
- pool_id = resolved_slot->pool_id();
- slot_index = resolved_slot->slot_index();
- slot_acquisition_id = resolved_slot->slot_acquisition_id();
- }
+ auto const* pool_slot = frame.pool_slot();
+ VERIFY(pool_slot != nullptr);
return VideoFrameHandle {
- .pool_id = pool_id,
- .slot_index = slot_index,
- .slot_acquisition_id = slot_acquisition_id,
+ .pool_id = pool_slot->ledger().id(),
+ .slot_index = pool_slot->slot_index(),
+ .slot_acquisition_id = pool_slot->slot_acquisition_id(),
.timestamp = frame.timestamp(),
.duration = frame.duration(),
.size = frame.size().to_type<int>(),
@@ -89,6 +105,37 @@ VideoFrameHandle VideoFrameHandle::for_frame(VideoFrame const& frame)
namespace IPC {
+template<>
+ErrorOr<void> encode(Encoder& encoder, Media::VideoFrameMetadata const& metadata)
+{
+ TRY(encoder.encode(metadata.timestamp));
+ TRY(encoder.encode(metadata.duration));
+ TRY(encoder.encode(metadata.size));
+ TRY(encoder.encode(metadata.bit_depth));
+ TRY(encoder.encode(metadata.subsampling.x()));
+ TRY(encoder.encode(metadata.subsampling.y()));
+ TRY(encoder.encode(metadata.cicp));
+ return {};
+}
+
+template<>
+ErrorOr<Media::VideoFrameMetadata> decode(Decoder& decoder)
+{
+ Media::VideoFrameMetadata metadata;
+ metadata.timestamp = TRY(decoder.decode<AK::Duration>());
+ metadata.duration = TRY(decoder.decode<AK::Duration>());
+ metadata.size = TRY(decoder.decode<Gfx::IntSize>());
+ metadata.bit_depth = TRY(decoder.decode<u8>());
+ metadata.subsampling = Media::Subsampling {
+ TRY(decoder.decode<bool>()),
+ TRY(decoder.decode<bool>()),
+ };
+ metadata.cicp = TRY(decoder.decode<Media::CodingIndependentCodePoints>());
+ if (!metadata.is_valid())
+ return Error::from_string_literal("Video frame metadata describes a frame that could not have been decoded");
+ return metadata;
+}
+
template<>
ErrorOr<void> encode(Encoder& encoder, Media::VideoFrameHandle const& handle)
{
diff --git a/Libraries/LibMediaCodecs/VideoFrameHandle.h b/Libraries/LibMediaCodecs/VideoFrameHandle.h
index 610140fc187..7585368c988 100644
--- a/Libraries/LibMediaCodecs/VideoFrameHandle.h
+++ b/Libraries/LibMediaCodecs/VideoFrameHandle.h
@@ -21,6 +21,22 @@ namespace Media {
AK_TYPEDEF_DISTINCT_ORDERED_ID(u64, VideoFramePoolID);
+// 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;
+ u8 bit_depth { 0 };
+ Subsampling subsampling;
+ CodingIndependentCodePoints cicp;
+};
+
// References a frame in a previously-announced pool slot buffer, along with the metadata needed
// to present it. The receiving process resolves it against its mapping of that slot's buffer,
// validating the slot acquisition ID.
@@ -29,7 +45,7 @@ struct MEDIACODECS_API VideoFrameHandle {
bool is_valid() const;
- AK::Duration conservative_end() const { return VideoFrame::conservative_end_of(timestamp, duration); }
+ VideoFrameMetadata metadata() const;
VideoFramePoolID pool_id { 0 };
u32 slot_index { 0 };
@@ -60,6 +76,12 @@ MEDIACODECS_API ErrorOr<FramePlaneLayout> frame_plane_layout(Gfx::IntSize, u8 bi
namespace IPC {
+template<>
+MEDIACODECS_API ErrorOr<void> encode(Encoder&, Media::VideoFrameMetadata const&);
+
+template<>
+MEDIACODECS_API ErrorOr<Media::VideoFrameMetadata> decode(Decoder&);
+
template<>
MEDIACODECS_API ErrorOr<void> encode(Encoder&, Media::VideoFrameHandle const&);
diff --git a/Libraries/LibMediaCodecs/VideoFramePool.cpp b/Libraries/LibMediaCodecs/VideoFramePool.cpp
index 170573a20b7..f28f72d0a61 100644
--- a/Libraries/LibMediaCodecs/VideoFramePool.cpp
+++ b/Libraries/LibMediaCodecs/VideoFramePool.cpp
@@ -39,11 +39,6 @@ SlotHeader& slot_header(Core::AnonymousBuffer& buffer)
return *reinterpret_cast<SlotHeader*>(buffer.data<u8>());
}
-SlotHeader const& slot_header(Core::AnonymousBuffer const& buffer)
-{
- return *reinterpret_cast<SlotHeader const*>(buffer.data<u8 const>());
-}
-
}
ErrorOr<NonnullRefPtr<VideoFramePool>> VideoFramePool::create(size_t byte_budget)
@@ -428,28 +423,20 @@ void VideoFrameRelayPool::did_free_slot(u32 slot_index)
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)
- : m_slot_buffer(move(slot_buffer))
+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_pool_id(pool_id)
- , m_slot_index(slot_index)
- , m_slot_acquisition_id(slot_acquisition_id)
+ , m_sender_id(sender_id)
, m_on_release(move(on_release))
{
}
-ResolvedVideoFrameSlot::~ResolvedVideoFrameSlot()
+ReceivedVideoFrameStorage::~ReceivedVideoFrameStorage()
{
if (m_on_release)
m_on_release();
}
-bool ResolvedVideoFrameSlot::revalidate() const
-{
- AK::atomic_thread_fence(AK::MemoryOrder::memory_order_acquire);
- return slot_header(m_slot_buffer).slot_acquisition_id.load() == m_slot_acquisition_id;
-}
-
ErrorOr<Gfx::YUVData> yuv_data_in_slot_buffer(Core::AnonymousBuffer const& slot_buffer, Gfx::IntSize size, u8 bit_depth, Subsampling subsampling, CodingIndependentCodePoints const& cicp)
{
if (!slot_buffer.is_valid() || slot_buffer.size() <= slot_data_offset())
@@ -464,81 +451,30 @@ ErrorOr<Gfx::YUVData> yuv_data_in_slot_buffer(Core::AnonymousBuffer const& slot_
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>> resolve_frame_from_slot(Core::AnonymousBuffer const& slot_buffer, RefPtr<VideoSurface> surface, VideoFrameHandle const& handle, Function<void()> on_release)
+ErrorOr<NonnullRefPtr<VideoFrame>> create_received_video_frame(VideoFrameMetadata const& metadata, Core::AnonymousBuffer pixel_buffer, RefPtr<VideoSurface> surface, u64 sender_id, Function<void()> on_release)
{
- if (!slot_buffer.is_valid() || slot_buffer.size() < slot_data_offset())
- return Error::from_string_literal("Invalid video frame slot buffer");
- if (!handle.is_valid())
- return Error::from_string_literal("Video frame handle describes a frame that could not have been decoded");
-
- // A surface holds the pixels itself, so only an inline framebuffer has a plane layout to validate.
- if (surface == nullptr) {
- TRY(yuv_data_in_slot_buffer(slot_buffer, handle.size, handle.bit_depth, handle.subsampling, handle.cicp));
- } else {
- auto surface_size = surface->size();
- if (handle.subsampling.value() != Subsampling::yuv420() || handle.size.width() > surface_size.width() || handle.size.height() > surface_size.height())
- return Error::from_string_literal("Video frame handle does not match its surface");
+ 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();
- if (slot_header(slot_buffer).slot_acquisition_id.load(AK::MemoryOrder::memory_order_acquire) != handle.slot_acquisition_id)
- return Error::from_string_literal("VideoFrameHandle refers to a recycled slot");
+ if (!metadata.is_valid())
+ return Error::from_string_literal("Video frame metadata describes a frame that could not have been decoded");
- auto resolved_slot = TRY(try_make_ref_counted<ResolvedVideoFrameSlot>(slot_buffer, move(surface), handle.pool_id, handle.slot_index, handle.slot_acquisition_id, move(on_release)));
- return try_make_ref_counted<VideoFrame>(handle.timestamp, handle.duration, handle.size.to_type<u32>(), handle.bit_depth, handle.subsampling, handle.cicp, move(resolved_slot));
-}
-
-NonnullRefPtr<VideoFrameSlotDirectory> VideoFrameSlotDirectory::create()
-{
- return adopt_ref(*new VideoFrameSlotDirectory());
-}
-
-VideoFrameSlotDirectory::~VideoFrameSlotDirectory() = default;
-
-void VideoFrameSlotDirectory::set_on_slots_changed(Function<void()> on_slots_changed)
-{
- m_on_slots_changed = move(on_slots_changed);
-}
-
-void VideoFrameSlotDirectory::notify_slot_announced(VideoFramePoolID pool_id, u32 slot_index, Core::AnonymousBuffer slot_buffer, RefPtr<VideoSurface> surface)
-{
- if (!slot_buffer.is_valid() || slot_buffer.size() < slot_data_offset())
- return;
- m_slots_by_pool_id.ensure(pool_id).set(slot_index, AnnouncedSlot { move(slot_buffer), move(surface) });
- if (m_on_slots_changed)
- m_on_slots_changed();
-}
-
-void VideoFrameSlotDirectory::notify_pool_retired(VideoFramePoolID pool_id)
-{
- m_slots_by_pool_id.remove(pool_id);
-}
-
-void VideoFrameSlotDirectory::notify_all_pools_retired()
-{
- m_slots_by_pool_id.clear();
-}
-
-RefPtr<VideoFrame> VideoFrameSlotDirectory::resolve_frame(VideoFrameHandle const& handle, Function<void()> on_release) const
-{
- auto slots = m_slots_by_pool_id.get(handle.pool_id);
- if (!slots.has_value())
- return nullptr;
- auto slot = slots->get(handle.slot_index);
- if (!slot.has_value())
- return nullptr;
-
- // A frame's handle reaches us through the frame ring while the buffer it was written into is announced by
- // message, so a handle can arrive before the buffer it belongs to. Acquisition IDs count up per slot across
- // every buffer it is given, so one running ahead of the announced buffer's is that wait rather than a loss.
- if (slot_header(slot->buffer).slot_acquisition_id.load(AK::MemoryOrder::memory_order_acquire) < handle.slot_acquisition_id)
- return nullptr;
-
- auto frame_or_error = resolve_frame_from_slot(slot->buffer, slot->surface, handle, move(on_release));
- if (frame_or_error.is_error()) {
- dbgln("VideoFrameSlotDirectory: Slot {} of pool {} was announced but did not resolve: {}", handle.slot_index, handle.pool_id, frame_or_error.error());
- return nullptr;
+ 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 (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));
}
- return frame_or_error.release_value();
+
+ return try_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.h
index 7a998c4817d..e35795b7149 100644
--- a/Libraries/LibMediaCodecs/VideoFramePool.h
+++ b/Libraries/LibMediaCodecs/VideoFramePool.h
@@ -207,61 +207,30 @@ private:
u64 m_allocated_buffer_id { 0 };
};
-// A strong reference to a slot in a frame pool resolved on the remote side.
-class MEDIACODECS_API ResolvedVideoFrameSlot : public AtomicRefCounted<ResolvedVideoFrameSlot> {
+// 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:
- ResolvedVideoFrameSlot(Core::AnonymousBuffer slot_buffer, RefPtr<VideoSurface> surface, VideoFramePoolID pool_id, u32 slot_index, u64 slot_acquisition_id, Function<void()> on_release);
- ~ResolvedVideoFrameSlot();
+ ReceivedVideoFrameStorage(Core::AnonymousBuffer pixel_buffer, RefPtr<VideoSurface> surface, u64 sender_id, Function<void()> on_release);
+ ~ReceivedVideoFrameStorage();
- bool revalidate() const;
-
- Core::AnonymousBuffer slot_buffer() const { return m_slot_buffer; }
+ Core::AnonymousBuffer const& pixel_buffer() const { return m_pixel_buffer; }
RefPtr<VideoSurface> const& surface() const { return m_surface; }
- VideoFramePoolID pool_id() const { return m_pool_id; }
- u32 slot_index() const { return m_slot_index; }
- u64 slot_acquisition_id() const { return m_slot_acquisition_id; }
+ // 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_slot_buffer;
+ Core::AnonymousBuffer m_pixel_buffer;
RefPtr<VideoSurface> m_surface;
- VideoFramePoolID m_pool_id { 0 };
- u32 m_slot_index { 0 };
- u64 m_slot_acquisition_id { 0 };
+ u64 m_sender_id { 0 };
Function<void()> m_on_release;
};
// Views the planes laid out within a slot'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&);
-// Resolves a frame handle against the slot framebuffer it refers to, validating the slot's acquisition ID against the
-// handle's. The resolved frame revalidates it again after its pixels are consumed, seqlock-style, discarding reads of
-// recycled slots.
-MEDIACODECS_API ErrorOr<NonnullRefPtr<VideoFrame>> resolve_frame_from_slot(Core::AnonymousBuffer const& slot_buffer, RefPtr<VideoSurface> surface, VideoFrameHandle const&, Function<void()> on_release);
-
-// Tracks all the active slot framebuffers from a VideoFramePool via announcement and retirement notifications. Used to
-// resolve frames on a remote process. Resolved frames' lifetimes are guaranteed until they are released.
-class MEDIACODECS_API VideoFrameSlotDirectory : public AtomicRefCounted<VideoFrameSlotDirectory> {
-public:
- static NonnullRefPtr<VideoFrameSlotDirectory> create();
- ~VideoFrameSlotDirectory();
-
- void set_on_slots_changed(Function<void()>);
-
- void notify_slot_announced(VideoFramePoolID, u32 slot_index, Core::AnonymousBuffer slot_buffer, RefPtr<VideoSurface> surface);
- void notify_pool_retired(VideoFramePoolID);
- void notify_all_pools_retired();
-
- RefPtr<VideoFrame> resolve_frame(VideoFrameHandle const&, Function<void()> on_release) const;
-
-private:
- VideoFrameSlotDirectory() = default;
-
- struct AnnouncedSlot {
- Core::AnonymousBuffer buffer;
- RefPtr<VideoSurface> surface;
- };
- HashMap<VideoFramePoolID, HashMap<u32, AnnouncedSlot>> m_slots_by_pool_id;
- Function<void()> m_on_slots_changed;
-};
+// 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);
}
diff --git a/Libraries/LibMediaCodecs/VideoSurface.cpp b/Libraries/LibMediaCodecs/VideoSurface.cpp
index 74ac026a6b4..0032f3973c3 100644
--- a/Libraries/LibMediaCodecs/VideoSurface.cpp
+++ b/Libraries/LibMediaCodecs/VideoSurface.cpp
@@ -56,7 +56,7 @@ ErrorOr<NonnullRefPtr<VideoSurface>> VideoSurface::create_from_mach_port(Core::M
#ifdef AK_OS_LINUX
-ErrorOr<NonnullRefPtr<VideoSurface>> VideoSurface::create_from_dma_buf(u32 id, Gfx::LinuxDmaBufHandle dma_buf)
+ErrorOr<NonnullRefPtr<VideoSurface>> VideoSurface::create_from_dma_buf(u64 id, Gfx::LinuxDmaBufHandle dma_buf)
{
return adopt_nonnull_ref_or_enomem(new (nothrow) VideoSurface(id, move(dma_buf)));
}
@@ -98,7 +98,7 @@ ErrorOr<RefPtr<Media::VideoSurface>> decode(Decoder& decoder)
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 id = TRY(decoder.decode<u64>());
auto dma_buf = TRY(decoder.decode<Gfx::LinuxDmaBufHandle>());
return TRY(Media::VideoSurface::create_from_dma_buf(id, move(dma_buf)));
#else
diff --git a/Libraries/LibMediaCodecs/VideoSurface.h b/Libraries/LibMediaCodecs/VideoSurface.h
index 4ae89c118fa..0e41e69abaf 100644
--- a/Libraries/LibMediaCodecs/VideoSurface.h
+++ b/Libraries/LibMediaCodecs/VideoSurface.h
@@ -39,7 +39,8 @@ class MEDIACODECS_API VideoSurface : public AtomicRefCounted<VideoSurface> {
public:
~VideoSurface();
- u32 id() const { return m_id; }
+ // Tells the surface apart from every other its sender has handed out, including from an earlier decoder process.
+ u64 id() const { return m_id; }
Gfx::IntSize size() const;
// Reads the pixels back into memory, which works only where the platform lets this process map the surface.
@@ -55,14 +56,14 @@ public:
#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);
+ static ErrorOr<NonnullRefPtr<VideoSurface>> create_from_dma_buf(u64 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)
+ VideoSurface(Core::IOSurfaceHandle io_surface, u64 id)
: m_io_surface(move(io_surface))
, m_id(id)
{
@@ -72,7 +73,7 @@ private:
#endif
#ifdef AK_OS_LINUX
- VideoSurface(u32 id, Gfx::LinuxDmaBufHandle dma_buf)
+ VideoSurface(u64 id, Gfx::LinuxDmaBufHandle dma_buf)
: m_dma_buf(move(dma_buf))
, m_id(id)
{
@@ -81,7 +82,7 @@ private:
Gfx::LinuxDmaBufHandle m_dma_buf;
#endif
- u32 m_id { 0 };
+ u64 m_id { 0 };
};
}
diff --git a/Services/Compositor/ContextPresenter.cpp b/Services/Compositor/ContextPresenter.cpp
index 05452ca3f2d..a146dd5f98f 100644
--- a/Services/Compositor/ContextPresenter.cpp
+++ b/Services/Compositor/ContextPresenter.cpp
@@ -451,8 +451,8 @@ Gfx::IntRect ContextPresenter::damage_since_last_raster(Gfx::IntSize viewport_si
}
Vector<Compositing::VideoSinkResourceId> video_sinks_with_new_frames;
auto video_sinks_drawn_by_list = m_scene.display_list()->referenced_resource_ids().video_sinks;
- for (auto const& [video_sink_id, frame_slot] : last_frame.video_frame_slots) {
- if (current_video_frame_slot(video_sink_id) == frame_slot)
+ for (auto const& [video_sink_id, frame_id] : last_frame.video_frame_ids) {
+ if (current_video_frame_id(video_sink_id) == frame_id)
continue;
// A video drawn only by a nested display list, such as an SVG image's, has no command in
// this list to damage.
@@ -492,10 +492,10 @@ void ContextPresenter::remember_rasterized_frame(Gfx::IntSize viewport_size, Com
canvas_content_generations.set(canvas_id, m_canvas_surfaces.canvas_content_generation(canvas_id));
}
// Every video the context holds is drawn by the list or by a display list it nests.
- HashMap<Compositing::VideoSinkResourceId, Optional<VideoFrameSlot>> video_frame_slots;
+ HashMap<Compositing::VideoSinkResourceId, Optional<u64>> video_frame_ids;
for (auto const& [id, handle] : m_scene.video_sink_handles()) {
Compositing::VideoSinkResourceId video_sink_id { id };
- video_frame_slots.set(video_sink_id, current_video_frame_slot(video_sink_id));
+ video_frame_ids.set(video_sink_id, current_video_frame_id(video_sink_id));
}
m_last_rasterized_frame = RasterizedFrame {
.display_list = NonnullRefPtr { *m_scene.display_list() },
@@ -503,11 +503,11 @@ void ContextPresenter::remember_rasterized_frame(Gfx::IntSize viewport_size, Com
.scroll_state_snapshot = presented_scroll_state_snapshot,
.viewport_size = viewport_size,
.canvas_content_generations = move(canvas_content_generations),
- .video_frame_slots = move(video_frame_slots),
+ .video_frame_ids = move(video_frame_ids),
};
}
-Optional<ContextPresenter::VideoFrameSlot> ContextPresenter::current_video_frame_slot(Compositing::VideoSinkResourceId video_sink_id)
+Optional<u64> ContextPresenter::current_video_frame_id(Compositing::VideoSinkResourceId video_sink_id)
{
auto sink = m_scene.resource_storage().video_sink(video_sink_id);
if (!sink)
@@ -515,12 +515,7 @@ Optional<ContextPresenter::VideoFrameSlot> ContextPresenter::current_video_frame
auto frame = sink->current_frame();
if (!frame)
return {};
- auto handle = Media::VideoFrameHandle::for_frame(*frame);
- return VideoFrameSlot {
- .pool_id = handle.pool_id,
- .slot_index = handle.slot_index,
- .slot_acquisition_id = handle.slot_acquisition_id,
- };
+ return frame->id();
}
void ContextPresenter::paint_current_display_list(DisplayListPlayerSkia& display_list_player, Gfx::PaintingSurface& surface, FrameContent const& frame_content, Optional<Gfx::IntRect> damage_rect, PaintUIOverlay paint_ui_overlay, bool apply_raster_transform)
diff --git a/Services/Compositor/ContextPresenter.h b/Services/Compositor/ContextPresenter.h
index fa5ebcb3be6..70b5679fa7b 100644
--- a/Services/Compositor/ContextPresenter.h
+++ b/Services/Compositor/ContextPresenter.h
@@ -29,7 +29,7 @@
#include <LibGfx/Rect.h>
#include <LibGfx/ShareableBitmap.h>
#include <LibGfx/Size.h>
-#include <LibMediaCodecs/VideoFrameHandle.h>
+#include <LibMediaCodecs/VideoFrame.h>
namespace Gfx {
@@ -122,23 +122,13 @@ public:
void paint_screenshot(DisplayListPlayerSkia&, Gfx::ShareableBitmap&, FrameContent const&);
private:
- // A video frame named by the pool slot acquisition it was decoded into, which is new for every
- // frame even when frames share a surface.
- struct VideoFrameSlot {
- Media::VideoFramePoolID pool_id;
- u32 slot_index { 0 };
- u64 slot_acquisition_id { 0 };
-
- bool operator==(VideoFrameSlot const&) const = default;
- };
-
struct RasterizedFrame {
NonnullRefPtr<Compositing::DisplayList const> display_list;
Compositing::AccumulatedVisualContextTree visual_context_tree;
Compositing::ScrollStateSnapshot scroll_state_snapshot;
Gfx::IntSize viewport_size;
HashMap<Compositing::CanvasId, u64> canvas_content_generations;
- HashMap<Compositing::VideoSinkResourceId, Optional<VideoFrameSlot>> video_frame_slots;
+ HashMap<Compositing::VideoSinkResourceId, Optional<u64>> video_frame_ids;
};
enum class PaintUIOverlay : u8 {
@@ -154,7 +144,7 @@ private:
Gfx::IntRect frame_damage_for(PendingFrame const&, FrameContent const&);
Gfx::IntRect damage_since_last_raster(Gfx::IntSize viewport_size, FrameContent const&);
void remember_rasterized_frame(Gfx::IntSize viewport_size, Compositing::ScrollStateSnapshot const& presented_scroll_state_snapshot);
- Optional<VideoFrameSlot> current_video_frame_slot(Compositing::VideoSinkResourceId);
+ Optional<u64> current_video_frame_id(Compositing::VideoSinkResourceId);
void stop_backing_store_shrink_timer();
void stop_surplus_backing_store_retirement_timer();
diff --git a/Services/Compositor/DisplayListRasterCache.cpp b/Services/Compositor/DisplayListRasterCache.cpp
index f7413350983..2948ebce231 100644
--- a/Services/Compositor/DisplayListRasterCache.cpp
+++ b/Services/Compositor/DisplayListRasterCache.cpp
@@ -19,7 +19,6 @@
#include <LibGfx/Font/Font.h>
#include <LibGfx/YUVData.h>
#include <LibMediaCodecs/VideoFrame.h>
-#include <LibMediaCodecs/VideoFrameHandle.h>
#include <LibMediaCodecs/VideoSurface.h>
#include <core/SkFont.h>
@@ -73,9 +72,7 @@ struct DisplayListRasterCache::ImageFrameImage {
struct DisplayListRasterCache::VideoSinkImage {
AK_ALLOC_WITH_KMALLOC;
- Media::VideoFramePoolID pool_id { 0 };
- u32 slot_index { 0 };
- u64 slot_acquisition_id { 0 };
+ u64 frame_id { 0 };
// 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;
@@ -259,21 +256,13 @@ sk_sp<SkImage> DisplayListRasterCache::image_for_video_sink(DisplayListResourceS
if (!frame)
return nullptr;
- auto handle = Media::VideoFrameHandle::for_frame(*frame);
- auto surface = frame->surface();
auto& cached_image = *m_video_sink_images.ensure(id.value(), [] { return make<VideoSinkImage>(); });
auto cached_image_matches = [&] {
if (!cached_image.image)
return false;
if (cached_image.skia_backend_context != skia_backend_context)
return false;
- if (cached_image.pool_id != handle.pool_id)
- return false;
- if (cached_image.slot_index != handle.slot_index)
- return false;
- if (cached_image.slot_acquisition_id != handle.slot_acquisition_id)
- return false;
- return true;
+ return cached_image.frame_id == frame->id();
}();
if (cached_image_matches) {
cached_image.drawn_frame = frame;
@@ -282,16 +271,10 @@ sk_sp<SkImage> DisplayListRasterCache::image_for_video_sink(DisplayListResourceS
}
auto image = sk_image_from_video_frame(*frame, skia_backend_context);
-
- if (!frame->revalidate_backing())
- return nullptr;
-
if (!image)
return nullptr;
- cached_image.pool_id = handle.pool_id;
- cached_image.slot_index = handle.slot_index;
- cached_image.slot_acquisition_id = handle.slot_acquisition_id;
+ cached_image.frame_id = frame->id();
cached_image.drawn_frame = frame;
cached_image.skia_backend_context = skia_backend_context;
cached_image.image = image;
diff --git a/Services/Compositor/VideoFrameSkia.cpp b/Services/Compositor/VideoFrameSkia.cpp
index 033f9fe5e78..ae88c529c0c 100644
--- a/Services/Compositor/VideoFrameSkia.cpp
+++ b/Services/Compositor/VideoFrameSkia.cpp
@@ -9,11 +9,12 @@
#include <Compositor/SkiaBackendContext.h>
#include <Compositor/SkiaUtils.h>
#include <Compositor/VideoFrameSkia.h>
+#include <LibCore/Timer.h>
#include <LibGfx/Bitmap.h>
#include <LibGfx/ColorSpace.h>
#include <LibGfx/YUVData.h>
#include <LibMediaCodecs/VideoFrame.h>
-#include <LibMediaCodecs/VideoFrameHandle.h>
+#include <LibMediaCodecs/VideoFramePool.h>
#include <LibMediaCodecs/VideoSurface.h>
#include <core/SkCanvas.h>
@@ -162,8 +163,8 @@ SkYUVAPixmaps make_yuva_pixmaps(Gfx::YUVData const& yuv_data)
return SkYUVAPixmaps::FromExternalPixmaps(yuva_info, plane_pixmaps);
}
-// A surface-backed image samples the surface where it lies, so it stays valid for every frame decoded into that
-// surface. A decoder recycles a bounded set of surfaces, so each one's image is kept for as long as the surface is.
+// Kept for a while after it was last drawn in case its surface comes back, but no longer, since the image keeps the
+// surface's memory alive after the decoder has let go of it.
struct VideoSurfaceImage {
AK_ALLOC_WITH_KMALLOC;
@@ -171,49 +172,125 @@ struct VideoSurfaceImage {
NonnullRefPtr<Gfx::SkiaBackendContext> skia_backend_context;
Media::CodingIndependentCodePoints cicp;
sk_sp<SkImage> image;
- Media::VideoFramePoolID shown_pool_id { 0 };
- u32 shown_slot_index { 0 };
- u64 shown_slot_acquisition_id { 0 };
+ u64 shown_frame_id { 0 };
+ MonotonicTime last_drawn_time { MonotonicTime() };
};
-static HashMap<u32, NonnullOwnPtr<VideoSurfaceImage>>& video_surface_images()
+// Surface IDs are chosen by whoever sent the surface, so images are kept apart per sender.
+struct VideoSurfaceImageKey {
+ u64 sender_id { 0 };
+ u64 surface_id { 0 };
+
+ bool operator==(VideoSurfaceImageKey const&) const = default;
+};
+
+}
+
+template<>
+struct AK::Traits<Compositor::VideoSurfaceImageKey> : public DefaultTraits<Compositor::VideoSurfaceImageKey> {
+ static unsigned hash(Compositor::VideoSurfaceImageKey const& key) { return pair_int_hash(u64_hash(key.sender_id), u64_hash(key.surface_id)); }
+};
+
+namespace 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()
{
// Leaked so that no image outlives the GPU context at exit.
- static auto& images = *new HashMap<u32, NonnullOwnPtr<VideoSurfaceImage>>;
+ static auto& images = *new HashMap<VideoSurfaceImageKey, NonnullOwnPtr<VideoSurfaceImage>>;
return images;
}
+static void expire_undrawn_video_surface_images();
+
+static Core::Timer& video_surface_image_expiry_timer()
+{
+ static auto& timer = Core::Timer::create_single_shot(AK::Duration::zero(), [] { expire_undrawn_video_surface_images(); }).leak_ref();
+ return timer;
+}
+
+static void schedule_video_surface_image_expiry()
+{
+ auto& timer = video_surface_image_expiry_timer();
+ if (timer.is_active())
+ return;
+ auto const& images = video_surface_images();
+ if (images.is_empty())
+ return;
+ auto oldest_drawn_time = MonotonicTime::now();
+ for (auto const& entry : images)
+ oldest_drawn_time = min(oldest_drawn_time, entry.value->last_drawn_time);
+ auto delay = max(AK::Duration::zero(), oldest_drawn_time + UNDRAWN_VIDEO_SURFACE_IMAGE_LIFETIME - MonotonicTime::now());
+ timer.set_interval(delay);
+ timer.start();
+}
+
+static void expire_undrawn_video_surface_images()
+{
+ auto expiry_time = MonotonicTime::now() - UNDRAWN_VIDEO_SURFACE_IMAGE_LIFETIME;
+ video_surface_images().remove_all_matching([&](auto const&, auto const& image) {
+ return image->last_drawn_time <= expiry_time;
+ });
+ schedule_video_surface_image_expiry();
+}
+
+static void make_room_for_video_surface_image(u64 sender_id)
+{
+ auto& images = video_surface_images();
+ size_t sender_image_count = 0;
+ Optional<VideoSurfaceImageKey> least_recently_drawn_key;
+ MonotonicTime least_recently_drawn_time = MonotonicTime::now();
+ for (auto const& [key, image] : images) {
+ if (key.sender_id != sender_id)
+ continue;
+ sender_image_count++;
+ if (!least_recently_drawn_key.has_value() || image->last_drawn_time < least_recently_drawn_time) {
+ least_recently_drawn_key = key;
+ least_recently_drawn_time = image->last_drawn_time;
+ }
+ }
+ if (sender_image_count >= MAX_VIDEO_SURFACE_IMAGES_PER_SENDER)
+ images.remove(least_recently_drawn_key.value());
+}
+
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();
+ VideoSurfaceImageKey key { sender_id, surface.id() };
+
auto& images = video_surface_images();
auto* cached_image = [&]() -> VideoSurfaceImage* {
- auto cached = images.get(surface.id());
+ auto cached = images.get(key);
if (!cached.has_value())
return nullptr;
- auto& image = **cached;
- if (image.surface.ptr() != &surface || image.skia_backend_context.ptr() != &skia_backend_context || image.cicp != frame.cicp())
+ auto& image = *cached.value();
+ if (image.skia_backend_context.ptr() != &skia_backend_context || image.cicp != frame.cicp())
return nullptr;
return &image;
}();
if (!cached_image) {
- // A surface that only this cache still holds will not be handed out again.
- images.remove_all_matching([](auto, auto const& image) { return image->surface->ref_count() == 1; });
-
+ images.remove(key);
auto image = sk_image_from_video_surface(surface, frame.cicp(), skia_backend_context);
if (!image)
return nullptr;
+ make_room_for_video_surface_image(sender_id);
auto new_image = make<VideoSurfaceImage>(surface, skia_backend_context, frame.cicp(), move(image));
cached_image = new_image.ptr();
- images.set(surface.id(), move(new_image));
+ images.set(key, move(new_image));
}
- auto handle = Media::VideoFrameHandle::for_frame(frame);
- if (cached_image->shown_pool_id != handle.pool_id || cached_image->shown_slot_index != handle.slot_index || cached_image->shown_slot_acquisition_id != handle.slot_acquisition_id) {
+ cached_image->last_drawn_time = MonotonicTime::now();
+ schedule_video_surface_image_expiry();
+
+ if (cached_image->shown_frame_id != frame.id()) {
video_surface_image_will_show_new_frame(*cached_image->image);
- cached_image->shown_pool_id = handle.pool_id;
- cached_image->shown_slot_index = handle.slot_index;
- cached_image->shown_slot_acquisition_id = handle.slot_acquisition_id;
+ cached_image->shown_frame_id = frame.id();
}
return cached_image->image;
}
diff --git a/Tests/LibMedia/CMakeLists.txt b/Tests/LibMedia/CMakeLists.txt
index 3d947830afd..f556c43b29c 100644
--- a/Tests/LibMedia/CMakeLists.txt
+++ b/Tests/LibMedia/CMakeLists.txt
@@ -38,7 +38,6 @@ set(TEST_SOURCES
TestRemoteVideoNode.cpp
TestSourceBufferDemuxer.cpp
TestTimeRanges.cpp
- TestVideoEdgeQueue.cpp
TestVideoFramePool.cpp
TestVorbisDecode.cpp
TestVP9Decode.cpp
diff --git a/Tests/LibMedia/TestRemoteVideoNode.cpp b/Tests/LibMedia/TestRemoteVideoNode.cpp
index 807ded3eb58..9c58d223274 100644
--- a/Tests/LibMedia/TestRemoteVideoNode.cpp
+++ b/Tests/LibMedia/TestRemoteVideoNode.cpp
@@ -9,6 +9,7 @@
#include <AK/Mutex.h>
#include <AK/NonnullRefPtr.h>
#include <AK/ThreadSafeWeakable.h>
+#include <AK/Variant.h>
#include <AK/Vector.h>
#include <LibCore/EventLoop.h>
#include <LibCore/File.h>
@@ -26,7 +27,6 @@
#include <LibMedia/Sinks/AudioOutputFactory.h>
#include <LibMedia/Sinks/RemoteVideoSink.h>
#include <LibMedia/Track.h>
-#include <LibMedia/VideoEdgeQueue.h>
#include <LibMedia/VideoPresentation/VideoPresentationClientConnection.h>
#include <LibMedia/VideoPresentation/VideoPresentationServerConnection.h>
#include <LibMediaCodecs/VideoFrame.h>
@@ -102,28 +102,39 @@ Vector<AK::Duration> decode_reference_timestamps(StringView path)
return timestamps;
}
-// Bridges the two ends of the edge the way the IPC connection eventually will. The sink's pump-thread
-// delegates hand slot announcements and wake-ups to the consumer's draining thread; the consumer's
-// delegates drive the sink. RemoteVideoProducer is single-threaded, so the pump's delegates only queue
-// announcements and signal the draining thread, which is where the consumer is touched.
+// Bridges the two ends of the edge the way the IPC connection does. The sink's pump thread queues its messages, which
+// the consumer's thread delivers in order, since RemoteVideoProducer is single-threaded; the consumer's delegates
+// drive the sink directly.
struct VideoEdgeTestHarness
: public AtomicRefCounted<VideoEdgeTestHarness>
, public ThreadSafeWeakable<VideoEdgeTestHarness> {
- struct SlotAnnouncement {
- VideoFramePoolID pool_id;
- u32 slot_index { 0 };
- Core::AnonymousBuffer slot_buffer;
- RefPtr<VideoSurface> surface;
+ struct StatusMessage {
+ PipelineStatus status { PipelineStatus::Pending };
+ u32 seek_id { 0 };
+ };
+ using Message = Variant<RemoteVideoSink::LentFrame, StatusMessage>;
+ struct PostedMessage {
+ Message message;
+ MonotonicTime post_time;
};
RefPtr<RemoteVideoSink> sink;
- NonnullRefPtr<VideoFrameSlotDirectory> slot_directory { VideoFrameSlotDirectory::create() };
RefPtr<RemoteVideoProducer> consumer;
Mutex mutex;
ConditionVariable signal { mutex };
- Vector<SlotAnnouncement> pending_announces;
+ Vector<PostedMessage> pending_messages;
bool signaled { false };
+ // Messages are delivered only once they are this old, the way they take a while to cross between processes.
+ AK::Duration delivery_delay;
+
+ void post(Message message)
+ {
+ MutexLocker locker { mutex };
+ pending_messages.append({ move(message), MonotonicTime::now() });
+ signaled = true;
+ signal.broadcast();
+ }
void wake()
{
@@ -132,17 +143,33 @@ struct VideoEdgeTestHarness
signal.broadcast();
}
- void drain_announces()
+ void deliver_messages()
{
- Vector<SlotAnnouncement> announces;
+ Vector<Message> messages;
{
MutexLocker locker { mutex };
- announces = move(pending_announces);
+ auto deliverable_count = 0uz;
+ auto now = MonotonicTime::now();
+ while (deliverable_count < pending_messages.size() && now - pending_messages[deliverable_count].post_time >= delivery_delay)
+ deliverable_count++;
+ for (size_t i = 0; i < deliverable_count; i++)
+ messages.append(move(pending_messages[i].message));
+ pending_messages.remove(0, deliverable_count);
+ }
+ for (auto& message : messages) {
+ message.visit(
+ [&](RemoteVideoSink::LentFrame& lent_frame) {
+ auto release = [weak = make_weak_ref(), lend_id = lent_frame.lend_id] {
+ if (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)));
+ consumer->receive_frame(lent_frame.lend_id, lent_frame.seek_id, move(frame));
+ },
+ [&](StatusMessage const& status) {
+ consumer->receive_status(status.status, status.seek_id);
+ });
}
- for (auto& announcement : announces)
- slot_directory->notify_slot_announced(announcement.pool_id, announcement.slot_index, move(announcement.slot_buffer), move(announcement.surface));
- // The pump's delegates only wake this thread; the consumer is single-threaded, so it is notified here.
- consumer->notify_data_available();
}
};
@@ -151,70 +178,108 @@ void wire_full_node(VideoEdgeTestHarness& harness, NonnullRefPtr<VideoProducer>
// The detached pump thread can invoke these delegates while the test scope is being torn down,
// so they promote a weak reference to keep the harness alive for the duration of the call.
RemoteVideoSink::Delegates sink_delegates;
- sink_delegates.ring_data_available = [weak = harness.make_weak_ref()] {
+ sink_delegates.send_frame = [weak = harness.make_weak_ref()](RemoteVideoSink::LentFrame lent_frame) {
+ if (auto harness = weak.strong_ref())
+ harness->post(move(lent_frame));
+ };
+ sink_delegates.send_status = [weak = harness.make_weak_ref()](PipelineStatus status, u32 seek_id) {
if (auto harness = weak.strong_ref())
- harness->wake();
+ harness->post(VideoEdgeTestHarness::StatusMessage { status, seek_id });
};
+ sink_delegates.notify_clock_resumed = [] { };
sink_delegates.transmit_seek = [](InvalidateHeldData) { };
sink_delegates.transmit_time_reader = [](MediaTimeReader const&) { };
- sink_delegates.announce_slot = [weak = harness.make_weak_ref()](VideoFramePoolID pool_id, u32 slot_index, Core::AnonymousBuffer slot_buffer, RefPtr<VideoSurface> surface) {
- auto harness = weak.strong_ref();
- if (!harness)
- return;
- {
- MutexLocker locker { harness->mutex };
- harness->pending_announces.append({ pool_id, slot_index, move(slot_buffer), move(surface) });
- }
- harness->wake();
- };
- sink_delegates.retire_pool = [](VideoFramePoolID) { };
harness.sink = MUST(RemoteVideoSink::create(move(sink_delegates)));
- auto ring_fd = MUST(Core::System::dup(harness.sink->edge().ring_fd()));
- auto consumer_edge = MUST(VideoEdgeQueue::create(ring_fd, harness.sink->edge().header_buffer()));
RemoteVideoProducer::Delegates consumer_delegates;
consumer_delegates.request_start = [&harness] { harness.sink->start_input(); };
- consumer_delegates.request_seek = [&harness](AK::Duration timestamp, InvalidateHeldData invalidate_held_data) { harness.sink->seek_upstream(timestamp, invalidate_held_data); };
- consumer_delegates.release_slot = [&harness](VideoFramePoolID pool_id, u32 slot_index) { harness.sink->release_slot(pool_id, slot_index); };
- consumer_delegates.notify_space_available = [&harness] { harness.sink->notify_space_available(); };
- harness.consumer = RemoteVideoProducer::create(move(consumer_edge), harness.slot_directory, move(consumer_delegates));
+ consumer_delegates.request_seek = [&harness](AK::Duration timestamp, InvalidateHeldData invalidate_held_data, u64 newest_received_lend_id) {
+ harness.sink->seek_upstream(timestamp, invalidate_held_data, newest_received_lend_id);
+ };
+ harness.consumer = RemoteVideoProducer::create(move(consumer_delegates));
harness.consumer->set_wake_handler([&harness] { harness.wake(); });
// harness.consumer is set before connect_input, whose lock publishes it to the pump before the
- // pump can ring the consumer.
+ // pump can send anything to the consumer.
MUST(harness.sink->connect_input(decoder));
harness.consumer->start();
}
-// The consumer drops handles that describe a frame no decoder produces, so give the edge's items a real frame's format.
-VideoFrameHandle make_decodable_handle()
+NonnullRefPtr<VideoFrame> create_pooled_frame(VideoFramePool& pool, AK::Duration timestamp, AK::Duration duration = AK::Duration::from_milliseconds(33))
+{
+ static constexpr Gfx::IntSize frame_size { 2, 2 };
+ static constexpr u8 bit_depth = 8;
+ auto subsampling = Subsampling(true, true);
+
+ auto 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));
+}
+
+// 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 = [] { })
{
- VideoFrameHandle handle;
- handle.size = { 2, 2 };
- handle.bit_depth = 8;
- return handle;
+ 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)));
}
-// Builds a consumer over a controlled edge pre-filled with four frames at 1.0s..1.3s under seek_id 0,
-// to exercise the seek fast path deterministically.
-NonnullRefPtr<RemoteVideoProducer> make_lookahead_consumer(VideoEdgeQueue& producer_edge, size_t& upstream_seeks)
+RemoteVideoProducer::Delegates make_consumer_delegates(size_t& upstream_seeks)
{
- auto ring_fd = MUST(Core::System::dup(producer_edge.ring_fd()));
- auto consumer_edge = MUST(VideoEdgeQueue::create(ring_fd, producer_edge.header_buffer()));
RemoteVideoProducer::Delegates delegates;
delegates.request_start = [] { };
- delegates.request_seek = [&upstream_seeks](AK::Duration, InvalidateHeldData) { upstream_seeks++; };
- delegates.release_slot = [](VideoFramePoolID, u32) { };
- delegates.notify_space_available = [] { };
- auto consumer = RemoteVideoProducer::create(move(consumer_edge), VideoFrameSlotDirectory::create(), move(delegates));
-
- for (int i = 0; i < 4; i++) {
- auto handle = make_decodable_handle();
- handle.timestamp = AK::Duration::from_milliseconds(1000 + (i * 100));
- handle.duration = AK::Duration::from_milliseconds(100);
- MUST(producer_edge.enqueue(handle, 0));
+ delegates.request_seek = [&upstream_seeks](AK::Duration, InvalidateHeldData, u64) { upstream_seeks++; };
+ return delegates;
+}
+
+// Gives a consumer four frames at 1.0s..1.3s under seek 0, to exercise the seek fast path deterministically. Each frame
+// runs the given callback, which must outlive them, once it is released.
+void give_lookahead(RemoteVideoProducer& consumer, VideoFramePool& pool, Function<void()> const* on_release = nullptr)
+{
+ for (u64 i = 0; i < 4; i++) {
+ consumer.receive_frame(i + 1, 0, create_received_frame(pool, AK::Duration::from_milliseconds(1000 + (i * 100)), [on_release] {
+ if (on_release)
+ (*on_release)();
+ }));
}
- return consumer;
+}
+
+// Records what a sink lends, from its pump thread.
+struct LentFrameRecorder : public AtomicRefCounted<LentFrameRecorder> {
+ Mutex mutex;
+ Vector<RemoteVideoSink::LentFrame> lent_frames;
+
+ size_t count()
+ {
+ MutexLocker locker { mutex };
+ return lent_frames.size();
+ }
+
+ RemoteVideoSink::LentFrame at(size_t index)
+ {
+ MutexLocker locker { mutex };
+ return lent_frames[index];
+ }
+};
+
+NonnullRefPtr<RemoteVideoSink> make_recorded_sink(LentFrameRecorder& recorder)
+{
+ RemoteVideoSink::Delegates delegates;
+ delegates.send_frame = [recorder = NonnullRefPtr { recorder }](RemoteVideoSink::LentFrame lent_frame) {
+ MutexLocker locker { recorder->mutex };
+ recorder->lent_frames.append(move(lent_frame));
+ };
+ delegates.send_status = [](PipelineStatus, u32) { };
+ delegates.notify_clock_resumed = [] { };
+ delegates.transmit_seek = [](InvalidateHeldData) { };
+ delegates.transmit_time_reader = [](MediaTimeReader const&) { };
+ return MUST(RemoteVideoSink::create(move(delegates)));
+}
+
+NonnullRefPtr<RemoteVideoSink> make_sink_with_inert_delegates()
+{
+ return make_recorded_sink(*make_ref_counted<LentFrameRecorder>());
}
}
@@ -235,7 +300,7 @@ TEST_CASE(remote_video_node_delivers_every_frame_in_order)
auto deadline = MonotonicTime::now_coarse() + AK::Duration::from_seconds(10);
while (MonotonicTime::now_coarse() < deadline) {
loop.pump(Core::EventLoop::WaitMode::PollForEvents);
- harness->drain_announces();
+ harness->deliver_messages();
auto output = harness->consumer->peek();
if (output.status == PipelineStatus::HaveData) {
delivered.append(output.frame->timestamp());
@@ -283,7 +348,7 @@ TEST_CASE(remote_video_node_streams_and_seeks_under_concurrency)
};
while (!stop.load(AK::MemoryOrder::memory_order_relaxed)) {
- harness->drain_announces();
+ harness->deliver_messages();
auto output = harness->consumer->peek();
if (output.status == PipelineStatus::HaveData) {
@@ -299,8 +364,7 @@ TEST_CASE(remote_video_node_streams_and_seeks_under_concurrency)
}
if (have_consumed && ++since_seek >= 20) {
- // Seek with this frame still cached (peeked, not consumed) so the drop exercises both
- // the cached head and the unconsumed edge items.
+ // Seek with this frame still queued, so the drop covers it as well as the frames behind it.
seek_to(last_consumed > seek_step ? last_consumed - seek_step : AK::Duration::zero());
continue;
}
@@ -317,7 +381,7 @@ TEST_CASE(remote_video_node_streams_and_seeks_under_concurrency)
seek_to(AK::Duration::zero());
MutexLocker locker { harness->mutex };
- while (!harness->signaled && !stop.load(AK::MemoryOrder::memory_order_relaxed) && harness->pending_announces.is_empty())
+ while (!harness->signaled && !stop.load(AK::MemoryOrder::memory_order_relaxed) && harness->pending_messages.is_empty())
harness->signal.wait();
harness->signaled = false;
}
@@ -341,6 +405,102 @@ TEST_CASE(remote_video_node_streams_and_seeks_under_concurrency)
EXPECT(frames_pulled.load(AK::MemoryOrder::memory_order_relaxed) > 0);
}
+// Seeks in both directions, many of them landing in frames that are still on their way to the consumer, which the sink
+// has to lend again. Whichever way a seek is resolved, the first frame after it must hold the target or come just
+// before it, and the frames after that must follow in order, or a frame was skipped or a stale one delivered.
+TEST_CASE(remote_video_node_resolves_seeks_into_frames_on_their_way)
+{
+ auto& loop = never_destroyed_event_loop();
+ auto decoder = make_decoder(loop, TEST_CLIP);
+ IGNORE_USE_IN_ESCAPING_LAMBDA auto harness = make_ref_counted<VideoEdgeTestHarness>();
+ harness->delivery_delay = AK::Duration::from_milliseconds(3);
+ wire_full_node(*harness, decoder);
+
+ IGNORE_USE_IN_ESCAPING_LAMBDA Atomic<bool> stop { false };
+ IGNORE_USE_IN_ESCAPING_LAMBDA Atomic<size_t> seek_count { 0 };
+ IGNORE_USE_IN_ESCAPING_LAMBDA Atomic<bool> failure_detected { false };
+ IGNORE_USE_IN_ESCAPING_LAMBDA Atomic<i64> failure_target_ms { 0 };
+ IGNORE_USE_IN_ESCAPING_LAMBDA Atomic<i64> failure_frame_ms { 0 };
+
+ auto drainer = Threading::Thread::construct("Consumer Drainer"sv, [&]() -> intptr_t {
+ u32 random_state = 0x9e3779b9;
+ auto next_random = [&](u32 bound) {
+ random_state ^= random_state << 13;
+ random_state ^= random_state >> 17;
+ random_state ^= random_state << 5;
+ return random_state % bound;
+ };
+
+ Optional<AK::Duration> seek_target;
+ Optional<AK::Duration> last_timestamp;
+ size_t frames_since_seek = 0;
+ auto fail = [&](AK::Duration target, AK::Duration frame_timestamp) {
+ failure_target_ms.store(target.to_milliseconds(), AK::MemoryOrder::memory_order_relaxed);
+ failure_frame_ms.store(frame_timestamp.to_milliseconds(), AK::MemoryOrder::memory_order_relaxed);
+ failure_detected.store(true, AK::MemoryOrder::memory_order_relaxed);
+ };
+ auto seek_to = [&](AK::Duration target) {
+ harness->consumer->seek(target);
+ seek_target = target;
+ last_timestamp = {};
+ frames_since_seek = 0;
+ seek_count.fetch_add(1, AK::MemoryOrder::memory_order_relaxed);
+ };
+
+ while (!stop.load(AK::MemoryOrder::memory_order_relaxed)) {
+ harness->deliver_messages();
+
+ auto output = harness->consumer->peek();
+ if (output.status == PipelineStatus::HaveData) {
+ auto timestamp = output.frame->timestamp();
+ if (seek_target.has_value() && !last_timestamp.has_value() && timestamp > seek_target.value())
+ fail(seek_target.value(), timestamp);
+ if (last_timestamp.has_value() && timestamp <= last_timestamp.value())
+ fail(seek_target.value_or(AK::Duration::zero()), timestamp);
+ last_timestamp = timestamp;
+ harness->consumer->consume();
+
+ if (++frames_since_seek >= 4 + next_random(8)) {
+ // Mostly short hops forward, which land in the frames still on their way, and some jumps anywhere.
+ if (next_random(4) != 0)
+ seek_to(timestamp + AK::Duration::from_milliseconds(10 + next_random(120)));
+ else
+ seek_to(AK::Duration::from_milliseconds(next_random(4500)));
+ }
+ continue;
+ }
+ if (output.status == PipelineStatus::EndOfStream) {
+ seek_to(AK::Duration::from_milliseconds(next_random(2000)));
+ continue;
+ }
+
+ MutexLocker locker { harness->mutex };
+ if (harness->pending_messages.is_empty()) {
+ while (!harness->signaled && !stop.load(AK::MemoryOrder::memory_order_relaxed) && harness->pending_messages.is_empty())
+ harness->signal.wait();
+ }
+ harness->signaled = false;
+ }
+ return 0;
+ });
+ drainer->start();
+
+ auto deadline = MonotonicTime::now_coarse() + AK::Duration::from_milliseconds(1500);
+ while (MonotonicTime::now_coarse() < deadline)
+ loop.pump(Core::EventLoop::WaitMode::PollForEvents);
+
+ stop.store(true, AK::MemoryOrder::memory_order_relaxed);
+ harness->wake();
+ (void)drainer->join();
+
+ if (failure_detected.load(AK::MemoryOrder::memory_order_relaxed)) {
+ FAIL(MUST(String::formatted("Frame at {}ms delivered out of place after seeking to {}ms",
+ failure_frame_ms.load(AK::MemoryOrder::memory_order_relaxed),
+ failure_target_ms.load(AK::MemoryOrder::memory_order_relaxed))));
+ }
+ EXPECT(seek_count.load(AK::MemoryOrder::memory_order_relaxed) > 10);
+}
+
TEST_CASE(video_presentation_server_releases_playback_edge_when_connection_dies)
{
auto& loop = never_destroyed_event_loop();
@@ -379,8 +539,8 @@ TEST_CASE(video_presentation_server_releases_playback_edge_when_connection_dies)
EXPECT(!manager->track_is_enabled(track));
}
-// Each edge keeps buffers mapped in the Compositor, so a client that asks for edges without end is refused past the
-// limit, until it releases one.
+// Each edge keeps the frames it is lent, so a client that asks for edges without end is refused past the limit, until
+// it releases one.
TEST_CASE(video_presentation_client_limits_its_edges)
{
auto paired = MUST(IPC::Transport::create_paired());
@@ -398,12 +558,13 @@ TEST_CASE(video_presentation_client_limits_its_edges)
EXPECT(!client->create_edge(allocate_video_sink_handle(), [](NonnullRefPtr<DisplayingVideoSink>) { }).is_error());
}
-// A forward seek landing inside the buffered lookahead is resolved locally; a seek past it re-fetches.
+// A forward seek landing inside the received lookahead is resolved locally; a seek past it re-fetches.
TEST_CASE(consumer_resolves_forward_seeks_within_the_lookahead)
{
- auto producer_edge = MUST(VideoEdgeQueue::create());
+ auto pool = MUST(VideoFramePool::create());
size_t upstream_seeks = 0;
- auto consumer = make_lookahead_consumer(producer_edge, upstream_seeks);
+ auto consumer = RemoteVideoProducer::create(make_consumer_delegates(upstream_seeks));
+ give_lookahead(*consumer, *pool);
consumer->seek(AK::Duration::from_milliseconds(1200));
EXPECT_EQ(upstream_seeks, 0u);
@@ -415,64 +576,52 @@ TEST_CASE(consumer_resolves_forward_seeks_within_the_lookahead)
// A backward seek leaves the lookahead behind, so it must re-fetch upstream.
TEST_CASE(consumer_sends_backward_seeks_upstream)
{
- auto producer_edge = MUST(VideoEdgeQueue::create());
+ auto pool = MUST(VideoFramePool::create());
size_t upstream_seeks = 0;
- auto consumer = make_lookahead_consumer(producer_edge, upstream_seeks);
+ auto consumer = RemoteVideoProducer::create(make_consumer_delegates(upstream_seeks));
+ give_lookahead(*consumer, *pool);
consumer->seek(AK::Duration::from_milliseconds(500));
EXPECT_EQ(upstream_seeks, 1u);
}
-// The seek must reach upstream before the stale frames' slots are released, and a frame of the new seek that arrives
-// in between must stay in the ring.
+// The seek must reach upstream before the stale frames are released, naming the newest frame received so far, and a
+// frame of the new seek that arrives in between must be kept.
TEST_CASE(consumer_requests_seeks_before_releasing_stale_frames)
{
- auto producer_edge = MUST(VideoEdgeQueue::create());
- auto ring_fd = MUST(Core::System::dup(producer_edge.ring_fd()));
- auto consumer_edge = MUST(VideoEdgeQueue::create(ring_fd, producer_edge.header_buffer()));
-
+ auto pool = MUST(VideoFramePool::create());
Vector<StringView> events;
- Vector<u32> released_slot_indices;
+ Optional<u64> requested_newest_received_lend_id;
+ RefPtr<RemoteVideoProducer> consumer;
RemoteVideoProducer::Delegates delegates;
delegates.request_start = [] { };
- delegates.request_seek = [&](AK::Duration, InvalidateHeldData) {
+ delegates.request_seek = [&](AK::Duration, InvalidateHeldData, u64 newest_received_lend_id) {
events.append("seek"sv);
- auto handle = make_decodable_handle();
- handle.timestamp = AK::Duration::from_milliseconds(500);
- handle.duration = AK::Duration::from_milliseconds(100);
- handle.slot_index = 4;
- MUST(producer_edge.enqueue(handle, 1));
+ requested_newest_received_lend_id = newest_received_lend_id;
+ consumer->receive_frame(5, 1, create_received_frame(*pool, AK::Duration::from_milliseconds(500)));
};
- delegates.release_slot = [&](VideoFramePoolID, u32 slot_index) {
- events.append("release"sv);
- released_slot_indices.append(slot_index);
- };
- delegates.notify_space_available = [] { };
- auto consumer = RemoteVideoProducer::create(move(consumer_edge), VideoFrameSlotDirectory::create(), move(delegates));
-
- for (u32 i = 0; i < 4; i++) {
- auto handle = make_decodable_handle();
- handle.timestamp = AK::Duration::from_milliseconds(1000 + (i * 100));
- handle.duration = AK::Duration::from_milliseconds(100);
- handle.slot_index = i;
- MUST(producer_edge.enqueue(handle, 0));
- }
+ consumer = RemoteVideoProducer::create(move(delegates));
+ Function<void()> on_release = [&] { events.append("release"sv); };
+ give_lookahead(*consumer, *pool, &on_release);
consumer->seek(AK::Duration::from_milliseconds(500));
- EXPECT_EQ(events.size(), 5u);
- EXPECT_EQ(events.first(), "seek"sv);
- EXPECT_EQ(released_slot_indices, (Vector<u32> { 0, 1, 2, 3 }));
+ EXPECT_EQ(events, (Vector<StringView> { "seek"sv, "release"sv, "release"sv, "release"sv, "release"sv }));
+ EXPECT_EQ(requested_newest_received_lend_id, 4u);
+ auto output = consumer->peek();
+ EXPECT_EQ(output.status, PipelineStatus::HaveData);
+ EXPECT_EQ(output.frame->timestamp(), AK::Duration::from_milliseconds(500));
}
-// With the end of stream published, no frames exist beyond the lookahead for the producer to
+// With the end of stream received, no frames exist beyond the lookahead for the producer to
// re-emit, so a seek past the end must resolve locally instead of discarding the queued tail.
TEST_CASE(consumer_resolves_seeks_past_the_end_of_stream_locally)
{
- auto producer_edge = MUST(VideoEdgeQueue::create());
+ auto pool = MUST(VideoFramePool::create());
size_t upstream_seeks = 0;
- auto consumer = make_lookahead_consumer(producer_edge, upstream_seeks);
- producer_edge.set_status(PipelineStatus::EndOfStream, 0);
+ auto consumer = RemoteVideoProducer::create(make_consumer_delegates(upstream_seeks));
+ give_lookahead(*consumer, *pool);
+ consumer->receive_status(PipelineStatus::EndOfStream, 0);
consumer->seek(AK::Duration::from_milliseconds(3000));
EXPECT_EQ(upstream_seeks, 0u);
@@ -482,128 +631,99 @@ TEST_CASE(consumer_resolves_seeks_past_the_end_of_stream_locally)
EXPECT_EQ(upstream_seeks, 1u);
}
-// Observing a suspended edge must release every undelivered frame's lend, so that the suspended
-// producer's pool memory is actually reclaimed; resuming demand-seeks past those frames anyway.
-TEST_CASE(consumer_releases_ring_contents_on_suspension)
+// Observing a suspended edge must release every queued frame, so that the suspended producer's storage is actually
+// reclaimed; resuming demand-seeks past those frames anyway.
+TEST_CASE(consumer_releases_queued_frames_on_suspension)
{
- auto producer_edge = MUST(VideoEdgeQueue::create());
- auto ring_fd = MUST(Core::System::dup(producer_edge.ring_fd()));
- auto consumer_edge = MUST(VideoEdgeQueue::create(ring_fd, producer_edge.header_buffer()));
-
- size_t released_slots = 0;
- size_t space_notifications = 0;
- RemoteVideoProducer::Delegates delegates;
- delegates.request_start = [] { };
- delegates.request_seek = [](AK::Duration, InvalidateHeldData) { };
- delegates.release_slot = [&released_slots](VideoFramePoolID, u32) { released_slots++; };
- delegates.notify_space_available = [&space_notifications] { space_notifications++; };
- auto consumer = RemoteVideoProducer::create(move(consumer_edge), VideoFrameSlotDirectory::create(), move(delegates));
-
- for (u32 i = 0; i < 4; i++) {
- auto handle = make_decodable_handle();
- handle.timestamp = AK::Duration::from_milliseconds(1000 + (i * 100));
- handle.duration = AK::Duration::from_milliseconds(100);
- handle.slot_index = i;
- MUST(producer_edge.enqueue(handle, 0));
- }
- producer_edge.set_status(PipelineStatus::Suspended, 0);
+ auto pool = MUST(VideoFramePool::create());
+ size_t upstream_seeks = 0;
+ size_t released_frames = 0;
+ Function<void()> on_release = [&] { released_frames++; };
+ auto consumer = RemoteVideoProducer::create(make_consumer_delegates(upstream_seeks));
+ give_lookahead(*consumer, *pool, &on_release);
- consumer->notify_data_available();
+ consumer->receive_status(PipelineStatus::Suspended, 0);
- EXPECT_EQ(released_slots, 4u);
- EXPECT_EQ(space_notifications, 1u);
+ EXPECT_EQ(released_frames, 4u);
auto output = consumer->peek();
EXPECT(output.frame == nullptr);
EXPECT_EQ(output.status, PipelineStatus::Suspended);
}
-// A ring item's times are raw words the peer wrote; one that is not a canonical Duration must not reach Duration
-// arithmetic, which would abort the consumer's process.
-TEST_CASE(consumer_reads_forged_frame_times_without_aborting)
+// Frames lent under a seek the consumer has moved past are released as they arrive, and so are frames past the
+// queue's limit, so that a peer cannot make the consumer hold its storage without end.
+TEST_CASE(consumer_releases_frames_it_does_not_queue)
{
- auto producer_edge = MUST(VideoEdgeQueue::create());
+ auto pool = MUST(VideoFramePool::create());
size_t upstream_seeks = 0;
- auto consumer = make_lookahead_consumer(producer_edge, upstream_seeks);
+ size_t released_frames = 0;
+ auto consumer = RemoteVideoProducer::create(make_consumer_delegates(upstream_seeks));
- auto handle = make_decodable_handle();
- handle.duration = AK::Duration::from_milliseconds(100);
- SharedMemoryCodec<AK::Duration>::Representation forged_timestamp { 1, 2'000'000'000 };
- __builtin_memcpy(&handle.timestamp, &forged_timestamp, sizeof(forged_timestamp));
- MUST(producer_edge.enqueue(handle, 0));
+ consumer->seek(AK::Duration::from_seconds(5));
+ consumer->receive_frame(1, 0, create_received_frame(*pool, AK::Duration::zero(), [&] { released_frames++; }));
+ EXPECT_EQ(released_frames, 1u);
+ EXPECT_EQ(consumer->peek().status, PipelineStatus::Pending);
- consumer->seek(AK::Duration::from_milliseconds(1450));
- EXPECT_EQ(upstream_seeks, 1u);
+ for (u64 i = 0; i < RemoteVideoProducer::MAX_QUEUED_FRAME_COUNT + 2; i++)
+ consumer->receive_frame(i + 2, 1, create_received_frame(*pool, AK::Duration::from_milliseconds(5000 + i), [&] { released_frames++; }));
+ EXPECT_EQ(released_frames, 3u);
}
-namespace {
-
-NonnullRefPtr<VideoFrame> create_pooled_frame(VideoFramePool& pool, AK::Duration timestamp)
+// The sink's input has moved past the frames on their way to the consumer when the consumer asks for a seek. If those
+// frames hold the target, they are lent again under the seek's stamp instead of seeking the input back.
+TEST_CASE(sink_lends_frames_on_their_way_again_for_a_seek_into_them)
{
- static constexpr Gfx::IntSize frame_size { 2, 2 };
- static constexpr u8 bit_depth = 8;
- auto subsampling = Subsampling(true, true);
+ auto& loop = never_destroyed_event_loop();
+ auto recorder = make_ref_counted<LentFrameRecorder>();
+ auto sink = make_recorded_sink(*recorder);
- auto 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));
+ auto pool = MUST(VideoFramePool::create());
+ auto producer = ScriptedVideoProducer::create();
+ for (int i = 0; i < 4; i++)
+ producer->append_frame(create_pooled_frame(*pool, AK::Duration::from_milliseconds(i * 33)));
+ MUST(sink->connect_input(producer));
+ sink->start_input();
+ EXPECT(spin_until(loop, [&] { return recorder->count() == 4; }));
- return make_ref_counted<VideoFrame>(timestamp, AK::Duration::from_milliseconds(33), Gfx::Size<u32>(frame_size), bit_depth, subsampling, CodingIndependentCodePoints {}, move(slot));
-}
+ // The consumer had received only the first frame.
+ auto newest_received_lend_id = recorder->at(0).lend_id;
+ sink->seek_upstream(AK::Duration::from_milliseconds(70), InvalidateHeldData::No, newest_received_lend_id);
+ EXPECT_EQ(producer->seek_count(), 0u);
+ if (!spin_until(loop, [&] { return recorder->count() == 6; })) {
+ FAIL("The frames on their way were not lent again");
+ return;
+ }
+ EXPECT_EQ(recorder->at(4).seek_id, 1u);
+ EXPECT_EQ(recorder->at(4).metadata.timestamp, AK::Duration::from_milliseconds(66));
+ EXPECT_EQ(recorder->at(5).metadata.timestamp, AK::Duration::from_milliseconds(99));
+ EXPECT(recorder->at(5).lend_id > recorder->at(3).lend_id);
}
-// While a seek request is in flight, the pump must leave the producer's frames where the seek can still find
-// them, instead of moving them into the ring under a stamp the consumer has already superseded.
-TEST_CASE(pump_holds_off_while_a_seek_request_is_in_flight)
+// A seek outside the frames on their way to the consumer goes to the input, whether those frames end before the target
+// or the consumer had received them all.
+TEST_CASE(sink_seeks_its_input_for_seeks_outside_the_frames_on_their_way)
{
auto& loop = never_destroyed_event_loop();
-
- RemoteVideoSink::Delegates delegates;
- delegates.ring_data_available = [] { };
- delegates.transmit_seek = [](InvalidateHeldData) { };
- delegates.transmit_time_reader = [](MediaTimeReader const&) { };
- delegates.announce_slot = [](VideoFramePoolID, u32, Core::AnonymousBuffer, RefPtr<VideoSurface>) { };
- delegates.retire_pool = [](VideoFramePoolID) { };
- auto sink = MUST(RemoteVideoSink::create(move(delegates)));
+ auto recorder = make_ref_counted<LentFrameRecorder>();
+ auto sink = make_recorded_sink(*recorder);
auto pool = MUST(VideoFramePool::create());
auto producer = ScriptedVideoProducer::create();
- producer->append_frame(create_pooled_frame(*pool, AK::Duration::zero()));
- producer->append_frame(create_pooled_frame(*pool, AK::Duration::from_milliseconds(33)));
-
- auto ring_fd = MUST(Core::System::dup(sink->edge().ring_fd()));
- auto consumer_edge = MUST(VideoEdgeQueue::create(ring_fd, sink->edge().header_buffer()));
-
- // The consumer has requested a seek the pump has not applied yet.
- consumer_edge.set_requested_seek_id(1);
+ for (int i = 0; i < 4; i++)
+ producer->append_frame(create_pooled_frame(*pool, AK::Duration::from_milliseconds(i * 33)));
MUST(sink->connect_input(producer));
sink->start_input();
+ EXPECT(spin_until(loop, [&] { return recorder->count() == 4; }));
- auto hold_off_deadline = MonotonicTime::now_coarse() + AK::Duration::from_milliseconds(100);
- while (MonotonicTime::now_coarse() < hold_off_deadline) {
- EXPECT(!consumer_edge.peek().has_value());
- loop.pump(Core::EventLoop::WaitMode::PollForEvents);
- }
-
- // Applying the seek lets pumping resume, with the frames stamped for the request.
- sink->seek_upstream(AK::Duration::zero());
- EXPECT(spin_until(loop, [&] { return consumer_edge.peek().has_value(); }));
- EXPECT_EQ(consumer_edge.peek()->seek_id, 1u);
-}
-
-namespace {
+ sink->seek_upstream(AK::Duration::from_seconds(5), InvalidateHeldData::No, recorder->at(0).lend_id);
+ EXPECT_EQ(producer->seek_count(), 1u);
-NonnullRefPtr<RemoteVideoSink> make_sink_with_inert_delegates()
-{
- RemoteVideoSink::Delegates delegates;
- delegates.ring_data_available = [] { };
- delegates.transmit_seek = [](InvalidateHeldData) { };
- delegates.transmit_time_reader = [](MediaTimeReader const&) { };
- delegates.announce_slot = [](VideoFramePoolID, u32, Core::AnonymousBuffer, RefPtr<VideoSurface>) { };
- delegates.retire_pool = [](VideoFramePoolID) { };
- return MUST(RemoteVideoSink::create(move(delegates)));
-}
+ sink->seek_upstream(AK::Duration::from_milliseconds(70), InvalidateHeldData::No, recorder->at(3).lend_id);
+ EXPECT_EQ(producer->seek_count(), 2u);
+ sink->seek_upstream(AK::Duration::from_milliseconds(70), InvalidateHeldData::Yes, recorder->at(0).lend_id);
+ EXPECT_EQ(producer->seek_count(), 3u);
}
// A seek the consumer holds nothing for goes to the input right away, and the consumer's request for it, which
@@ -616,31 +736,10 @@ TEST_CASE(sink_seeks_its_input_directly_when_the_consumer_holds_nothing_for_the_
sink->seek(AK::Duration::from_seconds(1));
EXPECT_EQ(producer->seek_count(), 1u);
- sink->seek_upstream(AK::Duration::from_seconds(1));
+ sink->seek_upstream(AK::Duration::from_seconds(1), InvalidateHeldData::No, 0);
EXPECT_EQ(producer->seek_count(), 1u);
- sink->seek_upstream(AK::Duration::from_seconds(2));
- EXPECT_EQ(producer->seek_count(), 2u);
-}
-
-// A request the consumer has already made will seek the input to its own target, so a seek that arrives while the
-// request is on its way is left to the consumer.
-TEST_CASE(sink_leaves_a_seek_to_the_consumer_while_its_request_is_on_its_way)
-{
- auto sink = make_sink_with_inert_delegates();
- auto producer = ScriptedVideoProducer::create();
- auto ring_fd = MUST(Core::System::dup(sink->edge().ring_fd()));
- auto consumer_edge = MUST(VideoEdgeQueue::create(ring_fd, sink->edge().header_buffer()));
- MUST(sink->connect_input(producer));
-
- consumer_edge.set_requested_seek_id(1);
- sink->seek(AK::Duration::from_seconds(2));
- EXPECT_EQ(producer->seek_count(), 0u);
-
- sink->seek_upstream(AK::Duration::from_seconds(1));
- EXPECT_EQ(producer->seek_count(), 1u);
- consumer_edge.set_requested_seek_id(2);
- sink->seek_upstream(AK::Duration::from_seconds(2));
+ sink->seek_upstream(AK::Duration::from_seconds(2), InvalidateHeldData::No, 0);
EXPECT_EQ(producer->seek_count(), 2u);
}
@@ -650,12 +749,11 @@ TEST_CASE(sink_leaves_a_seek_to_the_consumer_while_its_request_is_on_its_way)
TEST_CASE(a_request_for_another_seek_supersedes_the_direct_seek)
{
auto& loop = never_destroyed_event_loop();
- auto sink = make_sink_with_inert_delegates();
+ auto recorder = make_ref_counted<LentFrameRecorder>();
+ auto sink = make_recorded_sink(*recorder);
auto pool = MUST(VideoFramePool::create());
auto producer = ScriptedVideoProducer::create();
- auto ring_fd = MUST(Core::System::dup(sink->edge().ring_fd()));
- auto consumer_edge = MUST(VideoEdgeQueue::create(ring_fd, sink->edge().header_buffer()));
MUST(sink->connect_input(producer));
sink->start_input();
@@ -663,14 +761,12 @@ TEST_CASE(a_request_for_another_seek_supersedes_the_direct_seek)
EXPECT_EQ(producer->seek_count(), 1u);
producer->append_frame(create_pooled_frame(*pool, AK::Duration::from_seconds(2)));
- consumer_edge.set_requested_seek_id(1);
- sink->seek_upstream(AK::Duration::from_seconds(2));
+ sink->seek_upstream(AK::Duration::from_seconds(2), InvalidateHeldData::No, 0);
EXPECT_EQ(producer->seek_count(), 2u);
- EXPECT(spin_until(loop, [&] { return consumer_edge.peek().has_value(); }));
- EXPECT_EQ(consumer_edge.peek()->seek_id, 1u);
+ EXPECT(spin_until(loop, [&] { return recorder->count() == 1; }));
+ EXPECT_EQ(recorder->at(0).seek_id, 1u);
- consumer_edge.set_requested_seek_id(2);
- sink->seek_upstream(AK::Duration::from_seconds(1));
+ sink->seek_upstream(AK::Duration::from_seconds(1), InvalidateHeldData::No, recorder->at(0).lend_id);
EXPECT_EQ(producer->seek_count(), 3u);
}
@@ -679,23 +775,20 @@ TEST_CASE(a_request_for_another_seek_supersedes_the_direct_seek)
TEST_CASE(sink_leaves_seeks_within_the_lent_frames_to_the_consumer)
{
auto& loop = never_destroyed_event_loop();
- auto sink = make_sink_with_inert_delegates();
+ auto recorder = make_ref_counted<LentFrameRecorder>();
+ auto sink = make_recorded_sink(*recorder);
auto pool = MUST(VideoFramePool::create());
auto producer = ScriptedVideoProducer::create();
producer->append_frame(create_pooled_frame(*pool, AK::Duration::zero()));
producer->append_frame(create_pooled_frame(*pool, AK::Duration::from_milliseconds(33)));
-
- auto ring_fd = MUST(Core::System::dup(sink->edge().ring_fd()));
- auto consumer_edge = MUST(VideoEdgeQueue::create(ring_fd, sink->edge().header_buffer()));
MUST(sink->connect_input(producer));
sink->start_input();
- EXPECT(spin_until(loop, [&] { return consumer_edge.peek_newest().has_value() && consumer_edge.peek_newest()->handle.timestamp == AK::Duration::from_milliseconds(33); }));
+ EXPECT(spin_until(loop, [&] { return recorder->count() == 2; }));
sink->seek(AK::Duration::from_milliseconds(20));
EXPECT_EQ(producer->seek_count(), 0u);
- consumer_edge.set_requested_seek_id(1);
- sink->seek_upstream(AK::Duration::from_milliseconds(20));
+ sink->seek_upstream(AK::Duration::from_milliseconds(20), InvalidateHeldData::No, recorder->at(1).lend_id);
EXPECT_EQ(producer->seek_count(), 1u);
sink->seek(AK::Duration::from_milliseconds(500));
@@ -707,13 +800,11 @@ TEST_CASE(sink_leaves_seeks_within_the_lent_frames_to_the_consumer)
TEST_CASE(pump_holds_off_after_a_direct_seek_until_the_consumer_requests_it)
{
auto& loop = never_destroyed_event_loop();
- auto sink = make_sink_with_inert_delegates();
+ auto recorder = make_ref_counted<LentFrameRecorder>();
+ auto sink = make_recorded_sink(*recorder);
auto pool = MUST(VideoFramePool::create());
auto producer = ScriptedVideoProducer::create();
-
- auto ring_fd = MUST(Core::System::dup(sink->edge().ring_fd()));
- auto consumer_edge = MUST(VideoEdgeQueue::create(ring_fd, sink->edge().header_buffer()));
MUST(sink->connect_input(producer));
sink->seek(AK::Duration::from_seconds(1));
EXPECT_EQ(producer->seek_count(), 1u);
@@ -724,123 +815,62 @@ TEST_CASE(pump_holds_off_after_a_direct_seek_until_the_consumer_requests_it)
auto hold_off_deadline = MonotonicTime::now_coarse() + AK::Duration::from_milliseconds(100);
while (MonotonicTime::now_coarse() < hold_off_deadline) {
- EXPECT(!consumer_edge.peek().has_value());
+ EXPECT_EQ(recorder->count(), 0u);
loop.pump(Core::EventLoop::WaitMode::PollForEvents);
}
- consumer_edge.set_requested_seek_id(1);
- sink->seek_upstream(AK::Duration::from_seconds(1));
+ sink->seek_upstream(AK::Duration::from_seconds(1), InvalidateHeldData::No, 0);
EXPECT_EQ(producer->seek_count(), 1u);
- EXPECT(spin_until(loop, [&] { return consumer_edge.peek().has_value(); }));
- EXPECT_EQ(consumer_edge.peek()->seek_id, 1u);
+ EXPECT(spin_until(loop, [&] { return recorder->count() > 0; }));
+ EXPECT_EQ(recorder->at(0).seek_id, 1u);
}
-// A request the consumer withdraws, having resolved the seek locally after all, must let pumping resume under the
-// unchanged stamp once the consumer's next consume wakes the pump.
-TEST_CASE(pump_resumes_after_a_withdrawn_seek_request)
+// The pump stops taking frames from its input once the limit of frames lent at once is reached, until one comes back.
+TEST_CASE(pump_waits_for_a_release_once_it_has_lent_its_limit)
{
auto& loop = never_destroyed_event_loop();
+ auto recorder = make_ref_counted<LentFrameRecorder>();
+ auto sink = make_recorded_sink(*recorder);
- RemoteVideoSink::Delegates delegates;
- delegates.ring_data_available = [] { };
- delegates.transmit_seek = [](InvalidateHeldData) { };
- delegates.transmit_time_reader = [](MediaTimeReader const&) { };
- delegates.announce_slot = [](VideoFramePoolID, u32, Core::AnonymousBuffer, RefPtr<VideoSurface>) { };
- delegates.retire_pool = [](VideoFramePoolID) { };
- auto sink = MUST(RemoteVideoSink::create(move(delegates)));
-
- auto pool = MUST(VideoFramePool::create());
+ auto pool = MUST(VideoFramePool::create(VideoFramePool::DEFAULT_BYTE_BUDGET));
auto producer = ScriptedVideoProducer::create();
- producer->append_frame(create_pooled_frame(*pool, AK::Duration::zero()));
- producer->append_frame(create_pooled_frame(*pool, AK::Duration::from_milliseconds(33)));
-
- auto ring_fd = MUST(Core::System::dup(sink->edge().ring_fd()));
- auto consumer_edge = MUST(VideoEdgeQueue::create(ring_fd, sink->edge().header_buffer()));
-
- consumer_edge.set_requested_seek_id(1);
+ auto frame = create_pooled_frame(*pool, AK::Duration::zero());
+ for (size_t i = 0; i < RemoteVideoSink::MAX_LENT_FRAME_COUNT + 1; i++)
+ producer->append_frame(frame);
MUST(sink->connect_input(producer));
sink->start_input();
+ EXPECT(spin_until(loop, [&] { return recorder->count() == RemoteVideoSink::MAX_LENT_FRAME_COUNT; }));
auto hold_off_deadline = MonotonicTime::now_coarse() + AK::Duration::from_milliseconds(100);
while (MonotonicTime::now_coarse() < hold_off_deadline) {
- EXPECT(!consumer_edge.peek().has_value());
+ EXPECT_EQ(recorder->count(), RemoteVideoSink::MAX_LENT_FRAME_COUNT);
loop.pump(Core::EventLoop::WaitMode::PollForEvents);
}
- consumer_edge.set_requested_seek_id(0);
- sink->notify_space_available();
- EXPECT(spin_until(loop, [&] { return consumer_edge.peek().has_value(); }));
- EXPECT_EQ(consumer_edge.peek()->seek_id, 0u);
+ sink->release_frame(recorder->at(0).lend_id);
+ EXPECT(spin_until(loop, [&] { return recorder->count() == RemoteVideoSink::MAX_LENT_FRAME_COUNT + 1; }));
}
-TEST_CASE(stopped_pump_reclaims_only_the_frames_left_in_the_ring)
+// A stopped pump lends nothing more, but the frames it lent stay lent until the consumer releases them.
+TEST_CASE(stopped_pump_keeps_its_lent_frames_until_they_are_released)
{
auto& loop = never_destroyed_event_loop();
-
- auto retired_pool_count = 0;
- RemoteVideoSink::Delegates delegates;
- delegates.ring_data_available = [] { };
- delegates.transmit_seek = [](InvalidateHeldData) { };
- delegates.transmit_time_reader = [](MediaTimeReader const&) { };
- delegates.announce_slot = [](VideoFramePoolID, u32, Core::AnonymousBuffer, RefPtr<VideoSurface>) { };
- delegates.retire_pool = [&](VideoFramePoolID) { retired_pool_count++; };
- auto sink = MUST(RemoteVideoSink::create(move(delegates)));
+ auto recorder = make_ref_counted<LentFrameRecorder>();
+ auto sink = make_recorded_sink(*recorder);
auto pool = MUST(VideoFramePool::create());
auto producer = ScriptedVideoProducer::create();
producer->append_frame(create_pooled_frame(*pool, AK::Duration::zero()));
producer->append_frame(create_pooled_frame(*pool, AK::Duration::from_milliseconds(33)));
-
- auto ring_fd = MUST(Core::System::dup(sink->edge().ring_fd()));
- auto consumer_edge = MUST(VideoEdgeQueue::create(ring_fd, sink->edge().header_buffer()));
-
MUST(sink->connect_input(producer));
sink->start_input();
+ EXPECT(spin_until(loop, [&] { return recorder->count() == 2; }));
- EXPECT(spin_until(loop, [&] {
- auto newest = consumer_edge.peek_newest();
- return newest.has_value() && newest->handle.timestamp == AK::Duration::from_milliseconds(33);
- }));
- auto taken_handle = consumer_edge.peek()->handle;
- consumer_edge.consume();
-
- sink->stop_and_reclaim_unconsumed_frames();
- EXPECT(sink->has_lent_slots());
- EXPECT_EQ(retired_pool_count, 0);
-
- sink->release_slot(taken_handle.pool_id, taken_handle.slot_index);
- EXPECT(!sink->has_lent_slots());
- EXPECT_EQ(retired_pool_count, 1);
-}
-
-TEST_CASE(consumer_forgets_announced_slots_on_suspension)
-{
- auto producer_edge = MUST(VideoEdgeQueue::create());
- auto ring_fd = MUST(Core::System::dup(producer_edge.ring_fd()));
- auto consumer_edge = MUST(VideoEdgeQueue::create(ring_fd, producer_edge.header_buffer()));
-
- auto pool = MUST(VideoFramePool::create());
- auto frame = create_pooled_frame(*pool, AK::Duration::from_milliseconds(1000));
- auto handle = VideoFrameHandle::for_frame(*frame);
-
- auto directory = VideoFrameSlotDirectory::create();
- directory->notify_slot_announced(pool->id(), handle.slot_index, pool->slot_buffer(handle.slot_index), nullptr);
-
- RemoteVideoProducer::Delegates delegates;
- delegates.request_start = [] { };
- delegates.request_seek = [](AK::Duration, InvalidateHeldData) { };
- delegates.release_slot = [](VideoFramePoolID, u32) { };
- delegates.notify_space_available = [] { };
- auto consumer = RemoteVideoProducer::create(move(consumer_edge), directory, move(delegates));
-
- auto resolved_before_suspension = directory->resolve_frame(handle, [] { });
- EXPECT(resolved_before_suspension != nullptr);
-
- producer_edge.set_status(PipelineStatus::Suspended, 0);
- consumer->notify_data_available();
+ sink->stop();
+ EXPECT(sink->has_lent_frames());
- // The decoder that announced this slot is gone, so nothing more resolves against it, while the frame that
- // already did keeps reading what it holds.
- EXPECT(directory->resolve_frame(handle, [] { }) == nullptr);
- EXPECT(resolved_before_suspension->revalidate_backing());
+ sink->release_frame(recorder->at(0).lend_id);
+ EXPECT(sink->has_lent_frames());
+ sink->release_frame(recorder->at(1).lend_id);
+ EXPECT(!sink->has_lent_frames());
}
diff --git a/Tests/LibMedia/TestVideoEdgeQueue.cpp b/Tests/LibMedia/TestVideoEdgeQueue.cpp
deleted file mode 100644
index a41ba0a662f..00000000000
--- a/Tests/LibMedia/TestVideoEdgeQueue.cpp
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <AK/Time.h>
-#include <LibCore/System.h>
-#include <LibMedia/VideoEdgeQueue.h>
-#include <LibTest/TestCase.h>
-
-using namespace Media;
-
-TEST_CASE(enqueue_peek_consume)
-{
- auto edge = MUST(VideoEdgeQueue::create());
- EXPECT(!edge.peek().has_value());
-
- VideoFrameHandle handle;
- handle.timestamp = AK::Duration::from_milliseconds(100);
- MUST(edge.enqueue(handle, 1));
-
- auto item = edge.peek();
- EXPECT(item.has_value());
- EXPECT_EQ(item->seek_id, 1u);
- EXPECT_EQ(item->handle.timestamp, AK::Duration::from_milliseconds(100));
- // peek() does not advance.
- EXPECT(edge.peek().has_value());
-
- edge.consume();
- EXPECT(!edge.peek().has_value());
-}
-
-TEST_CASE(header_carries_status)
-{
- auto edge = MUST(VideoEdgeQueue::create());
- auto initial = edge.status();
- EXPECT(initial.has_value());
- EXPECT_EQ(initial->status, PipelineStatus::Pending);
-
- edge.set_status(PipelineStatus::EndOfStream, 7);
- auto updated = edge.status();
- EXPECT(updated.has_value());
- EXPECT_EQ(updated->status, PipelineStatus::EndOfStream);
- EXPECT_EQ(updated->seek_id, 7u);
-}
-
-TEST_CASE(consumer_maps_the_same_edge_through_fds)
-{
- auto producer = MUST(VideoEdgeQueue::create());
- // Cross-process, IPC hands the consumer a dup'd fd; emulate that here so producer and consumer
- // don't both close the same one on teardown.
- auto ring_fd = MUST(Core::System::dup(producer.ring_fd()));
- auto consumer = MUST(VideoEdgeQueue::create(ring_fd, producer.header_buffer()));
-
- VideoFrameHandle handle;
- handle.slot_index = 3;
- MUST(producer.enqueue(handle, 2));
- producer.set_status(PipelineStatus::HaveData, 2);
-
- auto item = consumer.peek();
- EXPECT(item.has_value());
- EXPECT_EQ(item->handle.slot_index, 3u);
- EXPECT_EQ(item->seek_id, 2u);
- auto status = consumer.status();
- EXPECT(status.has_value());
- EXPECT_EQ(status->status, PipelineStatus::HaveData);
-
- consumer.consume();
- EXPECT(!consumer.peek().has_value());
-}
-
-TEST_CASE(requested_seek_id_is_shared_through_the_header)
-{
- auto producer = MUST(VideoEdgeQueue::create());
- auto ring_fd = MUST(Core::System::dup(producer.ring_fd()));
- auto consumer = MUST(VideoEdgeQueue::create(ring_fd, producer.header_buffer()));
-
- EXPECT_EQ(producer.requested_seek_id(), 0u);
- consumer.set_requested_seek_id(3);
- EXPECT_EQ(producer.requested_seek_id(), 3u);
-}
-
-TEST_CASE(peek_newest_reads_the_last_enqueued_item)
-{
- auto edge = MUST(VideoEdgeQueue::create());
- EXPECT(!edge.peek_newest().has_value());
-
- for (u32 i = 1; i <= 3; i++) {
- VideoFrameHandle handle;
- handle.timestamp = AK::Duration::from_milliseconds(100 * i);
- MUST(edge.enqueue(handle, 1));
- }
- EXPECT_EQ(edge.peek()->handle.timestamp, AK::Duration::from_milliseconds(100));
- EXPECT_EQ(edge.peek_newest()->handle.timestamp, AK::Duration::from_milliseconds(300));
-
- // Consuming leaves the newest item in place until it is the one consumed.
- edge.consume();
- edge.consume();
- EXPECT_EQ(edge.peek()->handle.timestamp, AK::Duration::from_milliseconds(300));
- EXPECT_EQ(edge.peek_newest()->handle.timestamp, AK::Duration::from_milliseconds(300));
- edge.consume();
- EXPECT(!edge.peek_newest().has_value());
-}
diff --git a/Tests/LibMedia/TestVideoFramePool.cpp b/Tests/LibMedia/TestVideoFramePool.cpp
index d41fb2504cc..a3e0c94dcc2 100644
--- a/Tests/LibMedia/TestVideoFramePool.cpp
+++ b/Tests/LibMedia/TestVideoFramePool.cpp
@@ -8,6 +8,7 @@
#include <AK/MemoryStream.h>
#include <AK/Mutex.h>
#include <AK/Queue.h>
+#include <AK/Random.h>
#include <AK/Time.h>
#include <LibCore/System.h>
#include <LibIPC/Decoder.h>
@@ -67,14 +68,11 @@ static Media::VideoFrameHandle make_handle(Media::VideoFramePool const& pool, Me
};
}
-static Media::VideoFrameHandle make_stress_handle(Media::VideoFramePoolID pool_id, u32 slot_index, u64 slot_acquisition_id)
+static Media::VideoFrameMetadata make_metadata()
{
- auto handle = Media::VideoFrameHandle {
- .pool_id = pool_id,
- .slot_index = slot_index,
- .slot_acquisition_id = slot_acquisition_id,
- .timestamp = AK::Duration::zero(),
- .duration = AK::Duration::zero(),
+ return Media::VideoFrameMetadata {
+ .timestamp = AK::Duration::from_milliseconds(40),
+ .duration = AK::Duration::from_milliseconds(20),
.size = RESOLVED_FRAME_SIZE,
.bit_depth = RESOLVED_FRAME_BIT_DEPTH,
.subsampling = RESOLVED_FRAME_SUBSAMPLING,
@@ -85,7 +83,12 @@ static Media::VideoFrameHandle make_stress_handle(Media::VideoFramePoolID pool_i
Media::VideoFullRangeFlag::Full,
},
};
- return handle;
+}
+
+// Maps a slot's buffer a second time, as receiving it in another process would.
+static Core::AnonymousBuffer received_copy_of(Core::AnonymousBuffer const& buffer)
+{
+ return MUST(Core::AnonymousBuffer::create_from_anon_fd(MUST(Core::System::dup(buffer.fd())), buffer.size()));
}
TEST_CASE(acquire_exhaustion_and_release)
@@ -208,26 +211,21 @@ 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 directory = Media::VideoFrameSlotDirectory::create();
- directory->notify_slot_announced(pool->id(), held.index, pool->slot_buffer(held.index), nullptr);
+ auto frame = MUST(Media::create_received_video_frame(make_metadata(), received_copy_of(pool->slot_buffer(held.index)), nullptr, 0, [] { }));
auto released = pool->try_acquire(FRAME_BYTE_COUNT).release_value();
pool->release_hold(released.index);
pool->shed_storage();
- // Only the held slot's buffer remains, and it still resolves.
+ // Only the held slot's buffer remains.
EXPECT_EQ(pool->allocated_byte_count(), measured_slot_buffer_size(resolved_frame_byte_count()));
- auto frame = directory->resolve_frame(make_handle(pool, held), [] { });
- EXPECT(frame != nullptr);
EXPECT_EQ(frame->yuv_data()->y_data()[0], 0x42);
- EXPECT(frame->revalidate_backing());
- // The held buffer is freed once its last hold releases, and the directory's mapping
- // remains readable.
+ // The held buffer is freed once its last hold releases, while a frame received from it keeps reading it.
pool->release_hold(held.index);
EXPECT_EQ(pool->allocated_byte_count(), 0u);
- EXPECT(directory->resolve_frame(make_handle(pool, held), [] { }) != nullptr);
+ EXPECT_EQ(frame->yuv_data()->y_data()[0], 0x42);
// Acquiring again allocates fresh with a monotonic acquisition ID.
auto fresh = pool->try_acquire(FRAME_BYTE_COUNT).release_value();
@@ -329,291 +327,106 @@ TEST_CASE(slot_freed_callback_wakes_a_waiting_acquirer)
EXPECT_EQ(acquired_index.load(), released_index);
}
-TEST_CASE(directory_resolves_the_current_slot_acquisition_only)
-{
- auto pool = make_pool();
- auto slot = pool->try_acquire(resolved_frame_byte_count()).release_value();
- slot.bytes.fill(0x42);
-
- auto directory = Media::VideoFrameSlotDirectory::create();
- directory->notify_slot_announced(pool->id(), slot.index, pool->slot_buffer(slot.index), nullptr);
-
- auto frame = directory->resolve_frame(make_handle(pool, slot), [] { });
- EXPECT(frame != nullptr);
- EXPECT_EQ(frame->yuv_data()->y_data()[0], 0x42);
- EXPECT(frame->revalidate_backing());
-
- // Recycling the slot into the same buffer invalidates the old acquisition ID, and the new
- // acquisition resolves without a fresh announcement.
- pool->release_hold(slot.index);
- Optional<Media::VideoFramePool::AcquiredSlot> reacquired;
- while (true) {
- reacquired = pool->try_acquire(resolved_frame_byte_count());
- if (reacquired->index == slot.index)
- break;
- pool->release_hold(reacquired->index);
- }
- EXPECT(!frame->revalidate_backing());
- EXPECT(directory->resolve_frame(make_handle(pool, slot), [] { }) == nullptr);
- EXPECT(directory->resolve_frame(make_handle(pool, *reacquired), [] { }) != nullptr);
-}
-
-TEST_CASE(replaced_buffers_stay_resolvable_through_old_mappings)
-{
- auto pool = make_pool();
-
- // Give every slot a buffer so that a larger frame must replace one.
- Vector<Media::VideoFramePool::AcquiredSlot> slots;
- for (u32 i = 0; i < Media::VideoFramePool::MAX_SLOT_COUNT; i++)
- slots.append(pool->try_acquire(resolved_frame_byte_count()).release_value());
- auto slot = slots.first();
- slot.bytes.fill(0x17);
- auto directory = Media::VideoFrameSlotDirectory::create();
- directory->notify_slot_announced(pool->id(), slot.index, pool->slot_buffer(slot.index), nullptr);
- for (auto const& acquired : slots)
- pool->release_hold(acquired.index);
-
- // A larger acquisition replaces the slot's buffer. The old buffer is never written again, so
- // the directory's mapping still resolves the old acquisition ID.
- auto replaced = pool->try_acquire(resolved_frame_byte_count() * 4).release_value();
- EXPECT_EQ(replaced.index, slot.index);
- auto old_frame = directory->resolve_frame(make_handle(pool, slot), [] { });
- EXPECT(old_frame != nullptr);
- EXPECT_EQ(old_frame->yuv_data()->y_data()[0], 0x17);
- EXPECT(old_frame->revalidate_backing());
-
- // The new acquisition resolves only once its buffer is announced.
- EXPECT(directory->resolve_frame(make_handle(pool, replaced), [] { }) == nullptr);
- directory->notify_slot_announced(pool->id(), replaced.index, pool->slot_buffer(replaced.index), nullptr);
- EXPECT(directory->resolve_frame(make_handle(pool, replaced), [] { }) != nullptr);
- EXPECT(directory->resolve_frame(make_handle(pool, slot), [] { }) == nullptr);
-}
-
-TEST_CASE(directory_resolves_through_a_second_mapping)
-{
- auto pool = make_pool();
- auto slot = pool->try_acquire(resolved_frame_byte_count()).release_value();
- slot.bytes.fill(0x7f);
-
- auto slot_buffer = pool->slot_buffer(slot.index);
- auto transferred_fd = MUST(Core::System::dup(slot_buffer.fd()));
- auto transferred_buffer = MUST(Core::AnonymousBuffer::create_from_anon_fd(transferred_fd, slot_buffer.size()));
- auto directory = Media::VideoFrameSlotDirectory::create();
- directory->notify_slot_announced(pool->id(), slot.index, transferred_buffer, nullptr);
-
- auto frame = directory->resolve_frame(make_handle(pool, slot), [] { });
- EXPECT(frame != nullptr);
- EXPECT_NE(frame->yuv_data()->y_data().data(), static_cast<u8 const*>(slot.bytes.data()));
- EXPECT_EQ(frame->yuv_data()->y_data()[0], 0x7f);
-}
-
-TEST_CASE(directory_ignores_invalid_slot_buffers)
-{
- auto pool = make_pool();
- auto slot = pool->try_acquire(resolved_frame_byte_count()).release_value();
-
- auto directory = Media::VideoFrameSlotDirectory::create();
- size_t slots_changed_count = 0;
- directory->set_on_slots_changed([&] { slots_changed_count++; });
-
- directory->notify_slot_announced(pool->id(), slot.index, {}, nullptr);
- auto too_small = MUST(Core::AnonymousBuffer::create_with_size(16));
- directory->notify_slot_announced(pool->id(), slot.index, too_small, nullptr);
-
- EXPECT_EQ(slots_changed_count, 0u);
- EXPECT(directory->resolve_frame(make_handle(pool, slot), [] { }) == nullptr);
-}
-
TEST_CASE(pool_ids_are_unique)
{
EXPECT_NE(make_pool()->id(), make_pool()->id());
}
-TEST_CASE(resolved_frames_read_slots_and_release_on_destruction)
+TEST_CASE(received_frames_read_their_buffer_and_release_it_once_dropped)
{
auto pool = make_pool();
auto slot = pool->try_acquire(resolved_frame_byte_count()).release_value();
slot.bytes.fill(0x33);
- auto directory = Media::VideoFrameSlotDirectory::create();
- directory->notify_slot_announced(pool->id(), slot.index, pool->slot_buffer(slot.index), nullptr);
bool released = false;
{
- auto frame = directory->resolve_frame(make_handle(pool, slot), [&] { released = true; });
- EXPECT(frame != nullptr);
+ auto frame = MUST(Media::create_received_video_frame(make_metadata(), received_copy_of(pool->slot_buffer(slot.index)), nullptr, 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->revalidate_backing());
EXPECT(frame->pool_slot() == nullptr);
+ EXPECT_EQ(frame->received_storage()->sender_id(), 7u);
EXPECT(!released);
}
EXPECT(released);
}
-TEST_CASE(resolve_frame_rejects_stale_and_oversized_handles)
+// The storage comes from another process, so a frame it could not hold is refused, and the storage released at once.
+TEST_CASE(received_frames_must_fit_their_storage)
{
auto pool = make_pool();
auto slot = pool->try_acquire(resolved_frame_byte_count()).release_value();
- auto directory = Media::VideoFrameSlotDirectory::create();
- directory->notify_slot_announced(pool->id(), slot.index, pool->slot_buffer(slot.index), nullptr);
- // A format too large for the slot's buffer must not resolve.
- auto oversized = make_handle(pool, slot);
+ auto release_count = 0u;
+ auto oversized = make_metadata();
oversized.bit_depth = 10;
- EXPECT(directory->resolve_frame(oversized, [] { }) == nullptr);
+ EXPECT(Media::create_received_video_frame(oversized, received_copy_of(pool->slot_buffer(slot.index)), nullptr, 0, [&] { release_count++; }).is_error());
+ EXPECT_EQ(release_count, 1u);
- auto handle = make_handle(pool, slot);
- auto frame = directory->resolve_frame(handle, [] { });
- EXPECT(frame != nullptr);
+ 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_EQ(release_count, 2u);
- // Recycle the slot; the resolved frame must fail revalidation, and the stale handle must
- // no longer resolve.
- pool->release_hold(slot.index);
- while (true) {
- auto reacquired = pool->try_acquire(resolved_frame_byte_count()).release_value();
- if (reacquired.index == slot.index)
- break;
- pool->release_hold(reacquired.index);
- }
- EXPECT(!frame->revalidate_backing());
- EXPECT(directory->resolve_frame(handle, [] { }) == nullptr);
+ EXPECT(Media::create_received_video_frame(make_metadata(), {}, nullptr, 0, [&] { release_count++; }).is_error());
+ EXPECT_EQ(release_count, 3u);
}
-// Handles come from another process, so one describing a frame no decoder produces must not resolve, even when the
-// slot's buffer could hold it.
-TEST_CASE(resolve_frame_rejects_handles_that_could_not_have_been_decoded)
+// Metadata comes from another process, so metadata describing a frame no decoder produces is refused, even when the
+// storage could hold it.
+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 directory = Media::VideoFrameSlotDirectory::create();
- directory->notify_slot_announced(pool->id(), slot.index, pool->slot_buffer(slot.index), nullptr);
- EXPECT(directory->resolve_frame(make_handle(pool, slot), [] { }) != nullptr);
+ auto receive = [&](Media::VideoFrameMetadata const& metadata) {
+ return Media::create_received_video_frame(metadata, received_copy_of(pool->slot_buffer(slot.index)), nullptr, 0, [] { });
+ };
+ EXPECT(!receive(make_metadata()).is_error());
- auto thirteen_bit = make_handle(pool, slot);
+ auto thirteen_bit = make_metadata();
thirteen_bit.bit_depth = 13;
- EXPECT(directory->resolve_frame(thirteen_bit, [] { }) == nullptr);
+ EXPECT(receive(thirteen_bit).is_error());
- auto negative_duration = make_handle(pool, slot);
+ auto negative_duration = make_metadata();
negative_duration.duration = AK::Duration::from_milliseconds(-20);
- EXPECT(directory->resolve_frame(negative_duration, [] { }) == nullptr);
+ EXPECT(receive(negative_duration).is_error());
- auto unknown_primaries = make_handle(pool, slot);
+ auto unknown_primaries = make_metadata();
unknown_primaries.cicp.set_color_primaries(static_cast<Media::ColorPrimaries>(200));
- EXPECT(directory->resolve_frame(unknown_primaries, [] { }) == nullptr);
+ EXPECT(receive(unknown_primaries).is_error());
- auto too_wide = make_handle(pool, slot);
+ auto too_wide = make_metadata();
too_wide.size = { static_cast<int>(Media::MAX_VIDEO_FRAME_DIMENSION) + 1, 1 };
EXPECT(!too_wide.is_valid());
}
-TEST_CASE(handles_that_could_not_have_been_decoded_are_refused_over_ipc)
+TEST_CASE(metadata_that_could_not_have_been_decoded_is_refused_over_ipc)
{
- auto pool = make_pool();
- auto slot = pool->try_acquire(resolved_frame_byte_count()).release_value();
- auto handle = make_handle(pool, slot);
- handle.bit_depth = 13;
+ auto metadata = make_metadata();
+ metadata.bit_depth = 13;
IPC::MessageBuffer message;
IPC::Encoder encoder { message };
- MUST(encoder.encode(handle));
+ MUST(encoder.encode(metadata));
Queue<IPC::Attachment> attachments;
FixedMemoryStream stream { message.data().span() };
IPC::Decoder decoder { stream, attachments };
- EXPECT(decoder.decode<Media::VideoFrameHandle>().is_error());
+ EXPECT(decoder.decode<Media::VideoFrameMetadata>().is_error());
}
-TEST_CASE(directory_resolves_announced_slots)
+TEST_CASE(handles_that_could_not_have_been_decoded_are_refused_over_ipc)
{
auto pool = make_pool();
auto slot = pool->try_acquire(resolved_frame_byte_count()).release_value();
- slot.bytes.fill(0x66);
-
- auto directory = Media::VideoFrameSlotDirectory::create();
- size_t slots_changed_count = 0;
- directory->set_on_slots_changed([&] { slots_changed_count++; });
-
- // A handle resolves to nothing until its slot has been announced.
auto handle = make_handle(pool, slot);
- EXPECT(directory->resolve_frame(handle, [] { }) == nullptr);
-
- directory->notify_slot_announced(pool->id(), slot.index, pool->slot_buffer(slot.index), nullptr);
- EXPECT_EQ(slots_changed_count, 1u);
-
- bool released = false;
- {
- auto frame = directory->resolve_frame(handle, [&] { released = true; });
- EXPECT(frame != nullptr);
- EXPECT_EQ(frame->yuv_data()->y_data()[0], 0x66);
- EXPECT(!released);
- }
- EXPECT(released);
-
- directory->notify_pool_retired(pool->id());
- EXPECT(directory->resolve_frame(handle, [] { }) == nullptr);
-}
-
-TEST_CASE(recycle_versus_hold_stress)
-{
- IGNORE_USE_IN_ESCAPING_LAMBDA auto pool = make_pool();
- auto const frame_count = 50'000;
-
- // Allocate every slot's buffer up front so the consumer's mappings stay valid while the
- // producer recycles same-sized frames through them.
- Vector<Media::VideoFramePool::AcquiredSlot> slots;
- for (u32 i = 0; i < Media::VideoFramePool::MAX_SLOT_COUNT; i++)
- slots.append(pool->try_acquire(resolved_frame_byte_count()).release_value());
- IGNORE_USE_IN_ESCAPING_LAMBDA auto directory = Media::VideoFrameSlotDirectory::create();
- for (u32 i = 0; i < Media::VideoFramePool::MAX_SLOT_COUNT; i++)
- directory->notify_slot_announced(pool->id(), i, pool->slot_buffer(i), nullptr);
- for (auto const& slot : slots)
- pool->release_hold(slot.index);
-
- IGNORE_USE_IN_ESCAPING_LAMBDA Atomic<u64> published_packed { 0 };
- IGNORE_USE_IN_ESCAPING_LAMBDA Atomic<bool> producer_done { false };
+ handle.bit_depth = 13;
- IGNORE_USE_IN_ESCAPING_LAMBDA auto pool_id = pool->id();
- auto consumer_thread = Threading::Thread::construct("PoolConsumer"sv, [&directory, &pool_id, &published_packed, &producer_done]() {
- size_t verified_count = 0;
- auto deadline = MonotonicTime::now_coarse() + AK::Duration::from_seconds(30);
- while ((!producer_done.load() || verified_count == 0) && MonotonicTime::now_coarse() < deadline) {
- auto packed = published_packed.load();
- if (packed == 0)
- continue;
- // The producer packs (slot << 32) | (slot_acquisition_id & 0xffffffff), with slot_acquisition_id
- // also determining the fill byte, so any undetected recycle shows up as a
- // mismatched pattern below.
- auto slot_index = static_cast<u32>(packed >> 32);
- auto slot_acquisition_id = packed & 0xffffffffu;
-
- auto handle = make_stress_handle(pool_id, slot_index, slot_acquisition_id);
- auto frame = directory->resolve_frame(handle, [] { });
- if (frame == nullptr)
- continue;
- auto first = frame->yuv_data()->y_data()[0];
- auto last = frame->yuv_data()->v_data()[frame->yuv_data()->v_data().size() - 1];
- if (!frame->revalidate_backing())
- continue;
- // Revalidation passed, so the bytes we read must match this slot_acquisition_id's pattern.
- EXPECT_EQ(first, static_cast<u8>(slot_acquisition_id));
- EXPECT_EQ(last, static_cast<u8>(slot_acquisition_id));
- verified_count++;
- }
- EXPECT(verified_count > 0);
- return 0;
- });
- consumer_thread->start();
-
- for (int i = 0; i < frame_count; i++) {
- auto slot = pool->try_acquire(resolved_frame_byte_count());
- if (!slot.has_value())
- continue;
- VERIFY(slot->slot_acquisition_id <= 0xffffffffu);
- slot->bytes.fill(static_cast<u8>(slot->slot_acquisition_id));
- published_packed.store((static_cast<u64>(slot->index) << 32) | slot->slot_acquisition_id);
- pool->release_hold(slot->index);
- }
- producer_done.store(true);
- (void)consumer_thread->join();
+ IPC::MessageBuffer message;
+ IPC::Encoder encoder { message };
+ MUST(encoder.encode(handle));
+ Queue<IPC::Attachment> attachments;
+ FixedMemoryStream stream { message.data().span() };
+ IPC::Decoder decoder { stream, attachments };
+ EXPECT(decoder.decode<Media::VideoFrameHandle>().is_error());
}
// A frame shown a second time arrives as a second hold on the acquisition its slot is already held for, which must
@@ -663,10 +476,9 @@ 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)));
+ return MUST(Media::VideoSurface::create_from_dma_buf(get_random<u64>(), move(dma_buf)));
# endif
}
@@ -871,78 +683,29 @@ TEST_CASE(surface_slots_survive_a_mach_port_round_trip)
EXPECT_NE(lent_surface, nullptr);
auto reimported = MUST(Core::IOSurfaceHandle::from_mach_port(lent_surface->create_mach_port()));
- EXPECT_EQ(reimported.id(), surface->id());
+ EXPECT_EQ(static_cast<u64>(reimported.id()), surface->id());
EXPECT_EQ(reimported.width(), 16u);
EXPECT_EQ(reimported.height(), 16u);
}
# endif
-TEST_CASE(directory_resolves_an_announced_surface_slot)
+TEST_CASE(received_surface_frames_read_their_surface)
{
- auto pool = MUST(Media::VideoFrameSurfacePool::create());
auto surface = make_surface();
- 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));
-
- Media::VideoFrameHandle handle {
- .pool_id = pool->id(),
- .slot_index = acquired.index,
- .slot_acquisition_id = acquired.slot_acquisition_id,
- .timestamp = {},
- .duration = {},
- .size = { 16, 16 },
- .bit_depth = 8,
- .subsampling = Media::Subsampling(true, true),
- .cicp = {},
- };
+ auto metadata = make_metadata();
+ metadata.size = { 16, 16 };
- auto frame = directory->resolve_frame(handle, [] { });
- EXPECT_NE(frame, nullptr);
- EXPECT_NE(frame->surface(), nullptr);
+ 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 live on the GPU, so no view into its slot buffer is offered.
+ // 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());
-}
-
-TEST_CASE(directory_waits_for_a_slot_to_be_announced_with_its_new_surface)
-{
- auto pool = MUST(Media::VideoFrameSurfacePool::create());
- auto directory = Media::VideoFrameSlotDirectory::create();
-
- Vector<NonnullRefPtr<Media::VideoSurface>> surfaces;
- 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(), make_contents()).value());
- directory->notify_slot_announced(pool->id(), acquisitions.last().index, pool->slot_buffer(acquisitions.last().index), pool->slot_surface(acquisitions.last().index));
- pool->release_hold(acquisitions.last().index);
- }
- // The new surface displaces the first one from its slot, but the directory has yet to hear of that.
- auto new_surface = make_surface();
- auto acquired = pool->try_acquire(new_surface, make_contents()).value();
- EXPECT_EQ(acquired.index, acquisitions.first().index);
-
- Media::VideoFrameHandle handle {
- .pool_id = pool->id(),
- .slot_index = acquired.index,
- .slot_acquisition_id = acquired.slot_acquisition_id,
- .timestamp = {},
- .duration = {},
- .size = { 16, 16 },
- .bit_depth = 8,
- .subsampling = Media::Subsampling(true, true),
- .cicp = {},
- };
- EXPECT_EQ(directory->resolve_frame(handle, [] { }), nullptr);
+ 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());
- directory->notify_slot_announced(pool->id(), acquired.index, pool->slot_buffer(acquired.index), pool->slot_surface(acquired.index));
- auto frame = directory->resolve_frame(handle, [] { });
- EXPECT_NE(frame, nullptr);
- EXPECT_EQ(frame->surface()->id(), new_surface->id());
+ auto buffer = MUST(Core::AnonymousBuffer::create_with_size(4096));
+ EXPECT(Media::create_received_video_frame(metadata, buffer, surface, 0, [] { }).is_error());
}
TEST_CASE(surface_slots_hold_and_free_through_the_shared_ledger)