Truly independent web browser
LibMedia: Allow video producers to be explicitly suspended
Zaggy1024ece378dc13b2
diff --git a/Libraries/LibMedia/Producers/DecodedVideoProducer.cpp b/Libraries/LibMedia/Producers/DecodedVideoProducer.cppindex c3a16d1b5f3..481de62fb68 100644--- a/Libraries/LibMedia/Producers/DecodedVideoProducer.cpp+++ b/Libraries/LibMedia/Producers/DecodedVideoProducer.cpp@@ -62,6 +62,11 @@ void DecodedVideoProducer::start()m_thread_data->start();}+void DecodedVideoProducer::suspend()+{+ m_thread_data->suspend();+}+VideoProducerOutput DecodedVideoProducer::peek(){return m_thread_data->peek();@@ -107,6 +112,8 @@ VideoProducerOutput DecodedVideoProducer::ThreadData::peek_while_locked()// A read stops being reported as blocked before its unblocked handler sets a checkpoint, so the checkpoint is read// first.auto checkpoint = m_checkpoint.load();+ if (m_suspension_request == SuspensionRequest::FromConsumer)+ return { nullptr, PipelineStatus::Suspended, checkpoint };auto read_is_blocked = read_is_blocked_while_locked();if (m_last_processed_seek_id != m_seek_id)return { nullptr, read_is_blocked ? PipelineStatus::Blocked : PipelineStatus::Pending, checkpoint };@@ -274,14 +281,14 @@ DecoderErrorOr<void> DecodedVideoProducer::ThreadData::create_decoder_for_frame(void DecodedVideoProducer::ThreadData::wait_for_another_seek_or_exit(u32 seek_id){auto locker = take_lock();- while (m_seek_id == seek_id && !should_thread_exit_while_locked())+ while (m_seek_id == seek_id && !should_break_out_of_loop_while_locked())m_wait_state->condition.wait();}bool DecodedVideoProducer::ThreadData::check_if_seek_is_needed_or_allow_demuxer_reads(u32 seek_id){auto locker = take_lock();- if (m_seek_id != seek_id || should_thread_exit_while_locked())+ if (m_seek_id != seek_id || should_break_out_of_loop_while_locked())return true;m_demuxer->reset_blocking_reads_aborted_for_track(m_track);m_wait_state->output_should_interrupt_demuxer_reads.store(true, MemoryOrder::memory_order_relaxed);@@ -356,6 +363,24 @@ void DecodedVideoProducer::ThreadData::start()wake();}+void DecodedVideoProducer::ThreadData::suspend()+{+ auto locker = take_lock();+ VERIFY(!m_decode_thread_id.is_current_thread());+ if (m_requested_state == RequestedState::Exit)+ return;+ if (m_requested_state == RequestedState::None) {+ m_requested_state = RequestedState::Running;+ m_last_consumer_activity = MonotonicTime::now();+ }+ m_suspension_request = SuspensionRequest::FromConsumer;+ m_demuxer->set_blocking_reads_aborted_for_track(m_track);+ m_demuxer_read_is_blocked.store(false);+ m_downstream_needs_wake = true;+ dispatch_wake_if_needed_while_locked();+ wake();+}+void DecodedVideoProducer::ThreadData::exit(){auto locker = take_lock();@@ -367,14 +392,13 @@ void DecodedVideoProducer::ThreadData::exit()void DecodedVideoProducer::ThreadData::note_consumer_activity_while_locked() const{m_last_consumer_activity = MonotonicTime::now();- m_auto_suspend_requested = false;+ if (m_suspension_request == SuspensionRequest::Automatic)+ m_suspension_request = SuspensionRequest::None;}DecodedVideoProducer::ThreadData::WaitResult DecodedVideoProducer::ThreadData::wait_for_frame_storage_while_locked(){- if (m_requested_state != RequestedState::Running)- return WaitResult::ExitDecodeLoop;- if (m_auto_suspend_requested)+ if (m_requested_state != RequestedState::Running || m_suspension_request != SuspensionRequest::None)return WaitResult::ExitDecodeLoop;auto idle_at = m_last_consumer_activity + m_auto_suspend_idle_timeout;@@ -386,7 +410,8 @@ DecodedVideoProducer::ThreadData::WaitResult DecodedVideoProducer::ThreadData::wreturn WaitResult::ContinueDecoding;}- m_auto_suspend_requested = true;+ if (m_suspension_request == SuspensionRequest::None)+ m_suspension_request = SuspensionRequest::Automatic;return WaitResult::ExitDecodeLoop;}@@ -400,6 +425,7 @@ void DecodedVideoProducer::ThreadData::seek(AK::Duration timestamp, InvalidateHeauto locker = take_lock();VERIFY(!m_decode_thread_id.is_current_thread());note_consumer_activity_while_locked();+ m_suspension_request = SuspensionRequest::None;m_downstream_needs_wake = true;auto seek_behavior = m_seek_reason.load(MemoryOrder::memory_order_relaxed);@@ -443,15 +469,15 @@ void DecodedVideoProducer::ThreadData::wait_for_start()m_wait_state->condition.wait();}-bool DecodedVideoProducer::ThreadData::should_thread_exit_while_locked() const+bool DecodedVideoProducer::ThreadData::should_break_out_of_loop_while_locked() const{- return m_requested_state == RequestedState::Exit;+ return m_requested_state == RequestedState::Exit || m_suspension_request == SuspensionRequest::FromConsumer;}bool DecodedVideoProducer::ThreadData::should_thread_exit() const{auto locker = take_lock();- return should_thread_exit_while_locked();+ return m_requested_state == RequestedState::Exit;}template<typename Invokee>@@ -468,13 +494,14 @@ bool DecodedVideoProducer::ThreadData::handle_auto_suspension(){VERIFY(m_decode_thread_id.is_current_thread());auto locker = take_lock();- if (!m_auto_suspend_requested)+ if (m_suspension_request == SuspensionRequest::None)return false;-m_queue.clear();m_last_queued_frame = nullptr;m_decoder.clear();- m_auto_suspend_requested = false;+ // A seek requested before the consumer suspended us is one that no consumer waits for anymore.+ if (exchange(m_suspension_request, SuspensionRequest::None) == SuspensionRequest::FromConsumer)+ resolve_seek(m_seek_id);m_current_halting_status = PipelineStatus::Suspended;// The consumer's last peek predates the suspension, so wake it regardless of what it saw.m_downstream_needs_wake = true;@@ -613,7 +640,7 @@ void DecodedVideoProducer::ThreadData::handle_seek()seek_reason = m_seek_reason.load(MemoryOrder::memory_order_relaxed);timestamp = m_seek_timestamp;- if (should_thread_exit_while_locked())+ if (should_break_out_of_loop_while_locked())return;m_demuxer->reset_blocking_reads_aborted_for_track(m_track);m_wait_state->output_should_interrupt_demuxer_reads.store(false, MemoryOrder::memory_order_relaxed);@@ -738,7 +765,7 @@ void DecodedVideoProducer::ThreadData::handle_seek()if (frame_result.error().category() == DecoderErrorCategory::TryAgain) {auto locker = take_lock();- if (should_thread_exit_while_locked())+ if (should_break_out_of_loop_while_locked())return;if (m_seek_id != seek_id) {new_seek_id = m_seek_id;@@ -856,7 +883,7 @@ void DecodedVideoProducer::ThreadData::push_data_and_decode_some_frames()auto locker = take_lock();enter_halting_state(status, move(error));- while (m_seek_id == m_last_processed_seek_id && !should_thread_exit_while_locked())+ while (m_seek_id == m_last_processed_seek_id && !should_break_out_of_loop_while_locked())m_wait_state->condition.wait();};@@ -888,7 +915,7 @@ void DecodedVideoProducer::ThreadData::push_data_and_decode_some_frames()if (!m_wait_state->frame_storage_was_freed && wait_for_frame_storage_while_locked() == WaitResult::ExitDecodeLoop)return;m_wait_state->frame_storage_was_freed = false;- if (should_thread_exit_while_locked())+ if (should_break_out_of_loop_while_locked())return;continue;}diff --git a/Libraries/LibMedia/Producers/DecodedVideoProducer.h b/Libraries/LibMedia/Producers/DecodedVideoProducer.hindex 6927da23305..d790fb49193 100644--- a/Libraries/LibMedia/Producers/DecodedVideoProducer.h+++ b/Libraries/LibMedia/Producers/DecodedVideoProducer.h@@ -55,6 +55,7 @@ public:void set_error_handler(ErrorHandler&&);virtual void start() override;+ virtual void suspend() override;virtual VideoProducerOutput peek() override;virtual void consume() override;@@ -79,6 +80,7 @@ private:void set_wake_handler(PipelineWakeHandler);void start();+ void suspend();VideoDecoderSelection select_decoder_for_frame(CodedFrame const&, VideoDecoderSelection after = {}) const;void replace_decoder_once_drained(CodedFrame const&, DecodeIntent);DecoderErrorOr<void> receive_into_decoder(CodedFrame const&, DecodeIntent);@@ -104,7 +106,7 @@ private:void register_decode_thread();void wait_for_start();- bool should_thread_exit_while_locked() const;+ bool should_break_out_of_loop_while_locked() const;bool should_thread_exit() const;bool handle_auto_suspension();template<typename Invokee>@@ -202,7 +204,12 @@ private:AK::Duration const m_auto_suspend_idle_timeout;mutable MonotonicTime m_last_consumer_activity { MonotonicTime::now() };- mutable bool m_auto_suspend_requested { false };+ enum class SuspensionRequest : u8 {+ None,+ Automatic,+ FromConsumer,+ };+ mutable SuspensionRequest m_suspension_request { SuspensionRequest::None };};NonnullRefPtr<ThreadData> m_thread_data;diff --git a/Libraries/LibMedia/Producers/RemoteVideoProducer.cpp b/Libraries/LibMedia/Producers/RemoteVideoProducer.cppindex 65c1fbf9937..288ecaa8d1d 100644--- a/Libraries/LibMedia/Producers/RemoteVideoProducer.cpp+++ b/Libraries/LibMedia/Producers/RemoteVideoProducer.cpp@@ -12,6 +12,7 @@ namespace Media {NonnullRefPtr<RemoteVideoProducer> RemoteVideoProducer::create(Delegates delegates){VERIFY(delegates.request_start);+ VERIFY(delegates.request_suspend);VERIFY(delegates.request_seek);return adopt_ref(*new RemoteVideoProducer(move(delegates)));}@@ -70,6 +71,11 @@ void RemoteVideoProducer::start()m_delegates.request_start();}+void RemoteVideoProducer::suspend()+{+ m_delegates.request_suspend();+}+void RemoteVideoProducer::set_wake_handler(PipelineWakeHandler handler){m_wake_handler.set(move(handler));diff --git a/Libraries/LibMedia/Producers/RemoteVideoProducer.h b/Libraries/LibMedia/Producers/RemoteVideoProducer.hindex 50d59b0713b..733512b74c0 100644--- a/Libraries/LibMedia/Producers/RemoteVideoProducer.h+++ b/Libraries/LibMedia/Producers/RemoteVideoProducer.h@@ -29,6 +29,7 @@ public:struct Delegates {Function<void()> request_start;+ Function<void()> request_suspend;Function<void(AK::Duration, InvalidateHeldData, u64 newest_received_lend_id)> request_seek;};@@ -43,6 +44,7 @@ public:void stop_consuming();virtual void start() override;+ virtual void suspend() override;virtual VideoProducerOutput peek() override;virtual void consume() override;virtual void set_wake_handler(PipelineWakeHandler) override;diff --git a/Libraries/LibMedia/Producers/VideoProducer.h b/Libraries/LibMedia/Producers/VideoProducer.hindex 512ffca0b7d..4c6c90df464 100644--- a/Libraries/LibMedia/Producers/VideoProducer.h+++ b/Libraries/LibMedia/Producers/VideoProducer.h@@ -27,6 +27,8 @@ public:virtual ~VideoProducer() = default;virtual void start() = 0;+ // Drops any decoded output and reports Suspended until the next seek, starting the producer if it hasn't started.+ virtual void suspend() = 0;virtual VideoProducerOutput peek() = 0;virtual void consume() = 0;diff --git a/Libraries/LibMedia/Sinks/RemoteVideoSink.cpp b/Libraries/LibMedia/Sinks/RemoteVideoSink.cppindex ebd050bef2d..69c233e5293 100644--- a/Libraries/LibMedia/Sinks/RemoteVideoSink.cpp+++ b/Libraries/LibMedia/Sinks/RemoteVideoSink.cpp@@ -31,6 +31,8 @@ public:void seek_upstream(AK::Duration timestamp, InvalidateHeldData, u64 newest_received_lend_id);void seek_input_directly(AK::Duration timestamp);void start_input();+ void suspend_input();+ void consumer_started_input();void release_frame(u64 lend_id);void pump_thread_loop();@@ -62,6 +64,9 @@ private:bool m_exit_requested { false };bool m_pump_thread_exited { false };bool m_wake_pending { false };+ // The input may still hold what it had for a previous consumer, so it is only peeked once this consumer has started+ // or suspended it, as it would be in process.+ bool m_consumer_has_started_input { 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;@@ -146,6 +151,7 @@ void RemoteVideoSink::report_remote_resize(Gfx::Size<u32> size)}void RemoteVideoSink::start_input() { m_thread_data->start_input(); }+void RemoteVideoSink::suspend_input() { m_thread_data->suspend_input(); }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(); }@@ -284,6 +290,27 @@ void RemoteVideoSink::ThreadData::start_input()}if (input)input->start();+ consumer_started_input();+}++void RemoteVideoSink::ThreadData::suspend_input()+{+ RefPtr<VideoProducer> input;+ {+ MutexLocker locker { m_mutex };+ input = m_input;+ }+ if (input)+ input->suspend();+ consumer_started_input();+}++void RemoteVideoSink::ThreadData::consumer_started_input()+{+ MutexLocker locker { m_mutex };+ m_consumer_has_started_input = true;+ m_wake_pending = true;+ m_wait_condition.broadcast();}void RemoteVideoSink::ThreadData::release_frame(u64 lend_id)@@ -416,7 +443,7 @@ void RemoteVideoSink::ThreadData::pump_thread_loop()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()) {+ if (m_input == nullptr || !m_consumer_has_started_input || !may_lend_another_frame || m_direct_seek_timestamp.has_value()) {wait_on_pump_thread(locker);continue;}diff --git a/Libraries/LibMedia/Sinks/RemoteVideoSink.h b/Libraries/LibMedia/Sinks/RemoteVideoSink.hindex 84b45cfa97e..53819a1e7ef 100644--- a/Libraries/LibMedia/Sinks/RemoteVideoSink.h+++ b/Libraries/LibMedia/Sinks/RemoteVideoSink.h@@ -63,6 +63,7 @@ public:virtual void set_state_change_handler(PipelineStateChangeHandler) override;virtual void set_resize_handler(PipelineResizeHandler) override;void start_input();+ void suspend_input();void report_remote_status(PipelineStatus, PipelineCheckpoint);void report_remote_resize(Gfx::Size<u32>);diff --git a/Libraries/LibMedia/VideoPresentation/VideoPresentationClientConnection.cpp b/Libraries/LibMedia/VideoPresentation/VideoPresentationClientConnection.cppindex e9e07260833..e19212d2922 100644--- a/Libraries/LibMedia/VideoPresentation/VideoPresentationClientConnection.cpp+++ b/Libraries/LibMedia/VideoPresentation/VideoPresentationClientConnection.cpp@@ -75,6 +75,11 @@ void VideoPresentationClientConnection::video_edge_ready(u64 edge_id, MediaTimeRconnection.async_request_start(edge_id);});};+ consumer_delegates.request_suspend = [weak_connection, edge_id] {+ weak_connection.with_target([&](auto& connection) {+ connection.async_request_suspend(edge_id);+ });+ };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_request_seek(edge_id, timestamp, invalidate_held_data, newest_received_lend_id);diff --git a/Libraries/LibMedia/VideoPresentation/VideoPresentationServer.ipc b/Libraries/LibMedia/VideoPresentation/VideoPresentationServer.ipcindex a43d85b4b7e..04e4bd8197f 100644--- a/Libraries/LibMedia/VideoPresentation/VideoPresentationServer.ipc+++ b/Libraries/LibMedia/VideoPresentation/VideoPresentationServer.ipc@@ -8,6 +8,7 @@ endpoint VideoPresentationServer {release_video_edge(u64 edge_id) =|request_start(u64 edge_id) =|+ request_suspend(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) =|diff --git a/Libraries/LibMedia/VideoPresentation/VideoPresentationServerConnection.cpp b/Libraries/LibMedia/VideoPresentation/VideoPresentationServerConnection.cppindex 5abcfa5b51c..e23047acf1b 100644--- a/Libraries/LibMedia/VideoPresentation/VideoPresentationServerConnection.cpp+++ b/Libraries/LibMedia/VideoPresentation/VideoPresentationServerConnection.cpp@@ -147,6 +147,12 @@ void VideoPresentationServerConnection::request_start(u64 edge_id)it->value.pump->start_input();}+void VideoPresentationServerConnection::request_suspend(u64 edge_id)+{+ if (auto it = m_edge_states.find(edge_id); it != m_edge_states.end())+ it->value.pump->suspend_input();+}+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())diff --git a/Libraries/LibMedia/VideoPresentation/VideoPresentationServerConnection.h b/Libraries/LibMedia/VideoPresentation/VideoPresentationServerConnection.hindex db3029741bd..083a8a86ed4 100644--- a/Libraries/LibMedia/VideoPresentation/VideoPresentationServerConnection.h+++ b/Libraries/LibMedia/VideoPresentation/VideoPresentationServerConnection.h@@ -41,6 +41,7 @@ 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_suspend(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, PipelineCheckpoint checkpoint) override;diff --git a/Tests/LibMedia/TestDecodedVideoProducer.cpp b/Tests/LibMedia/TestDecodedVideoProducer.cppindex 2ee6b8a8382..6c69174b70a 100644--- a/Tests/LibMedia/TestDecodedVideoProducer.cpp+++ b/Tests/LibMedia/TestDecodedVideoProducer.cpp@@ -1626,6 +1626,107 @@ TEST_CASE(video_producer_auto_suspends_and_resumes_only_from_a_seek)EXPECT(seek_to_resume_and_pump_until_woken_with_data(loop, *producer, AK::Duration::zero()).has_value());}+TEST_CASE(video_producer_suspended_before_starting_reads_nothing_until_a_seek)+{+ auto& loop = never_destroyed_event_loop();++ auto [inner_demuxer, track] = demuxer_and_video_track_for("./vp9_in_webm.webm"sv);+ auto demuxer = BlockingDemuxer::create(inner_demuxer, NumericLimits<size_t>::max());+ auto producer = TRY_OR_FAIL(Media::DecodedVideoProducer::try_create(loop, demuxer, track, SHORT_AUTO_SUSPEND_TIMEOUT));++ bool woken = false;+ producer->set_wake_handler([&] { woken = true; });+ // A wake can still be queued on the shared event loop once this test returns.+ ScopeGuard stop_handling_wakes = [&] { producer->set_wake_handler({}); };+ producer->suspend();+ EXPECT_EQ(producer->peek().status, Media::PipelineStatus::Suspended);+ EXPECT(pump_until(loop, [&] { return woken; }));++ sleep_past_the_idle_timeout();+ loop.pump(Core::EventLoop::WaitMode::PollForEvents);+ EXPECT_EQ(producer->peek().status, Media::PipelineStatus::Suspended);+ EXPECT_EQ(demuxer->samples_served(), 0u);++ EXPECT(seek_to_resume_and_pump_until_woken_with_data(loop, *producer, AK::Duration::zero()).has_value());+ EXPECT(demuxer->samples_served() > 0);+}++// A producer suspended at the end of its stream no longer reports that end, which may be stale for a new consumer.+TEST_CASE(video_producer_suspended_at_the_end_of_its_stream_waits_for_a_seek)+{+ auto& loop = never_destroyed_event_loop();++ auto [demuxer, track] = demuxer_and_video_track_for("./vp9_in_webm.webm"sv);+ auto producer = TRY_OR_FAIL(Media::DecodedVideoProducer::try_create(loop, demuxer, track));+ producer->start();+ EXPECT(pump_until(loop, [&] {+ auto output = producer->peek();+ if (output.frame != nullptr)+ producer->consume();+ return output.status == Media::PipelineStatus::EndOfStream;+ }));++ bool woken = false;+ producer->set_wake_handler([&] { woken = true; });+ ScopeGuard stop_handling_wakes = [&] { producer->set_wake_handler({}); };+ producer->suspend();+ EXPECT_EQ(producer->peek().status, Media::PipelineStatus::Suspended);+ EXPECT(pump_until(loop, [&] { return woken; }));+ sleep_past_the_idle_timeout();+ loop.pump(Core::EventLoop::WaitMode::PollForEvents);+ EXPECT_EQ(producer->peek().status, Media::PipelineStatus::Suspended);++ EXPECT(seek_to_resume_and_pump_until_woken_with_data(loop, *producer, AK::Duration::zero()).has_value());+}++TEST_CASE(video_producer_suspended_during_a_blocked_read_stops_reading)+{+ auto& loop = never_destroyed_event_loop();++ auto [inner_demuxer, track] = demuxer_and_video_track_for("./vp9_in_webm.webm"sv);+ auto demuxer = BlockingDemuxer::create(inner_demuxer, 3);+ auto producer = TRY_OR_FAIL(Media::DecodedVideoProducer::try_create(loop, demuxer, track));+ producer->start();+ EXPECT(demuxer->wait_until_a_read_blocks(AK::Duration::from_seconds(5)));++ producer->suspend();+ EXPECT_EQ(producer->peek().status, Media::PipelineStatus::Suspended);+ auto samples_served = demuxer->samples_served();+ demuxer->stop_blocking_reads();+ sleep_past_the_idle_timeout();+ loop.pump(Core::EventLoop::WaitMode::PollForEvents);+ EXPECT_EQ(demuxer->samples_served(), samples_served);+ EXPECT_EQ(producer->peek().status, Media::PipelineStatus::Suspended);+}++// A seek requested before the suspension is not one that the consumer is still waiting for.+TEST_CASE(video_producer_suspended_with_a_seek_pending_drops_that_seek)+{+ auto& loop = never_destroyed_event_loop();++ auto stream = load_test_file("big_buck_bunny_5s.webm"sv);+ auto demuxer = create_demuxer(stream);+ auto tracks = TRY_OR_FAIL(demuxer->get_tracks_for_type(Media::TrackType::Video));+ VERIFY(!tracks.is_empty());+ auto producer = TRY_OR_FAIL(Media::DecodedVideoProducer::try_create(loop, demuxer, tracks[0]));+ producer->start();+ EXPECT(pump_until(loop, [&] { return producer->peek().status == Media::PipelineStatus::HaveData; }));++ producer->seek(AK::Duration::from_seconds(3));+ producer->suspend();+ EXPECT_EQ(producer->peek().status, Media::PipelineStatus::Suspended);+ sleep_past_the_idle_timeout();+ loop.pump(Core::EventLoop::WaitMode::PollForEvents);+ EXPECT_EQ(producer->peek().status, Media::PipelineStatus::Suspended);++ auto output = seek_to_resume_and_pump_until_woken_with_data(loop, *producer, AK::Duration::zero());+ if (!output.has_value()) {+ FAIL("Expected data after seeking");+ return;+ }+ EXPECT(output->frame->timestamp() < AK::Duration::from_seconds(1));+}+TEST_CASE(video_producer_suspends_while_frames_are_held_and_wakes_the_consumer){auto& loop = never_destroyed_event_loop();diff --git a/Tests/LibMedia/TestMediaCommon.h b/Tests/LibMedia/TestMediaCommon.hindex b0b5a7881ad..457b8238b35 100644--- a/Tests/LibMedia/TestMediaCommon.h+++ b/Tests/LibMedia/TestMediaCommon.h@@ -171,6 +171,7 @@ public:}virtual void start() override { }+ virtual void suspend() override { }virtual Media::VideoProducerOutput peek() override{MutexLocker locker { m_mutex };diff --git a/Tests/LibMedia/TestRemoteVideoNode.cpp b/Tests/LibMedia/TestRemoteVideoNode.cppindex 0b97edd3871..1060a4dccbf 100644--- a/Tests/LibMedia/TestRemoteVideoNode.cpp+++ b/Tests/LibMedia/TestRemoteVideoNode.cpp@@ -59,6 +59,45 @@ NonnullRefPtr<DecodedVideoProducer> make_decoder(Core::EventLoop& loop, StringVireturn MUST(DecodedVideoProducer::try_create(loop, demuxer, tracks[0]));}+// Forwards to another producer, recording what the first peek of it saw.+class FirstPeekRecordingVideoProducer final : public VideoProducer {+public:+ static NonnullRefPtr<FirstPeekRecordingVideoProducer> create(NonnullRefPtr<VideoProducer> inner)+ {+ return adopt_ref(*new FirstPeekRecordingVideoProducer(move(inner)));+ }++ virtual void start() override { m_inner->start(); }+ virtual void suspend() override { m_inner->suspend(); }+ virtual VideoProducerOutput peek() override+ {+ auto output = m_inner->peek();+ MutexLocker locker { m_mutex };+ if (!m_first_peeked_status.has_value())+ m_first_peeked_status = output.status;+ return output;+ }+ virtual void consume() override { m_inner->consume(); }+ virtual void set_wake_handler(PipelineWakeHandler handler) override { m_inner->set_wake_handler(move(handler)); }+ virtual void seek(AK::Duration timestamp, InvalidateHeldData invalidate_held_data) override { m_inner->seek(timestamp, invalidate_held_data); }++ Optional<PipelineStatus> first_peeked_status() const+ {+ MutexLocker locker { m_mutex };+ return m_first_peeked_status;+ }++private:+ explicit FirstPeekRecordingVideoProducer(NonnullRefPtr<VideoProducer> inner)+ : m_inner(move(inner))+ {+ }++ NonnullRefPtr<VideoProducer> m_inner;+ mutable Mutex m_mutex;+ Optional<PipelineStatus> m_first_peeked_status;+};+bool spin_until(Core::EventLoop& loop, Function<bool()> condition, AK::Duration timeout = AK::Duration::from_seconds(2)){auto deadline = MonotonicTime::now_coarse() + timeout;@@ -119,6 +158,9 @@ struct VideoEdgeTestHarnessbool 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;+ // Holds the consumer's suspension back from the pump until the test sends it, as it would be crossing processes.+ bool holds_suspension_requests { false };+ bool has_held_suspension_request { false };void post(Message message){@@ -165,7 +207,12 @@ struct VideoEdgeTestHarness}};-void wire_full_node(VideoEdgeTestHarness& harness, NonnullRefPtr<VideoProducer> const& decoder)+enum class ConsumerStart : u8 {+ Running,+ Suspended,+};++void wire_full_node(VideoEdgeTestHarness& harness, NonnullRefPtr<VideoProducer> const& decoder, ConsumerStart start = ConsumerStart::Running){// 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.@@ -186,6 +233,13 @@ void wire_full_node(VideoEdgeTestHarness& harness, NonnullRefPtr<VideoProducer>RemoteVideoProducer::Delegates consumer_delegates;consumer_delegates.request_start = [&harness] { harness.sink->start_input(); };+ consumer_delegates.request_suspend = [&harness] {+ if (harness.holds_suspension_requests) {+ harness.has_held_suspension_request = true;+ return;+ }+ harness.sink->suspend_input();+ };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);};@@ -195,7 +249,10 @@ void wire_full_node(VideoEdgeTestHarness& harness, NonnullRefPtr<VideoProducer>// harness.consumer is set before connect_input, whose lock publishes it to the pump before the// pump can send anything to the consumer.MUST(harness.sink->connect_input(decoder));- harness.consumer->start();+ if (start == ConsumerStart::Suspended)+ harness.consumer->suspend();+ else+ harness.consumer->start();}NonnullRefPtr<VideoFrame> create_pooled_frame(VideoFramePool& pool, AK::Duration timestamp, AK::Duration duration = AK::Duration::from_milliseconds(33))@@ -220,6 +277,7 @@ RemoteVideoProducer::Delegates make_consumer_delegates(size_t& upstream_seeks){RemoteVideoProducer::Delegates delegates;delegates.request_start = [] { };+ delegates.request_suspend = [] { };delegates.request_seek = [&upstream_seeks](AK::Duration, InvalidateHeldData, u64) { upstream_seeks++; };return delegates;}@@ -306,6 +364,82 @@ TEST_CASE(remote_video_node_delivers_every_frame_in_order)EXPECT_EQ(delivered, reference);}+TEST_CASE(remote_video_node_suspended_before_starting_delivers_nothing_until_a_seek)+{+ auto& loop = never_destroyed_event_loop();+ auto decoder = make_decoder(loop, TEST_CLIP);+ auto harness = make_ref_counted<VideoEdgeTestHarness>();+ wire_full_node(*harness, decoder, ConsumerStart::Suspended);++ auto pump_until_consumer_reports = [&](PipelineStatus status) {+ auto deadline = MonotonicTime::now_coarse() + AK::Duration::from_seconds(10);+ while (MonotonicTime::now_coarse() < deadline) {+ loop.pump(Core::EventLoop::WaitMode::PollForEvents);+ harness->deliver_messages();+ auto reported_status = harness->consumer->peek().status;+ if (reported_status == status)+ return true;+ if (reported_status == PipelineStatus::HaveData)+ return false;+ }+ return false;+ };+ EXPECT(pump_until_consumer_reports(PipelineStatus::Suspended));++ harness->consumer->seek(AK::Duration::zero());+ EXPECT(pump_until_consumer_reports(PipelineStatus::HaveData));+}++// A producer that played to its end before its sink attached still reports that end. Until the consumer's suspension+// reaches the pump, the pump must not pass it on, or the consumer would see an end that the clock may be far from.+TEST_CASE(remote_video_node_attached_suspended_to_an_ended_producer_reports_no_end_of_stream)+{+ auto& loop = never_destroyed_event_loop();+ auto decoder = make_decoder(loop, TEST_CLIP);+ decoder->start();+ EXPECT(pump_until(loop, [&] {+ auto output = decoder->peek();+ if (output.frame != nullptr)+ decoder->consume();+ return output.status == PipelineStatus::EndOfStream;+ }));++ auto input = FirstPeekRecordingVideoProducer::create(decoder);+ auto harness = make_ref_counted<VideoEdgeTestHarness>();+ harness->holds_suspension_requests = true;+ wire_full_node(*harness, input, ConsumerStart::Suspended);+ EXPECT(harness->has_held_suspension_request);++ bool consumer_saw_end_of_stream = false;+ auto pump_until_consumer_reports = [&](PipelineStatus status) {+ return pump_until(loop, [&] {+ harness->deliver_messages();+ auto reported_status = harness->consumer->peek().status;+ if (reported_status == PipelineStatus::EndOfStream)+ consumer_saw_end_of_stream = true;+ return reported_status == status;+ });+ };++ // Give a pump that peeks too early the time to do so. Whether it does is checked from what it first saw.+ auto deadline = MonotonicTime::now_coarse() + AK::Duration::from_milliseconds(100);+ while (MonotonicTime::now_coarse() < deadline) {+ loop.pump(Core::EventLoop::WaitMode::PollForEvents);+ harness->deliver_messages();+ }++ harness->sink->suspend_input();+ EXPECT(pump_until_consumer_reports(PipelineStatus::Suspended));+ auto first_peeked_status = input->first_peeked_status();+ EXPECT(first_peeked_status.has_value());+ if (first_peeked_status.has_value())+ EXPECT_EQ(*first_peeked_status, PipelineStatus::Suspended);++ harness->consumer->seek(AK::Duration::zero());+ EXPECT(pump_until_consumer_reports(PipelineStatus::HaveData));+ EXPECT(!consumer_saw_end_of_stream);+}+// Stress the boundary under genuine concurrency: the pump thread and the draining thread race while// seeks are injected mid-drain. Seeks go backward, so a correct node visibly rewinds; a leaked// superseded-generation frame comes from ahead of where we were and trips the assertion. Also catches@@ -627,6 +761,7 @@ TEST_CASE(consumer_requests_seeks_before_releasing_stale_frames)RefPtr<RemoteVideoProducer> consumer;RemoteVideoProducer::Delegates delegates;delegates.request_start = [] { };+ delegates.request_suspend = [] { };delegates.request_seek = [&](AK::Duration, InvalidateHeldData, u64 newest_received_lend_id) {events.append("seek"sv);requested_newest_received_lend_id = newest_received_lend_id;