Truly independent web browser
LibMedia+LibWeb+Compositor: Bring video sinks up to date for captures
Zaggy1024c8fa6cbdfc61
diff --git a/Libraries/LibCompositing/Video/VideoFramePresentationPage.h b/Libraries/LibCompositing/Video/VideoFramePresentationPage.hindex 4668c31f6cf..8ba58531f50 100644--- a/Libraries/LibCompositing/Video/VideoFramePresentationPage.h+++ b/Libraries/LibCompositing/Video/VideoFramePresentationPage.h@@ -57,6 +57,7 @@ public:SharedMemoryValue<MonotonicTime> presentation_time;u32 width { 0 };u32 height { 0 };+ bool frame_is_up_to_date { false };};void publish_presented_frame(PresentedFrame const&);Optional<PresentedFrame> presented_frame() const;diff --git a/Libraries/LibMedia/Sinks/DisplayingVideoSink.cpp b/Libraries/LibMedia/Sinks/DisplayingVideoSink.cppindex a4ac3dbbe9f..a6f710c8307 100644--- a/Libraries/LibMedia/Sinks/DisplayingVideoSink.cpp+++ b/Libraries/LibMedia/Sinks/DisplayingVideoSink.cpp@@ -22,6 +22,7 @@ ErrorOr<NonnullRefPtr<DisplayingVideoSink>> DisplayingVideoSink::try_create(MediDisplayingVideoSink::DisplayingVideoSink(MediaTimeReader time_reader): m_time_reader(move(time_reader)){+ m_reported_freshness = freshness();}DisplayingVideoSink::~DisplayingVideoSink()@@ -90,6 +91,13 @@ void DisplayingVideoSink::disconnect_input(NonnullRefPtr<VideoProducer> const& ivoid DisplayingVideoSink::seek(AK::Duration timestamp, InvalidateHeldData invalidate_held_data){+ begin_seek(timestamp, invalidate_held_data, SeekStatus::InProgress);+ report_freshness_if_changed();+}++void DisplayingVideoSink::begin_seek(AK::Duration timestamp, InvalidateHeldData invalidate_held_data, SeekStatus seek_status)+{+ VERIFY(seek_status != SeekStatus::None);m_seek_id++;m_latest_status = PipelineStatus::Pending;m_last_dispatched_status = PipelineStatus::Pending;@@ -129,8 +137,7 @@ void DisplayingVideoSink::seek(AK::Duration timestamp, InvalidateHeldData invaliif (m_input != nullptr)m_input->seek(timestamp, invalidate_held_data);- if (m_seek_status == SeekStatus::None)- m_seek_status = SeekStatus::InProgress;+ m_seek_status = seek_status;m_next_frame = nullptr;}@@ -148,6 +155,8 @@ DisplayingVideoSinkUpdateResult DisplayingVideoSink::update(MonotonicTime now){if (m_input == nullptr)return {};+ if (is_ticking())+ m_has_updated_since_ticking_began = true;auto time_state = m_time_reader.time_state(now);auto current_time = time_state.time;@@ -166,7 +175,7 @@ DisplayingVideoSinkUpdateResult DisplayingVideoSink::update(MonotonicTime now)last_status = output.status;m_input_checkpoint = output.checkpoint;if (output.frame == nullptr) {- if (is_terminal(last_status) && m_seek_status == SeekStatus::InProgress) {+ if (is_terminal(last_status) && m_seek_status != SeekStatus::None) {m_seek_status = SeekStatus::None;new_frame_available = true;}@@ -255,7 +264,8 @@ DisplayingVideoSinkUpdateResult DisplayingVideoSink::update(MonotonicTime now)auto time_is_changing = time_state.is_advancing || m_seek_status != SeekStatus::None;if (time_is_changing) {m_next_frame = nullptr;- m_seek_status = SeekStatus::InProgress;+ if (m_seek_status == SeekStatus::None)+ m_seek_status = SeekStatus::CatchingUp;m_seek_resolution_is_pending_frame_at_target = true;m_input->seek(current_time);status_to_dispatch = PipelineStatus::Pending;@@ -292,6 +302,7 @@ DisplayingVideoSinkUpdateResult DisplayingVideoSink::update(MonotonicTime now)if (may_require_updates && updates_were_stopped && !new_frame_available && m_on_present_needed)m_on_present_needed();+ report_freshness_if_changed();return {.new_frame_available = new_frame_available,.may_require_updates = may_require_updates,@@ -308,13 +319,29 @@ void DisplayingVideoSink::set_ticking(bool ticking)auto was_ticking = exchange(m_is_ticking, ticking);if (ticking == was_ticking)return;- if (ticking)- seek_back_to_current_time();- if (m_on_ticking_changed)- m_on_ticking_changed();+ if (ticking) {+ m_has_updated_since_ticking_began = false;+ catch_up_to_clock();+ }+ report_freshness_if_changed();+}++DisplayingVideoSink::Freshness DisplayingVideoSink::freshness() const+{+ return { .is_ticking = is_ticking(), .is_catching_up = is_catching_up(), .frame_is_up_to_date = frame_is_up_to_date() };+}++void DisplayingVideoSink::report_freshness_if_changed()+{+ auto freshness = this->freshness();+ if (freshness == m_reported_freshness)+ return;+ m_reported_freshness = freshness;+ if (m_on_freshness_changed)+ m_on_freshness_changed();}-void DisplayingVideoSink::seek_back_to_current_time()+void DisplayingVideoSink::catch_up_to_clock(){if (m_seek_status != SeekStatus::None)return;@@ -324,7 +351,8 @@ void DisplayingVideoSink::seek_back_to_current_time()if (m_current_frame != nullptr && m_current_frame->contains_timestamp(current_time))return;- seek(current_time);+ begin_seek(current_time, InvalidateHeldData::No, SeekStatus::CatchingUp);+ report_freshness_if_changed();}RefPtr<VideoFrame> DisplayingVideoSink::current_frame() constdiff --git a/Libraries/LibMedia/Sinks/DisplayingVideoSink.h b/Libraries/LibMedia/Sinks/DisplayingVideoSink.hindex f0c18f2abdc..cbb8cfec04d 100644--- a/Libraries/LibMedia/Sinks/DisplayingVideoSink.h+++ b/Libraries/LibMedia/Sinks/DisplayingVideoSink.h@@ -52,7 +52,14 @@ public:virtual void notify_clock_resumed() override;virtual void set_ticking(bool) override;bool is_ticking() const { return m_is_ticking; }- void set_on_ticking_changed(Function<void()> handler) { m_on_ticking_changed = move(handler); }+ // Called when the sink starts or stops ticking, catching up, or having an up-to-date frame.+ void set_on_freshness_changed(Function<void()> handler) { m_on_freshness_changed = move(handler); }+ // Seeks the input to the clock's time if the current frame doesn't show it, whether or not the sink is ticking.+ void catch_up_to_clock();+ // A catch-up that waits for data keeps the last frame shown until the data arrives, so it is not waited for.+ bool is_catching_up() const { return m_seek_status == SeekStatus::CatchingUp && m_latest_status != PipelineStatus::Blocked; }+ // Whether the frame may change if it is ticked.+ bool frame_is_up_to_date() const { return is_ticking() && m_has_updated_since_ticking_began && !is_catching_up(); }DisplayingVideoSinkUpdateResult update(MonotonicTime now);RefPtr<VideoFrame> current_frame() const;@@ -62,12 +69,13 @@ public:private:void dispatch_state_if_changed(PipelineStatus, PipelineCheckpoint);- void seek_back_to_current_time();+ void report_freshness_if_changed();MediaTimeReader m_time_reader;RefPtr<VideoProducer> m_input;bool m_is_ticking { true };+ bool m_has_updated_since_ticking_began { false };RefPtr<VideoFrame> m_next_frame;RefPtr<VideoFrame> m_current_frame;bool m_cached_frames_are_discontinuous { false };@@ -76,9 +84,12 @@ private:enum class SeekStatus : u8 {None,+ // A seek that the sink made to catch its frames up to the clock. A seek from upstream replaces it.+ CatchingUp,InProgress,};SeekStatus m_seek_status { SeekStatus::None };+ void begin_seek(AK::Duration timestamp, InvalidateHeldData, SeekStatus);PipelineStateChangeHandler m_on_state_changed;PipelineStatus m_latest_status { PipelineStatus::Pending };@@ -91,7 +102,16 @@ private:Gfx::Size<u32> m_last_dispatched_size;Function<void()> m_on_present_needed;- Function<void()> m_on_ticking_changed;+ Function<void()> m_on_freshness_changed;+ struct Freshness {+ bool is_ticking { false };+ bool is_catching_up { false };+ bool frame_is_up_to_date { false };++ bool operator==(Freshness const&) const = default;+ };+ Freshness freshness() const;+ Freshness m_reported_freshness;bool m_last_update_may_require_updates { false };};diff --git a/Libraries/LibWeb/Compositor/CompositorConnection.cpp b/Libraries/LibWeb/Compositor/CompositorConnection.cppindex 5848c7291e0..d5c39287b28 100644--- a/Libraries/LibWeb/Compositor/CompositorConnection.cpp+++ b/Libraries/LibWeb/Compositor/CompositorConnection.cpp@@ -466,6 +466,33 @@ bool CompositorConnection::did_rasterize(Layout::RustFFI::RasterizationOutcome oVERIFY_NOT_REACHED();}+void CompositorConnection::bring_video_sink_up_to_date(Media::VideoSinkHandle video_sink_handle, Optional<MonotonicTime> deadline)+{+ if (!can_send_message_to_compositor())+ return;+ auto token = m_next_video_sink_up_to_date_token++;+ async_bring_video_sink_up_to_date(video_sink_handle, token);+ while (true) {+ OwnPtr<Messages::CompositorWebContentClient::VideoSinkIsUpToDate> answer;+ if (deadline.has_value())+ answer = wait_for_specific_endpoint_message_until<Messages::CompositorWebContentClient::VideoSinkIsUpToDate>(deadline.value());+ else+ answer = wait_for_specific_endpoint_message<Messages::CompositorWebContentClient::VideoSinkIsUpToDate>();+ if (!answer) {+ if (!is_open())+ did_lose_compositor();+ return;+ }+ if (answer->token() == token)+ return;+ }+}++void CompositorConnection::video_sink_is_up_to_date(u64)+{+ // CompositorConnection::bring_video_sink_up_to_date() waits for its answer, and an answer it gave up on goes nowhere.+}+void CompositorConnection::invalidate_keyboard_scroll_state(Web::CompositorContextId context_id, u64 generation){if (!can_send_message_to_compositor())diff --git a/Libraries/LibWeb/Compositor/CompositorConnection.h b/Libraries/LibWeb/Compositor/CompositorConnection.hindex 9ee4a05b8c1..15dfba61a85 100644--- a/Libraries/LibWeb/Compositor/CompositorConnection.h+++ b/Libraries/LibWeb/Compositor/CompositorConnection.h@@ -69,6 +69,8 @@ public:void add_video_sink(Media::VideoSinkHandle, NonnullRefPtr<Compositing::VideoFramePresentationPage>);void remove_video_sink(Media::VideoSinkHandle);void release_video_frame_hold(Media::VideoSinkHandle, u64 generation);+ // Waits for the compositor to say that the sink's frame follows its clock, until the deadline if there is one.+ void bring_video_sink_up_to_date(Media::VideoSinkHandle, Optional<MonotonicTime> deadline);RefPtr<IPC::ThreadSafeMessagePoster> poster_while_compositor_is_reachable();bool post_canvas_2d_stream_batch_fonts_and_image_frames(ReadonlySpan<Gfx::Font const*>, ReadonlySpan<Gfx::DecodedImageFrame const*>);void did_fail_to_post_canvas_2d_message();@@ -133,6 +135,7 @@ private:virtual void async_scroll_updates(Web::CompositorContextId, Compositing::PendingAsyncScrollUpdates) override;virtual void animated_content_moved_under_pointer(Web::CompositorContextId, i64 frame_time_nanoseconds) override;bool did_rasterize(Layout::RustFFI::RasterizationOutcome);+ virtual void video_sink_is_up_to_date(u64 token) override;virtual void did_complete_screenshot(Compositing::ScreenshotRequestId) override;virtual void did_fail_screenshot(Compositing::ScreenshotRequestId) override;virtual void paint_contexts_for_screenshot(u64 preparation_id, Vector<Web::CompositorContextId>) override;@@ -155,6 +158,7 @@ private:u64 m_next_screenshot_request_id { 1 };Atomic<u64> m_next_rasterization_token { 1 };u64 m_serial { 0 };+ u64 m_next_video_sink_up_to_date_token { 1 };bool m_has_lost_compositor { false };// The media server whose presentation channel the Compositor holds; a replacement server needs a new channel.Optional<u64> m_video_presentation_channel_media_client_generation;diff --git a/Libraries/LibWeb/Compositor/CompositorHost.cpp b/Libraries/LibWeb/Compositor/CompositorHost.cppindex a01489edf5d..04b2288c4e3 100644--- a/Libraries/LibWeb/Compositor/CompositorHost.cpp+++ b/Libraries/LibWeb/Compositor/CompositorHost.cpp@@ -299,6 +299,12 @@ void CompositorHost::remove_video_sink(Media::VideoSinkHandle video_sink_handle)connection->remove_video_sink(video_sink_handle);}+void CompositorHost::bring_video_sink_up_to_date(Media::VideoSinkHandle video_sink_handle, Optional<MonotonicTime> deadline)+{+ if (auto* connection = compositor_connection())+ connection->bring_video_sink_up_to_date(video_sink_handle, deadline);+}+Compositing::VideoFrameHold::ReleaseThroughCompositor CompositorHost::video_frame_hold_releaser_for_current_connection() const{auto* connection = compositor_connection();diff --git a/Libraries/LibWeb/Compositor/CompositorHost.h b/Libraries/LibWeb/Compositor/CompositorHost.hindex b55d32098e3..e13ce459df9 100644--- a/Libraries/LibWeb/Compositor/CompositorHost.h+++ b/Libraries/LibWeb/Compositor/CompositorHost.h@@ -164,6 +164,7 @@ public:// Returns whether a compositor heard of the sink, which one that connects later will not have.[[nodiscard]] bool add_video_sink(Media::VideoSinkHandle, NonnullRefPtr<Compositing::VideoFramePresentationPage>);void remove_video_sink(Media::VideoSinkHandle);+ void bring_video_sink_up_to_date(Media::VideoSinkHandle, Optional<MonotonicTime> deadline);Compositing::VideoFrameHold::ReleaseThroughCompositor video_frame_hold_releaser_for_current_connection() const;void invalidate_wheel_event_listener_state(Web::CompositorContextId, u64 generation);void invalidate_keyboard_scroll_state(Web::CompositorContextId, u64 generation);diff --git a/Libraries/LibWeb/HTML/HTMLMediaElement.cpp b/Libraries/LibWeb/HTML/HTMLMediaElement.cppindex 05b39e97c75..c9ab0fd9d51 100644--- a/Libraries/LibWeb/HTML/HTMLMediaElement.cpp+++ b/Libraries/LibWeb/HTML/HTMLMediaElement.cpp@@ -118,6 +118,20 @@ public:m_hold_for_video_frame_callbacks = nullptr;}+ bool frame_is_up_to_date() const+ {+ if (!m_presentation_page)+ return true;+ auto presented_frame = m_presentation_page->presented_frame();+ return presented_frame.has_value() && presented_frame->frame_is_up_to_date;+ }++ void bring_frame_up_to_date(Optional<MonotonicTime> deadline)+ {+ if (m_compositor_host)+ m_compositor_host->bring_video_sink_up_to_date(m_handle, deadline);+ }+Optional<Compositing::CapturedVideoFrame> capture_current_frame(){if (!m_compositor_host || !m_presentation_page)@@ -2259,6 +2273,19 @@ Optional<Compositing::CapturedVideoFrame> HTMLMediaElement::capture_current_videif (!m_active_video_sink)return {};note_frame_captured();++ // NB: If the sink doesn't have an up-to-date frame, give it some time to catch up before capturing a stale or+ // missing one instead. This blocks the main thread, so it must be bounded. After this initial wait, the+ // sink will be kept ticking for a certain time, so subsequent captures won't block. Tests wait without a+ // bound, so that a sink that never catches up times the test out rather than depending on load.+ static constexpr auto capture_catch_up_limit = AK::Duration::from_milliseconds(500);+ if (m_ready_state >= ReadyState::HaveCurrentData && !m_active_video_sink->frame_is_up_to_date()) {+ sync_video_sink_ticking();+ Optional<MonotonicTime> deadline;+ if (!Window::in_test_mode())+ deadline = MonotonicTime::now() + capture_catch_up_limit;+ m_active_video_sink->bring_frame_up_to_date(deadline);+ }return m_active_video_sink->capture_current_frame();}diff --git a/Services/Compositor/CompositorState.cpp b/Services/Compositor/CompositorState.cppindex 45ecd824a5d..737a570531c 100644--- a/Services/Compositor/CompositorState.cpp+++ b/Services/Compositor/CompositorState.cpp@@ -229,6 +229,9 @@ void CompositorState::destroy_contexts_for_web_content_client(CompositorStateWebm_screenshot_preparations.remove_all_matching([&](auto, auto const& preparation) {return preparation.requester == client.web_content_client_id();});+ m_pending_screenshots.remove_all_matching([&](auto, auto const& screenshot) {+ return screenshot.requester == client.web_content_client_id();+ });Vector<u64> preparations_awaiting_client;for (auto& [preparation_id, preparation] : m_screenshot_preparations) {if (preparation.awaited_painters.remove(client.web_content_client_id()))@@ -237,6 +240,7 @@ void CompositorState::destroy_contexts_for_web_content_client(CompositorStateWebm_web_content_clients.remove(client.web_content_client_id());for (auto preparation_id : preparations_awaiting_client)finish_screenshot_preparation_if_done(preparation_id);+ paint_screenshots_whose_sinks_have_caught_up();}CompositorState::PlaceholderCanvasAllocation CompositorState::allocate_placeholder_canvas(CompositorStateWebContentClient& client)@@ -360,7 +364,7 @@ void CompositorState::add_video_sink(CompositorStateWebContentClient& client, Meauto& sinks = m_video_sink_states.ensure(&client, [] { return HashMap<Media::VideoSinkHandle, VideoSinkState> {}; });if (sinks.contains(handle))return;- sinks.set(handle, VideoSinkState {});+ sinks.set(handle, VideoSinkState { .sink = nullptr, .requires_updates = false, .was_ticking = false, .published_frame_is_up_to_date = false, .up_to_date_request_token = {} });client.create_video_edge(handle);}@@ -375,19 +379,55 @@ void CompositorState::create_video_edges(CompositorStateWebContentClient& clientvoid CompositorState::remove_video_sink(CompositorStateWebContentClient& client, Media::VideoSinkHandle handle){- if (auto client_sinks = m_video_sink_states.get(&client); client_sinks.has_value())+ if (auto client_sinks = m_video_sink_states.get(&client); client_sinks.has_value()) {+ // The client gave up on the sink, so it isn't waiting for it either.+ if (auto sink_state = client_sinks->get(handle); sink_state.has_value() && sink_state->up_to_date_request_token.has_value())+ client.tell_video_sink_is_up_to_date(*sink_state->up_to_date_request_token);client_sinks->remove(handle);+ }client.release_video_edge(handle);+ paint_screenshots_whose_sinks_have_caught_up();}-void CompositorState::video_sink_ticking_changed(CompositorStateWebContentClient& client, Media::VideoSinkHandle handle)+void CompositorState::video_sink_freshness_changed(CompositorStateWebContentClient& client, Media::VideoSinkHandle handle){auto* sink_state = video_sink_state(client, handle);if (!sink_state || !sink_state->sink)return;- if (sink_state->sink->is_ticking())- present_contexts_drawing_video_sink(client, handle);- update_unpainted_video_update_scheduling();+ auto is_ticking = sink_state->sink->is_ticking();+ if (is_ticking != exchange(sink_state->was_ticking, is_ticking)) {+ if (is_ticking)+ present_contexts_drawing_video_sink(client, handle);+ update_unpainted_video_update_scheduling();+ }+ publish_video_sink_freshness(client, handle, *sink_state);+}++void CompositorState::publish_video_sink_freshness(CompositorStateWebContentClient& client, Media::VideoSinkHandle handle, VideoSinkState& sink_state)+{+ // Whatever changed the sink's frame may also have finished a screenshot's wait for it.+ paint_screenshots_whose_sinks_have_caught_up();++ auto frame_is_up_to_date = sink_state.sink && sink_state.sink->frame_is_up_to_date();+ if (frame_is_up_to_date != sink_state.published_frame_is_up_to_date) {+ sink_state.published_frame_is_up_to_date = frame_is_up_to_date;+ client.video_sink_frame_freshness_changed(handle, frame_is_up_to_date);+ }+ if (!frame_is_up_to_date)+ return;+ if (auto token = exchange(sink_state.up_to_date_request_token, {}); token.has_value())+ client.tell_video_sink_is_up_to_date(*token);+}++void CompositorState::bring_video_sink_up_to_date(CompositorStateWebContentClient& client, Media::VideoSinkHandle handle, u64 token)+{+ auto* sink_state = video_sink_state(client, handle);+ if (!sink_state || (sink_state->sink && sink_state->sink->frame_is_up_to_date())) {+ client.tell_video_sink_is_up_to_date(token);+ return;+ }+ if (auto superseded_token = exchange(sink_state->up_to_date_request_token, token); superseded_token.has_value())+ client.tell_video_sink_is_up_to_date(*superseded_token);}// The sink's owner decides on ticking, and the sink hears of it across its edge. A sink with no edge yet cannot be@@ -403,17 +443,21 @@ void CompositorState::on_video_sink_ready(CompositorStateWebContentClient& clienif (!sink_state)return;sink_state->sink = sink;- sink->set_on_ticking_changed([this, &client, handle] {- video_sink_ticking_changed(client, handle);- });sink->set_on_present_needed([this, &client, handle] {- if (auto* sink_state = video_sink_state(client, handle); sink_state && sink_state->sink)+ auto* sink_state = video_sink_state(client, handle);+ if (sink_state && sink_state->sink)client.video_sink_presented_frame(handle, sink_state->sink->current_frame(), sink_state->sink->take_frame_counts());present_contexts_drawing_video_sink(client, handle);update_unpainted_video_update_scheduling();+ if (sink_state)+ publish_video_sink_freshness(client, handle, *sink_state);+ });+ sink->set_on_freshness_changed([this, &client, handle] {+ video_sink_freshness_changed(client, handle);});present_contexts_drawing_video_sink(client, handle);update_unpainted_video_update_scheduling();+ publish_video_sink_freshness(client, handle, *sink_state);}void CompositorState::update_unpainted_video_update_scheduling()@@ -654,6 +698,7 @@ CompositorState::VideoSinkUpdateResult CompositorState::update_all_video_sinks()frame_counts = sink_state.sink->take_frame_counts();if (!frame_counts.is_zero())client_entry.key->video_sink_counted_frames(sink_entry.key, frame_counts);+ publish_video_sink_freshness(*client_entry.key, sink_entry.key, sink_state);if (!is_painted && sink_state.requires_updates)result = VideoSinkUpdateResult::UnpaintedSinkRequiresUpdates;}@@ -761,13 +806,123 @@ void CompositorState::present_frame(Web::CompositorContextId context_id, Gfx::Inm_core.present_frame_of_page(context_id, viewport_rect);}-bool CompositorState::request_screenshot(Web::CompositorContextId context_id, Gfx::ShareableBitmap& target_bitmap)+// How long a screenshot waits for the video sinks it draws to catch up to their clocks, after which it shows the frames+// they have.+static constexpr auto SCREENSHOT_VIDEO_SINK_LIMIT = AK::Duration::from_seconds(2);++void CompositorState::request_screenshot(CompositorStateWebContentClient& requester, Web::CompositorContextId context_id, Compositing::ScreenshotRequestId request_id, Gfx::ShareableBitmap target_bitmap){VERIFY(presented_context_if_present(context_id));- if (!target_bitmap.is_valid() || !target_bitmap.bitmap())- return false;- auto target_surface = Gfx::PaintingSurface::wrap_bitmap(*target_bitmap.bitmap());- return m_core.paint_screenshot(context_id, *target_surface);++ PendingScreenshot screenshot { requester.web_content_client_id(), context_id, request_id, move(target_bitmap), {}, {} };+ catch_up_newly_drawn_screenshot_sinks(screenshot);++ auto screenshot_id = m_next_pending_screenshot_id++;+ screenshot.deadline = Core::Timer::create_single_shot(SCREENSHOT_VIDEO_SINK_LIMIT, [this, screenshot_id] {+ paint_pending_screenshot(screenshot_id);+ });+ screenshot.deadline->start();+ m_pending_screenshots.set(screenshot_id, move(screenshot));+ paint_screenshots_whose_sinks_have_caught_up();+}++// The screenshot draws the video sinks of its context and of the contexts nested in it, which can change while it waits.+// Each sink is caught up once, as a sink that isn't ticking falls behind its clock again as soon as it plays on.+void CompositorState::catch_up_newly_drawn_screenshot_sinks(PendingScreenshot& screenshot)+{+ for (auto& sink : screenshot.sinks)+ sink.is_drawn = false;+ HashMap<Web::CompositorContextId, Vector<Web::CompositorContextId>> children;+ for (auto const& [child_id, _] : m_presented_contexts) {+ if (auto parent_context_id = m_core.parent_context(child_id); parent_context_id.has_value())+ children.ensure(*parent_context_id).append(child_id);+ }+ HashTable<Web::CompositorContextId> visited;+ Vector<Web::CompositorContextId> to_visit { screenshot.context_id };+ while (!to_visit.is_empty()) {+ auto id = to_visit.take_last();+ if (visited.set(id) != HashSetResult::InsertedNewEntry)+ continue;+ auto* context = presented_context_if_present(id);+ if (!context)+ continue;+ for (auto handle : context->raster_targets.drawn_video_sinks()) {+ auto client_id = context->web_content_client.web_content_client_id();+ auto* sink_state = video_sink_state(context->web_content_client, handle);+ if (!sink_state)+ continue;+ auto index = screenshot.sinks.find_first_index_if([&](auto const& sink) { return sink.client == client_id && sink.handle == handle; });+ if (!index.has_value()) {+ index = screenshot.sinks.size();+ screenshot.sinks.append({ client_id, handle });+ }+ screenshot.sinks[*index].is_drawn = true;+ auto& screenshot_sink = screenshot.sinks[*index];+ // A sink found before its edge attached is caught up once it attaches.+ if (screenshot_sink.was_asked_to_catch_up || !sink_state->sink)+ continue;+ screenshot_sink.was_asked_to_catch_up = true;+ if (!sink_state->sink->frame_is_up_to_date())+ sink_state->sink->catch_up_to_clock();+ }+ if (auto child_ids = children.find(id); child_ids != children.end())+ to_visit.extend(child_ids->value);+ }+}++CompositorState::VideoSinkState* CompositorState::screenshot_sink_state(ScreenshotSink const& sink)+{+ auto* client = web_content_client_if_present(sink.client);+ if (!client)+ return nullptr;+ return video_sink_state(*client, sink.handle);+}++bool CompositorState::screenshot_sinks_have_caught_up(PendingScreenshot const& screenshot)+{+ return all_of(screenshot.sinks, [&](auto const& sink) {+ if (!sink.is_drawn)+ return true;+ // A sink without an edge, or one whose input has yet to start, has no frame to catch up.+ auto* sink_state = screenshot_sink_state(sink);+ return !sink_state || !sink_state->sink || !sink_state->sink->is_catching_up();+ });+}++// Painting may update the sinks, so it waits until whatever found them caught up is done with them.+void CompositorState::paint_screenshots_whose_sinks_have_caught_up()+{+ if (m_pending_screenshots.is_empty() || m_screenshot_check_is_scheduled)+ return;+ m_screenshot_check_is_scheduled = true;+ Core::deferred_invoke([self = NonnullRefPtr(*this)] {+ self->m_screenshot_check_is_scheduled = false;+ Vector<u64> screenshots_to_paint;+ for (auto& [screenshot_id, screenshot] : self->m_pending_screenshots) {+ self->catch_up_newly_drawn_screenshot_sinks(screenshot);+ if (self->screenshot_sinks_have_caught_up(screenshot))+ screenshots_to_paint.append(screenshot_id);+ }+ for (auto screenshot_id : screenshots_to_paint)+ self->paint_pending_screenshot(screenshot_id);+ });+}++void CompositorState::paint_pending_screenshot(u64 screenshot_id)+{+ auto screenshot = m_pending_screenshots.take(screenshot_id);+ if (!screenshot.has_value())+ return;+ screenshot->deadline->stop();++ auto painted = false;+ if (presented_context_if_present(screenshot->context_id) && screenshot->target_bitmap.is_valid() && screenshot->target_bitmap.bitmap()) {+ auto target_surface = Gfx::PaintingSurface::wrap_bitmap(*screenshot->target_bitmap.bitmap());+ painted = m_core.paint_screenshot(screenshot->context_id, *target_surface);+ }++ if (auto* requester = web_content_client_if_present(screenshot->requester))+ requester->tell_screenshot_result(screenshot->request_id, painted);}// How long a screenshot waits for the processes that paint its context's descendants. One whose script never yieldsdiff --git a/Services/Compositor/CompositorState.h b/Services/Compositor/CompositorState.hindex 78ebe008c95..4a78bda159f 100644--- a/Services/Compositor/CompositorState.h+++ b/Services/Compositor/CompositorState.h@@ -60,6 +60,9 @@ public:virtual void release_video_edge(Media::VideoSinkHandle) = 0;virtual void video_sink_presented_frame(Media::VideoSinkHandle, RefPtr<Media::VideoFrame>, Media::DisplayingVideoSinkFrameCounts) { }virtual void video_sink_counted_frames(Media::VideoSinkHandle, Media::DisplayingVideoSinkFrameCounts) { }+ virtual void video_sink_frame_freshness_changed(Media::VideoSinkHandle, bool) { }+ virtual void tell_video_sink_is_up_to_date(u64 token) = 0;+ virtual void tell_screenshot_result(Compositing::ScreenshotRequestId, bool painted) = 0;virtual void request_animated_image_frames(AnimatedImage::FrameRequest const&) { }virtual void placeholder_canvas_committed(Compositing::CanvasId, Gfx::IntSize, bool origin_clean) = 0;// The owner of this client's canvases, which are the only ones its contexts may draw.@@ -122,6 +125,7 @@ public:// For a presentation channel that arrives after the sinks did, or that replaces the one their edges were on.void create_video_edges(CompositorStateWebContentClient&);void remove_video_sink(CompositorStateWebContentClient&, Media::VideoSinkHandle);+ void bring_video_sink_up_to_date(CompositorStateWebContentClient&, Media::VideoSinkHandle, u64 token);void on_video_sink_ready(CompositorStateWebContentClient&, Media::VideoSinkHandle, NonnullRefPtr<Media::DisplayingVideoSink> const&);void add_animated_image(CompositorStateWebContentClient&, Compositing::ImageFrameResourceId, AnimatedImage::Description);void remove_animated_image(CompositorStateWebContentClient&, Compositing::ImageFrameResourceId);@@ -150,7 +154,8 @@ public:void hurry_rendering_opportunity(Web::CompositorContextId);// Asks for the next display tick the context's maximum rate lets through, for its render clock.void request_clock_tick(Web::CompositorContextId, double maximum_frames_per_second);- bool request_screenshot(Web::CompositorContextId, Gfx::ShareableBitmap&);+ // Paints once the video sinks that the screenshot draws have frames following their clocks, and tells the client.+ void request_screenshot(CompositorStateWebContentClient&, Web::CompositorContextId, Compositing::ScreenshotRequestId, Gfx::ShareableBitmap);// Has each process that owns a descendant of the context in another process paint it, along with whatever lies below// it, and tells the requester once every one of them has handed over its frames, or gone away.void prepare_remote_descendants_for_screenshot(CompositorStateWebContentClient& requester, Web::CompositorContextId, u64 request_id);@@ -309,9 +314,38 @@ private:struct VideoSinkState {RefPtr<Media::DisplayingVideoSink> sink;bool requires_updates { false };+ bool was_ticking { false };+ bool published_frame_is_up_to_date { false };+ // A client waits for one request at a time, so the request it waits for is the last one it made.+ Optional<u64> up_to_date_request_token;};VideoSinkState* video_sink_state(CompositorStateWebContentClient&, Media::VideoSinkHandle);- void video_sink_ticking_changed(CompositorStateWebContentClient&, Media::VideoSinkHandle);+ void video_sink_freshness_changed(CompositorStateWebContentClient&, Media::VideoSinkHandle);+ void publish_video_sink_freshness(CompositorStateWebContentClient&, Media::VideoSinkHandle, VideoSinkState&);++ struct ScreenshotSink {+ WebContentClientId client;+ Media::VideoSinkHandle handle;+ bool was_asked_to_catch_up { false };+ bool is_drawn { false };+ };+ // A screenshot that waits for the video sinks it draws to catch up to their clocks, ticking or not.+ struct PendingScreenshot {+ WebContentClientId requester;+ Web::CompositorContextId context_id;+ Compositing::ScreenshotRequestId request_id;+ Gfx::ShareableBitmap target_bitmap;+ Vector<ScreenshotSink> sinks;+ RefPtr<Core::Timer> deadline;+ };+ void catch_up_newly_drawn_screenshot_sinks(PendingScreenshot&);+ VideoSinkState* screenshot_sink_state(ScreenshotSink const&);+ bool screenshot_sinks_have_caught_up(PendingScreenshot const&);+ void paint_screenshots_whose_sinks_have_caught_up();+ void paint_pending_screenshot(u64 screenshot_id);+ HashMap<u64, PendingScreenshot> m_pending_screenshots;+ bool m_screenshot_check_is_scheduled { false };+ u64 m_next_pending_screenshot_id { 1 };// The frame that a video sink of the client shows now, which is null for a sink that the client does not have or// that shows none.RefPtr<Media::VideoFrame> current_video_frame(CompositorStateWebContentClient&, Media::VideoSinkHandle);diff --git a/Services/Compositor/CompositorWebContentClient.ipc b/Services/Compositor/CompositorWebContentClient.ipcindex fa4759bbe72..1453da0ef14 100644--- a/Services/Compositor/CompositorWebContentClient.ipc+++ b/Services/Compositor/CompositorWebContentClient.ipc@@ -16,6 +16,7 @@ endpoint CompositorWebContentClient[RustSender] animated_content_moved_under_pointer(Web::CompositorContextId context_id, i64 frame_time_nanoseconds) =|[RustSender] overlay_scrollbar_visibilities_changed(Vector<Web::OverlayScrollbarVisibility> visibilities) =|did_complete_screenshot(Compositing::ScreenshotRequestId request_id) =|+ video_sink_is_up_to_date(u64 token) =|did_fail_screenshot(Compositing::ScreenshotRequestId request_id) =|paint_contexts_for_screenshot(u64 preparation_id, Vector<Web::CompositorContextId> context_ids) =|remote_descendants_prepared_for_screenshot(u64 request_id) =|diff --git a/Services/Compositor/CompositorWebContentServer.ipc b/Services/Compositor/CompositorWebContentServer.ipcindex e1d68dc72bd..201420f4217 100644--- a/Services/Compositor/CompositorWebContentServer.ipc+++ b/Services/Compositor/CompositorWebContentServer.ipc@@ -22,6 +22,8 @@ endpoint CompositorWebContentServeradd_video_sink(Media::VideoSinkHandle video_sink_handle, NonnullRefPtr<Compositing::VideoFramePresentationPage> presentation_page) =|remove_video_sink(Media::VideoSinkHandle video_sink_handle) =|release_video_frame_hold(Media::VideoSinkHandle video_sink_handle, u64 generation) =|+ // Answered with video_sink_is_up_to_date() once the sink's frame follows its clock, which waits for it to tick.+ bring_video_sink_up_to_date(Media::VideoSinkHandle video_sink_handle, u64 token) =|// A channel to the image decoder of this WebContent, which the frames of its animated images come through.connect_to_image_decoder(IPC::TransportHandle handle) =|diff --git a/Services/Compositor/ConnectionFromWebContent.cpp b/Services/Compositor/ConnectionFromWebContent.cppindex 87d78aacc44..c3429d06678 100644--- a/Services/Compositor/ConnectionFromWebContent.cpp+++ b/Services/Compositor/ConnectionFromWebContent.cpp@@ -165,6 +165,16 @@ void ConnectionFromWebContent::video_sink_counted_frames(Media::VideoSinkHandlem_video_frame_holds.add_frame_counts(video_sink_handle, new_frame_counts);}+void ConnectionFromWebContent::bring_video_sink_up_to_date(Media::VideoSinkHandle video_sink_handle, u64 token)+{+ m_compositor_state->bring_video_sink_up_to_date(*this, video_sink_handle, token);+}++void ConnectionFromWebContent::video_sink_frame_freshness_changed(Media::VideoSinkHandle video_sink_handle, bool frame_is_up_to_date)+{+ m_video_frame_holds.set_frame_is_up_to_date(video_sink_handle, frame_is_up_to_date);+}+void ConnectionFromWebContent::create_video_edge(Media::VideoSinkHandle video_sink_handle){if (!m_video_presentation_connection)@@ -377,10 +387,7 @@ void ConnectionFromWebContent::request_screenshot(Web::CompositorContextId conte{if (!context_is_owned_by_this_connection(context_id))return;- if (m_compositor_state->request_screenshot(context_id, target_bitmap))- async_did_complete_screenshot(request_id);- else- async_did_fail_screenshot(request_id);+ m_compositor_state->request_screenshot(*this, context_id, request_id, move(target_bitmap));}}diff --git a/Services/Compositor/ConnectionFromWebContent.h b/Services/Compositor/ConnectionFromWebContent.hindex d554e84814f..b20073178f8 100644--- a/Services/Compositor/ConnectionFromWebContent.h+++ b/Services/Compositor/ConnectionFromWebContent.h@@ -54,6 +54,7 @@ private:virtual void add_video_sink(Media::VideoSinkHandle, NonnullRefPtr<Compositing::VideoFramePresentationPage>) override;virtual void remove_video_sink(Media::VideoSinkHandle) override;virtual void release_video_frame_hold(Media::VideoSinkHandle, u64 generation) override;+ virtual void bring_video_sink_up_to_date(Media::VideoSinkHandle, u64 token) override;virtual void set_parent_context(Web::CompositorContextId, Optional<Web::CompositorContextId>) override;virtual void stop_presenting_to_client(Web::CompositorContextId) override;virtual void destroy_context(Web::CompositorContextId) override;@@ -93,6 +94,15 @@ private:virtual Compositing::RegisteredImageFrames const& registered_image_frames() const override { return m_registered_image_frames; }virtual void ask_to_paint_contexts_for_screenshot(u64 preparation_id, Vector<Web::CompositorContextId> const& context_ids) override { async_paint_contexts_for_screenshot(preparation_id, context_ids); }virtual void tell_remote_descendants_prepared_for_screenshot(u64 request_id) override { async_remote_descendants_prepared_for_screenshot(request_id); }+ virtual void video_sink_frame_freshness_changed(Media::VideoSinkHandle, bool frame_is_up_to_date) override;+ virtual void tell_video_sink_is_up_to_date(u64 token) override { async_video_sink_is_up_to_date(token); }+ virtual void tell_screenshot_result(Compositing::ScreenshotRequestId request_id, bool painted) override+ {+ if (painted)+ async_did_complete_screenshot(request_id);+ else+ async_did_fail_screenshot(request_id);+ }bool context_is_owned_by_this_connection(Web::CompositorContextId);NonnullRefPtr<CompositorState> m_compositor_state;diff --git a/Services/Compositor/VideoFrameHolds.cpp b/Services/Compositor/VideoFrameHolds.cppindex 373174eee21..b93f8329451 100644--- a/Services/Compositor/VideoFrameHolds.cpp+++ b/Services/Compositor/VideoFrameHolds.cpp@@ -59,6 +59,15 @@ void VideoFrameHolds::present_frame(Media::VideoSinkHandle handle, RefPtr<Media:sink->page->publish_presented_frame(presented_frame);}+void VideoFrameHolds::set_frame_is_up_to_date(Media::VideoSinkHandle handle, bool frame_is_up_to_date)+{+ auto sink = m_sinks.get(handle);+ if (!sink.has_value() || sink->presented_frame.frame_is_up_to_date == frame_is_up_to_date)+ return;+ sink->presented_frame.frame_is_up_to_date = frame_is_up_to_date;+ sink->page->publish_presented_frame(sink->presented_frame);+}+void VideoFrameHolds::add_frame_counts(Media::VideoSinkHandle handle, Media::DisplayingVideoSinkFrameCounts new_frame_counts){auto sink = m_sinks.get(handle);diff --git a/Services/Compositor/VideoFrameHolds.h b/Services/Compositor/VideoFrameHolds.hindex 92492dd00e3..e5827dcedd8 100644--- a/Services/Compositor/VideoFrameHolds.h+++ b/Services/Compositor/VideoFrameHolds.h@@ -27,6 +27,7 @@ public:void present_frame(Media::VideoSinkHandle, RefPtr<Media::VideoFrame>, Media::DisplayingVideoSinkFrameCounts new_frame_counts);void add_frame_counts(Media::VideoSinkHandle, Media::DisplayingVideoSinkFrameCounts new_frame_counts);+ void set_frame_is_up_to_date(Media::VideoSinkHandle, bool);ErrorOr<void> release_hold(Media::VideoSinkHandle, u64 generation);RefPtr<Media::VideoFrame> held_frame(Media::VideoSinkHandle, u64 generation) const;diff --git a/Tests/LibMedia/TestDisplayingVideoSink.cpp b/Tests/LibMedia/TestDisplayingVideoSink.cppindex a4543014c6b..10449b855b6 100644--- a/Tests/LibMedia/TestDisplayingVideoSink.cpp+++ b/Tests/LibMedia/TestDisplayingVideoSink.cpp@@ -659,3 +659,146 @@ TEST_CASE(updates_are_required_until_the_last_frame_finishes_presenting)clock->seek(AK::Duration::from_milliseconds(1200));EXPECT(!sink->update(MonotonicTime::now()).may_require_updates);}++TEST_CASE(frame_is_up_to_date_once_a_ticking_sink_has_caught_up)+{+ never_destroyed_event_loop();++ auto pool = MUST(Media::VideoFramePool::create());+ auto clock = MUST(Media::MonotonicMediaClock::try_create());+ clock->seek(AK::Duration::from_milliseconds(1000));+ auto sink = MUST(Media::DisplayingVideoSink::try_create(clock->time_reader()));+ auto producer = ScriptedVideoProducer::create();+ MUST(sink->connect_input(producer));++ // A sink that has yet to update has yet to bring its frame to the clock.+ EXPECT(!sink->frame_is_up_to_date());+ producer->append_frame(create_test_frame(*pool, AK::Duration::from_milliseconds(1000), AK::Duration::from_milliseconds(40)));+ (void)sink->update(MonotonicTime::now());+ EXPECT(sink->frame_is_up_to_date());++ // A seek from upstream leaves the frame from before it, which is up to date until the seek resolves.+ sink->seek(AK::Duration::from_milliseconds(3000));+ EXPECT(sink->frame_is_up_to_date());+ producer->append_frame(create_test_frame(*pool, AK::Duration::from_milliseconds(3000), AK::Duration::from_milliseconds(40)));+ clock->seek(AK::Duration::from_milliseconds(3000));+ (void)sink->update(MonotonicTime::now());+ EXPECT(sink->frame_is_up_to_date());++ sink->set_ticking(false);+ EXPECT(!sink->frame_is_up_to_date());++ // Catching up to a clock that moved while the sink wasn't ticking takes a seek of the sink's own.+ clock->seek(AK::Duration::from_milliseconds(5000));+ sink->set_ticking(true);+ (void)sink->update(MonotonicTime::now());+ EXPECT(!sink->frame_is_up_to_date());+ producer->append_frame(create_test_frame(*pool, AK::Duration::from_milliseconds(5000), AK::Duration::from_milliseconds(40)));+ (void)sink->update(MonotonicTime::now());+ EXPECT(sink->frame_is_up_to_date());+ EXPECT_EQ(sink->current_frame()->timestamp(), AK::Duration::from_milliseconds(5000));++ // A clock that stays within the frame needs no catching up.+ sink->set_ticking(false);+ sink->set_ticking(true);+ (void)sink->update(MonotonicTime::now());+ EXPECT(sink->frame_is_up_to_date());+}++// A screenshot catches a sink up to its clock without ticking it.+TEST_CASE(unticked_sink_catches_up_to_its_clock_on_request)+{+ auto& loop = never_destroyed_event_loop();++ auto pool = MUST(Media::VideoFramePool::create());+ auto clock = MUST(Media::MonotonicMediaClock::try_create());+ auto sink = MUST(Media::DisplayingVideoSink::try_create(clock->time_reader()));+ auto producer = ScriptedVideoProducer::create();+ MUST(sink->connect_input(producer));+ sink->set_ticking(false);+ producer->append_output(nullptr, Media::PipelineStatus::Suspended);+ producer->wake();+ loop.pump(Core::EventLoop::WaitMode::PollForEvents);++ // Paused at a time the sink has no frame for, nothing but a request makes it seek.+ clock->seek(AK::Duration::from_milliseconds(2000));+ (void)sink->update(MonotonicTime::now());+ auto seeks_before_catching_up = producer->seek_count();++ sink->catch_up_to_clock();+ EXPECT_EQ(producer->seek_count(), seeks_before_catching_up + 1);+ EXPECT(sink->is_catching_up());++ producer->consume();+ producer->append_frame(create_test_frame(*pool, AK::Duration::from_milliseconds(2000), AK::Duration::from_milliseconds(40)));+ producer->wake();+ loop.pump(Core::EventLoop::WaitMode::PollForEvents);+ EXPECT(!sink->is_catching_up());+ EXPECT_EQ(sink->current_frame()->timestamp(), AK::Duration::from_milliseconds(2000));+ EXPECT(!sink->frame_is_up_to_date());++ // A frame that already shows the clock's time needs no seek.+ sink->catch_up_to_clock();+ EXPECT_EQ(producer->seek_count(), seeks_before_catching_up + 1);+ EXPECT(!sink->is_catching_up());+}++TEST_CASE(sink_reports_changes_to_its_freshness)+{+ auto& loop = never_destroyed_event_loop();++ auto pool = MUST(Media::VideoFramePool::create());+ auto clock = MUST(Media::MonotonicMediaClock::try_create());+ auto sink = MUST(Media::DisplayingVideoSink::try_create(clock->time_reader()));+ size_t changes = 0;+ sink->set_on_freshness_changed([&] { changes++; });+ auto producer = ScriptedVideoProducer::create();+ MUST(sink->connect_input(producer));++ sink->set_ticking(false);+ EXPECT_EQ(changes, 1u);++ // Ticking starts a catch-up, and the frame is up to date once that is done.+ clock->seek(AK::Duration::from_milliseconds(1000));+ sink->set_ticking(true);+ EXPECT_EQ(changes, 2u);+ EXPECT(sink->is_catching_up());+ producer->append_frame(create_test_frame(*pool, AK::Duration::from_milliseconds(1000), AK::Duration::from_milliseconds(40)));+ producer->wake();+ loop.pump(Core::EventLoop::WaitMode::PollForEvents);+ EXPECT(sink->frame_is_up_to_date());+ EXPECT_EQ(changes, 3u);++ sink->set_ticking(true);+ EXPECT_EQ(changes, 3u);+ sink->set_ticking(false);+ EXPECT_EQ(changes, 4u);+}++// Data that has yet to arrive holds a catch-up up indefinitely, so the frame from before it counts as up to date.+TEST_CASE(catch_up_that_waits_for_data_leaves_the_frame_up_to_date)+{+ auto& loop = never_destroyed_event_loop();++ auto pool = MUST(Media::VideoFramePool::create());+ auto clock = MUST(Media::MonotonicMediaClock::try_create());+ auto sink = MUST(Media::DisplayingVideoSink::try_create(clock->time_reader()));+ auto producer = ScriptedVideoProducer::create();+ MUST(sink->connect_input(producer));+ producer->append_frame(create_test_frame(*pool, AK::Duration::zero(), AK::Duration::from_milliseconds(40)));+ (void)sink->update(MonotonicTime::now());+ EXPECT(sink->frame_is_up_to_date());++ sink->set_ticking(false);+ clock->seek(AK::Duration::from_milliseconds(3000));+ sink->set_ticking(true);+ EXPECT(sink->is_catching_up());+ EXPECT(!sink->frame_is_up_to_date());++ producer->append_output(nullptr, Media::PipelineStatus::Blocked);+ producer->wake();+ loop.pump(Core::EventLoop::WaitMode::PollForEvents);+ EXPECT(!sink->is_catching_up());+ EXPECT(sink->frame_is_up_to_date());+ EXPECT_EQ(sink->current_frame()->timestamp(), AK::Duration::zero());+}