Truly independent web browser
LibMedia: Seek producers locally when the remote sink will request one
Zaggy1024bf3615c57ecf
diff --git a/Libraries/LibMedia/Sinks/RemoteVideoSink.cpp b/Libraries/LibMedia/Sinks/RemoteVideoSink.cppindex 74913b7347d..5a51995d788 100644--- a/Libraries/LibMedia/Sinks/RemoteVideoSink.cpp+++ b/Libraries/LibMedia/Sinks/RemoteVideoSink.cpp@@ -28,6 +28,7 @@ public:void transmit_seek(InvalidateHeldData) const;void transmit_time_reader(MediaTimeReader const&) const;void seek_upstream(AK::Duration timestamp, InvalidateHeldData);+ void seek_input_directly(AK::Duration timestamp);void start_input();void notify_space_available();void release_slot(VideoFramePoolID, u32 slot_index);@@ -46,8 +47,23 @@ private:u64 outstanding_lend_count { 0 };};+ struct LentSlot {+ VideoFramePoolID pool_id;+ u32 slot_index { 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;+ };+void enqueue_frame(VideoFrame const&, u32 seek_id);- void lend_slot(PooledVideoFrameSlot const&);+ void lend_slot(VideoFrame const&);+ bool consumer_may_satisfy_seek_locally(AK::Duration timestamp) const;void wait_on_pump_thread(MutexLocker<Mutex>&);VideoEdgeQueue m_edge;@@ -60,9 +76,14 @@ private:bool m_pump_thread_exited { false };bool m_wake_pending { false };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;};ErrorOr<NonnullRefPtr<RemoteVideoSink>> RemoteVideoSink::create(Delegates delegates)@@ -99,7 +120,12 @@ VideoEdgeQueue const& RemoteVideoSink::edge() const { return m_thread_data->edgeErrorOr<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); }-void RemoteVideoSink::seek(AK::Duration, InvalidateHeldData invalidate_held_data) { m_thread_data->transmit_seek(invalidate_held_data); }+void RemoteVideoSink::seek(AK::Duration timestamp, InvalidateHeldData invalidate_held_data)+{+ if (invalidate_held_data == InvalidateHeldData::No)+ 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); }@@ -168,6 +194,7 @@ void RemoteVideoSink::ThreadData::disconnect_input(NonnullRefPtr<VideoProducer>MutexLocker locker { m_mutex };VERIFY(m_input == producer.ptr());m_input = nullptr;+ m_direct_seek_timestamp = {};}void RemoteVideoSink::ThreadData::ring_data_available() const@@ -188,13 +215,57 @@ void RemoteVideoSink::ThreadData::transmit_time_reader(MediaTimeReader const& tivoid RemoteVideoSink::ThreadData::seek_upstream(AK::Duration timestamp, InvalidateHeldData invalidate_held_data){MutexLocker locker { m_mutex };- if (m_input)+ 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_actual_seek_id++;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;+ };+ {+ MutexLocker locker { m_lent_pools_mutex };+ for (auto const& [slot, range] : m_lent_frame_ranges)+ include_range(range);+ }+ if (m_peeked_frame_range.has_value())+ include_range(*m_peeked_frame_range);+ if (!earliest_timestamp.has_value() || timestamp < *earliest_timestamp)+ return false;+ if (timestamp < *latest_end)+ return true;+ auto status = m_edge.status();+ return status.has_value() && status->seek_id == m_actual_seek_id && status->status == PipelineStatus::EndOfStream;+}++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;+ m_input->seek(timestamp, InvalidateHeldData::No);+}+void RemoteVideoSink::ThreadData::start_input(){RefPtr<VideoProducer> input;@@ -273,6 +344,7 @@ void RemoteVideoSink::ThreadData::pump_thread_loop()if (enqueued_frame_seek_id.has_value()) {{MutexLocker locker { m_mutex };+ m_peeked_frame_range = {};if (m_exit_requested)break;// Paired with the fence in RemoteVideoProducer::seek(): either that seek's look at the ring saw this@@ -284,7 +356,7 @@ void RemoteVideoSink::ThreadData::pump_thread_loop()enqueued_frame_seek_id = {};continue;}- if (m_edge.requested_seek_id() != m_actual_seek_id) {+ if (m_edge.requested_seek_id() != m_actual_seek_id || m_direct_seek_timestamp.has_value()) {wait_on_pump_thread(locker);continue;}@@ -303,13 +375,15 @@ void RemoteVideoSink::ThreadData::pump_thread_loop()MutexLocker locker { m_mutex };if (m_exit_requested)break;- auto seek_request_is_pending = m_edge.requested_seek_id() != m_actual_seek_id;+ 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() };}if (output.status == PipelineStatus::HaveData) {@@ -332,27 +406,28 @@ void RemoteVideoSink::ThreadData::pump_thread_loop()void RemoteVideoSink::ThreadData::enqueue_frame(VideoFrame const& frame, u32 seek_id){- auto const* pool_slot = frame.pool_slot();- VERIFY(pool_slot != nullptr);- lend_slot(*pool_slot);+ lend_slot(frame);MUST(m_edge.enqueue(VideoFrameHandle::for_frame(frame), seek_id));}-void RemoteVideoSink::ThreadData::lend_slot(PooledVideoFrameSlot const& pool_slot)+void RemoteVideoSink::ThreadData::lend_slot(VideoFrame const& frame){- auto& ledger = pool_slot.ledger();- auto slot_index = pool_slot.slot_index();+ 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()) {+ 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.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; })++;@@ -371,8 +446,10 @@ void RemoteVideoSink::ThreadData::release_slot(VideoFramePoolID pool_id, u32 sloif (!count.has_value() || *count == 0)return;ledger = lent_pool->ledger;- if (--*count == 0)+ 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);@@ -387,6 +464,7 @@ void RemoteVideoSink::ThreadData::release_all_lends(){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) {diff --git a/Libraries/LibMedia/Sinks/RemoteVideoSink.h b/Libraries/LibMedia/Sinks/RemoteVideoSink.hindex c37be35b3dc..31d60da2db7 100644--- a/Libraries/LibMedia/Sinks/RemoteVideoSink.h+++ b/Libraries/LibMedia/Sinks/RemoteVideoSink.h@@ -31,8 +31,9 @@ public:struct Delegates {// Rung when newly enqueued data, a status change or a resumed clock may need the consumer woken.Function<void()> ring_data_available;- // A seek reaches the far-end consumer first so its cached frames are consulted before anything moves upstream.- // The consumer will then seek upstream, which passes through the RemoteVideoProducer and across the edge.+ // 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;diff --git a/Tests/LibMedia/TestMediaCommon.h b/Tests/LibMedia/TestMediaCommon.hindex cc4a60377bd..c62aa343803 100644--- a/Tests/LibMedia/TestMediaCommon.h+++ b/Tests/LibMedia/TestMediaCommon.h@@ -7,6 +7,7 @@#pragma once#include <AK/Function.h>+#include <AK/Mutex.h>#include <AK/NeverDestroyed.h>#include <AK/Optional.h>#include <LibAudio/ChannelMap.h>@@ -157,6 +158,7 @@ public:void append_output(RefPtr<Media::VideoFrame> frame, Media::PipelineStatus status){+ MutexLocker locker { m_mutex };m_outputs.append({ move(frame), status });}@@ -169,11 +171,16 @@ public:virtual void start() override { }virtual Media::VideoProducerOutput peek() override{+ MutexLocker locker { m_mutex };if (m_outputs.is_empty())return { nullptr, Media::PipelineStatus::Pending };return m_outputs.first();}- virtual void consume() override { (void)m_outputs.take_first(); }+ virtual void consume() override+ {+ MutexLocker locker { m_mutex };+ (void)m_outputs.take_first();+ }virtual void set_wake_handler(Media::PipelineWakeHandler handler) override { m_wake_handler = move(handler); }virtual void seek(AK::Duration, Media::InvalidateHeldData = Media::InvalidateHeldData::No) override { m_seek_count++; }@@ -182,6 +189,7 @@ public:private:ScriptedVideoProducer() = default;+ Mutex m_mutex;Vector<Media::VideoProducerOutput> m_outputs;size_t m_seek_count { 0 };Media::PipelineWakeHandler m_wake_handler;diff --git a/Tests/LibMedia/TestRemoteVideoNode.cpp b/Tests/LibMedia/TestRemoteVideoNode.cppindex ba0ef724c96..9f8271a3f84 100644--- a/Tests/LibMedia/TestRemoteVideoNode.cpp+++ b/Tests/LibMedia/TestRemoteVideoNode.cpp@@ -544,6 +544,150 @@ TEST_CASE(pump_holds_off_while_a_seek_request_is_in_flight)EXPECT_EQ(consumer_edge.peek()->seek_id, 1u);}+namespace {++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)));+}++}++// A seek the consumer holds nothing for goes to the input right away, and the consumer's request for it, which+// follows, is already answered; a request for anywhere else is a new seek.+TEST_CASE(sink_seeks_its_input_directly_when_the_consumer_holds_nothing_for_the_seek)+{+ auto sink = make_sink_with_inert_delegates();+ auto producer = ScriptedVideoProducer::create();+ MUST(sink->connect_input(producer));++ sink->seek(AK::Duration::from_seconds(1));+ EXPECT_EQ(producer->seek_count(), 1u);+ sink->seek_upstream(AK::Duration::from_seconds(1));+ 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));+ EXPECT_EQ(producer->seek_count(), 2u);+}++// The consumer may seek on its own while a direct seek awaits its request, as when it starts ticking again. Its+// request supersedes the direct seek, so the input follows the consumer, pumping resumes under the request's stamp,+// and the request for the direct seek, which arrives after, is a seek of its own again.+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 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();++ sink->seek(AK::Duration::from_seconds(1));+ 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));+ EXPECT_EQ(producer->seek_count(), 2u);+ EXPECT(spin_until(loop, [&] { return consumer_edge.peek().has_value(); }));+ EXPECT_EQ(consumer_edge.peek()->seek_id, 1u);++ consumer_edge.set_requested_seek_id(2);+ sink->seek_upstream(AK::Duration::from_seconds(1));+ EXPECT_EQ(producer->seek_count(), 3u);+}++// The frames lent across the edge may satisfy a seek on the consumer's side, so such a seek waits for the consumer's+// decision.+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 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); }));++ 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));+ EXPECT_EQ(producer->seek_count(), 1u);++ sink->seek(AK::Duration::from_milliseconds(500));+ EXPECT_EQ(producer->seek_count(), 2u);+}++// Between the direct seek and the consumer's request for it, a frame of the new position would be stamped with the+// seek before it, so pumping waits for the request.+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 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);+ sink->start_input();+ producer->append_frame(create_pooled_frame(*pool, AK::Duration::zero()));+ producer->append_frame(create_pooled_frame(*pool, AK::Duration::from_milliseconds(33)));+ producer->wake();++ 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);+ }++ consumer_edge.set_requested_seek_id(1);+ sink->seek_upstream(AK::Duration::from_seconds(1));+ EXPECT_EQ(producer->seek_count(), 1u);+ EXPECT(spin_until(loop, [&] { return consumer_edge.peek().has_value(); }));+ EXPECT_EQ(consumer_edge.peek()->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)