Truly independent web browser
LibWeb+Compositor: Advance animated images in the compositor
Andreas Klingf7fc28e0540f
diff --git a/Libraries/LibWeb/Compositor/CompositorConnection.cpp b/Libraries/LibWeb/Compositor/CompositorConnection.cppindex 7d180a3e814..ea3aba343f6 100644--- a/Libraries/LibWeb/Compositor/CompositorConnection.cpp+++ b/Libraries/LibWeb/Compositor/CompositorConnection.cpp@@ -17,12 +17,14 @@#include <LibGfx/Bitmap.h>#include <LibIPC/Limits.h>#include <LibIPC/Transport.h>+#include <LibIPC/TransportHandle.h>#include <LibMediaClient/Client.h>#include <LibWeb/Compositor/RenderClock.h>#include <LibWeb/HTML/HTMLCanvasElement.h>#include <LibWeb/HTML/LocalNavigable.h>#include <LibWeb/Page/EventHandler.h>#include <LibWeb/Page/Page.h>+#include <LibWeb/Platform/ImageCodecPlugin.h>// The Paint stage presents frames, and only the connection hands it the sink it presents them through, and the// screenshots it asks for after them.@@ -278,6 +280,65 @@ void CompositorConnection::hand_frame_sink_to_paint_thread()paint_stage_adopt_frame_sink(&sink.leak_ref());}+// Gives the compositor a connection of its own to this process's image decoder, so that an animated image keeps getting+// frames while the main thread is busy.+void CompositorConnection::ensure_image_decoder_channel()+{+ auto& image_codec = Platform::ImageCodecPlugin::the();+ if (m_image_decoder_channel_client_generation == image_codec.client_generation())+ return;++ auto channel_or_error = IPC::TransportHandle::create_pair();+ if (channel_or_error.is_error()) {+ dbgln("Failed to create an image decoder channel for the Compositor: {}", channel_or_error.error());+ return;+ }+ auto channel = channel_or_error.release_value();+ image_codec.connect_frame_client(move(channel.first));+ async_connect_to_image_decoder(channel.second);+ m_image_decoder_channel_client_generation = image_codec.client_generation();+}++void CompositorConnection::add_animated_image(u64 frame_id, AnimatedImageRegistration const& image)+{+ if (!can_send_message_to_compositor())+ return;+ ensure_image_decoder_channel();+ // NB: Session ids start over with each decoder, so a session of a replaced decoder could name one of another image.+ auto session_id = image.image_decoder_client_generation == Platform::ImageCodecPlugin::the().client_generation() ? image.session_id : 0;+ async_add_animated_image(frame_id, session_id, image.size, image.color_space, image.frame_durations_in_milliseconds, image.loop_count);+}++void CompositorConnection::remove_animated_image(u64 frame_id)+{+ if (can_send_message_to_compositor())+ async_remove_animated_image(frame_id);+}++void CompositorConnection::start_animated_image(u64 frame_id)+{+ if (can_send_message_to_compositor())+ async_start_animated_image(frame_id);+}++void CompositorConnection::stop_animated_image(u64 frame_id)+{+ if (can_send_message_to_compositor())+ async_stop_animated_image(frame_id);+}++AnimatedImageState CompositorConnection::animated_image_state_for_testing(u64 frame_id)+{+ if (!can_send_message_to_compositor())+ return {};+ auto response = send_sync_but_allow_failure<Messages::CompositorWebContentServer::AnimatedImageStateForTesting>(frame_id);+ if (!response) {+ did_lose_compositor();+ return {};+ }+ return { .is_animating = response->is_animating(), .frame_index = response->frame_index(), .shown_frame_index = response->shown_frame_index(), .loops_completed = response->loops_completed() };+}+void CompositorConnection::add_video_sink(Media::VideoSinkHandle video_sink_handle, NonnullRefPtr<Compositing::VideoFramePresentationPage> presentation_page){if (!can_send_message_to_compositor())diff --git a/Libraries/LibWeb/Compositor/CompositorConnection.h b/Libraries/LibWeb/Compositor/CompositorConnection.hindex 9ca5b673753..0e901fc8b59 100644--- a/Libraries/LibWeb/Compositor/CompositorConnection.h+++ b/Libraries/LibWeb/Compositor/CompositorConnection.h@@ -51,6 +51,11 @@ public:void destroy_context(Web::CompositorContextId);// Has the Paint thread present frames through this connection from now on.void hand_frame_sink_to_paint_thread();+ void add_animated_image(u64 frame_id, AnimatedImageRegistration const&);+ void remove_animated_image(u64 frame_id);+ void start_animated_image(u64 frame_id);+ void stop_animated_image(u64 frame_id);+ AnimatedImageState animated_image_state_for_testing(u64 frame_id);void add_video_sink(Media::VideoSinkHandle, NonnullRefPtr<Compositing::VideoFramePresentationPage>);void remove_video_sink(Media::VideoSinkHandle);void release_video_frame_hold(Media::VideoSinkHandle, u64 generation);@@ -93,6 +98,7 @@ public:bool read_webgl_buffer_sub_data(Compositing::CanvasId, Compositing::WebGL::GLenum target, Compositing::WebGL::GLintptr offset, Compositing::WebGL::GLintptr size, Core::AnonymousBuffer const& data);void ensure_video_presentation_channel();+ void ensure_image_decoder_channel();// Takes up the render clock channel the Browser made between this process and the Compositor, which delivers// display ticks over it from then on.void attach_render_clock(IPC::TransportHandle);@@ -142,6 +148,7 @@ private: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;+ Optional<u64> m_image_decoder_channel_client_generation;};}diff --git a/Libraries/LibWeb/Compositor/CompositorHost.cpp b/Libraries/LibWeb/Compositor/CompositorHost.cppindex f6584f4f58f..60efe96ea9e 100644--- a/Libraries/LibWeb/Compositor/CompositorHost.cpp+++ b/Libraries/LibWeb/Compositor/CompositorHost.cpp@@ -430,6 +430,53 @@ void CompositorHost::stop_presenting_to_client(Web::CompositorContextId context_connection->stop_presenting_to_client(context_id);}+void CompositorHost::add_animated_image(u64 frame_id, AnimatedImageRegistration image)+{+ if (auto* connection = compositor_connection())+ connection->add_animated_image(frame_id, image);+ m_animated_images.set(frame_id, move(image));+}++void CompositorHost::remove_animated_image(u64 frame_id)+{+ m_animated_images.remove(frame_id);+ if (auto* connection = compositor_connection())+ connection->remove_animated_image(frame_id);+}++void CompositorHost::start_animated_image(u64 frame_id)+{+ m_animated_images.get(frame_id)->is_started = true;+ if (auto* connection = compositor_connection())+ connection->start_animated_image(frame_id);+}++void CompositorHost::stop_animated_image(u64 frame_id)+{+ m_animated_images.get(frame_id)->is_started = false;+ if (auto* connection = compositor_connection())+ connection->stop_animated_image(frame_id);+}++AnimatedImageState CompositorHost::animated_image_state_for_testing(u64 frame_id) const+{+ if (auto* connection = compositor_connection())+ return connection->animated_image_state_for_testing(frame_id);+ return {};+}++void CompositorHost::register_animated_images_with_new_compositor()+{+ auto* connection = compositor_connection();+ if (!connection)+ return;+ for (auto const& [frame_id, image] : m_animated_images) {+ connection->add_animated_image(frame_id, image);+ if (image.is_started)+ connection->start_animated_image(frame_id);+ }+}+void CompositorHost::add_video_sink(Media::VideoSinkHandle video_sink_handle, NonnullRefPtr<Compositing::VideoFramePresentationPage> presentation_page){if (auto* connection = compositor_connection())diff --git a/Libraries/LibWeb/Compositor/CompositorHost.h b/Libraries/LibWeb/Compositor/CompositorHost.hindex 78fd63cc705..bdfcd59cccf 100644--- a/Libraries/LibWeb/Compositor/CompositorHost.h+++ b/Libraries/LibWeb/Compositor/CompositorHost.h@@ -7,16 +7,20 @@#pragma once#include <AK/Function.h>+#include <AK/HashMap.h>#include <AK/Noncopyable.h>#include <AK/NonnullRefPtr.h>#include <AK/Optional.h>#include <AK/OwnPtr.h>#include <AK/Types.h>+#include <AK/Vector.h>+#include <AK/Weakable.h>#include <LibCompositing/DisplayList/DisplayListResourceStorage.h>#include <LibCompositing/Scrolling/AsyncScrollTree.h>#include <LibCompositing/Types.h>#include <LibCompositing/Video/VideoFrameHold.h>#include <LibGfx/Bitmap.h>+#include <LibGfx/ColorSpace.h>#include <LibGfx/Point.h>#include <LibGfx/Rect.h>#include <LibGfx/Size.h>@@ -49,6 +53,25 @@ struct PlaceholderCanvasPixels {bool origin_clean { true };};+// What the compositor needs to animate an image: it asks the decoder's session for the frames.+struct AnimatedImageRegistration {+ i64 session_id { 0 };+ Gfx::IntSize size;+ Gfx::ColorSpace color_space;+ Vector<u32> frame_durations_in_milliseconds;+ u32 loop_count { 0 };+ // The decoder the session belongs to, which may be gone by the time a new compositor hears of the image.+ u64 image_decoder_client_generation { 0 };+ bool is_started { false };+};++struct AnimatedImageState {+ bool is_animating { false };+ u32 frame_index { 0 };+ u32 shown_frame_index { 0 };+ u32 loops_completed { 0 };+};+class WEB_API CompositorContextHandle {AK_MAKE_NONCOPYABLE(CompositorContextHandle);AK_MAKE_NONMOVABLE(CompositorContextHandle);@@ -91,7 +114,7 @@ private:Web::CompositorContextId m_context_id;};-class WEB_API CompositorHost {+class WEB_API CompositorHost : public Weakable<CompositorHost> {AK_MAKE_NONCOPYABLE(CompositorHost);AK_MAKE_NONMOVABLE(CompositorHost);@@ -122,6 +145,15 @@ public:void set_parent_context(Web::CompositorContextId, Optional<Web::CompositorContextId>);void stop_presenting_to_client(Web::CompositorContextId);+ // Has the compositor show the frames of an animated image under the image frame with the id.+ void add_animated_image(u64 frame_id, AnimatedImageRegistration);+ void remove_animated_image(u64 frame_id);+ void start_animated_image(u64 frame_id);+ void stop_animated_image(u64 frame_id);+ AnimatedImageState animated_image_state_for_testing(u64 frame_id) const;+ // A new compositor process has heard of none of the images.+ void register_animated_images_with_new_compositor();+void add_video_sink(Media::VideoSinkHandle, NonnullRefPtr<Compositing::VideoFramePresentationPage>);void remove_video_sink(Media::VideoSinkHandle);void set_video_sink_ticking(Media::VideoSinkHandle, bool should_tick);@@ -153,6 +185,8 @@ protected:private:friend class CompositorContextHandle;+ HashMap<u64, AnimatedImageRegistration> m_animated_images;+// Drains the stream, but only when the message can actually be delivered.void send_canvas_2d_stream(Compositing::Canvas2DCommandStream&);diff --git a/Libraries/LibWeb/HTML/AnimatedBitmapDecodedImageData.cpp b/Libraries/LibWeb/HTML/AnimatedBitmapDecodedImageData.cppindex 559d682a153..df868ee6cde 100644--- a/Libraries/LibWeb/HTML/AnimatedBitmapDecodedImageData.cpp+++ b/Libraries/LibWeb/HTML/AnimatedBitmapDecodedImageData.cpp@@ -4,85 +4,52 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <AK/NeverDestroyed.h>#include <LibGC/Heap.h>#include <LibGfx/Bitmap.h>#include <LibJS/Runtime/ExternalMemory.h>#include <LibJS/Runtime/VM.h>#include <LibWeb/CSS/ComputedValues.h>+#include <LibWeb/Compositor/CompositorHost.h>+#include <LibWeb/DOM/Document.h>#include <LibWeb/DOM/DocumentObserver.h>#include <LibWeb/HTML/AnimatedBitmapDecodedImageData.h>+#include <LibWeb/Page/Page.h>+#include <LibWeb/Painting/ImagePaint.h>#include <LibWeb/Platform/ImageCodecPlugin.h>-#include <LibWeb/Platform/Timer.h>namespace Web::HTML {GC_DEFINE_ALLOCATOR(AnimatedBitmapDecodedImageData);-HashMap<i64, GC::RawPtr<AnimatedBitmapDecodedImageData>>& AnimatedBitmapDecodedImageData::session_registry()-{- static NeverDestroyed<HashMap<i64, GC::RawPtr<AnimatedBitmapDecodedImageData>>> registry;- return *registry;-}--void AnimatedBitmapDecodedImageData::install_frame_delivery_callback()-{- static bool s_installed = false;- if (s_installed)- return;- s_installed = true;-- Platform::ImageCodecPlugin::the().on_animation_frames_decoded = [](i64 session_id, Vector<NonnullRefPtr<Gfx::Bitmap>> bitmaps) {- deliver_frames_for_session(session_id, move(bitmaps));- };- Platform::ImageCodecPlugin::the().on_animation_decode_failed = [](i64 session_id) {- auto it = session_registry().find(session_id);- if (it != session_registry().end()) {- if (auto data = it->value)- data->m_request_in_flight = false;- }- };-}--void AnimatedBitmapDecodedImageData::deliver_frames_for_session(i64 session_id, Vector<NonnullRefPtr<Gfx::Bitmap>> bitmaps)-{- auto it = session_registry().find(session_id);- if (it == session_registry().end())- return;- if (auto data = it->value)- data->receive_frames(move(bitmaps), data->m_last_requested_start_frame);-}-GC::Ref<AnimatedBitmapDecodedImageData> AnimatedBitmapDecodedImageData::create(DOM::Document& document,i64 session_id,- u32 frame_count,u32 loop_count,- Gfx::IntSize size,Gfx::ColorSpace color_space,Vector<u32> durations,- Vector<NonnullRefPtr<Gfx::Bitmap>> initial_bitmaps)+ NonnullRefPtr<Gfx::Bitmap> first_bitmap){- auto animation_timer = Platform::Timer::create(GC::Heap::the());auto document_observer = GC::Heap::the().allocate<DOM::DocumentObserver>(document);-+ auto size = first_bitmap->size();auto data = GC::Heap::the().allocate<AnimatedBitmapDecodedImageData>(- session_id, frame_count, loop_count, size, move(color_space), move(durations), animation_timer, document_observer);-- // Place initial bitmaps into the buffer pool.- for (u32 i = 0; i < initial_bitmaps.size(); ++i) {- auto& slot = data->m_buffer_slots[i % BUFFER_POOL_SIZE];- slot.frame_index = i;- slot.frame = Gfx::DecodedImageFrame { *initial_bitmaps[i], data->m_color_space };- slot.generation = ++data->m_write_generation;+ session_id, durations.size(), loop_count, Gfx::DecodedImageFrame { *first_bitmap, color_space }, document_observer);++ data->m_image_decoder_client_generation = Platform::ImageCodecPlugin::the().client_generation();++ auto& page = document.page();+ page.ensure_compositor_host();+ if (page.has_compositor_host()) {+ auto& compositor_host = page.compositor_host();+ compositor_host.add_animated_image(data->m_first_frame.id(), {+ .session_id = session_id,+ .size = size,+ .color_space = move(color_space),+ .frame_durations_in_milliseconds = move(durations),+ .loop_count = loop_count,+ .image_decoder_client_generation = data->m_image_decoder_client_generation,+ });+ data->m_compositor_host = compositor_host.make_weak_ptr<Compositor::CompositorHost>();}-- if (!initial_bitmaps.is_empty())- data->m_last_displayed_frame = data->m_buffer_slots[0].frame;-- install_frame_delivery_callback();- session_registry().set(session_id, data.ptr());-return data;}@@ -90,234 +57,90 @@ AnimatedBitmapDecodedImageData::AnimatedBitmapDecodedImageData(i64 session_id,u32 frame_count,u32 loop_count,- Gfx::IntSize size,- Gfx::ColorSpace color_space,- Vector<u32> durations,- GC::Ref<Platform::Timer> animation_timer,+ Gfx::DecodedImageFrame first_frame,GC::Ref<DOM::DocumentObserver> document_observer): AnimatedDecodedImageData(document_observer), m_session_id(session_id), m_frame_count(frame_count), m_loop_count(loop_count)- , m_size(size)- , m_color_space(move(color_space))- , m_durations(move(durations))- , m_animation_timer(animation_timer)+ , m_first_frame(move(first_frame))+ , m_default_frame(m_first_frame.bitmap_ref(), m_first_frame.color_space()){- m_animation_timer->on_timeout = GC::create_function(vm().heap(), [weak_this = GC::Weak { *this }] {- if (auto self = weak_this.ptr())- self->advance_animation();- });}AnimatedBitmapDecodedImageData::~AnimatedBitmapDecodedImageData() = default;-void AnimatedBitmapDecodedImageData::visit_edges(Cell::Visitor& visitor)-{- Base::visit_edges(visitor);- visitor.visit(m_animation_timer);-}-size_t AnimatedBitmapDecodedImageData::external_memory_size() const{- size_t size = JS::vector_external_memory_size(m_durations);- for (auto const& slot : m_buffer_slots) {- if (slot.frame.has_value())- size = JS::saturating_add_external_memory_size(size, slot.frame->bitmap().data_size());- }- return size;+ return m_first_frame.bitmap().data_size();}void AnimatedBitmapDecodedImageData::finalize(){Base::finalize();- m_animation_timer->stop();- session_registry().remove(m_session_id);- Platform::ImageCodecPlugin::the().stop_animation_decode(m_session_id);-}--bool AnimatedBitmapDecodedImageData::animation_has_completed() const-{- return m_loop_count > 0 && m_loops_completed == m_loop_count;-}--void AnimatedBitmapDecodedImageData::reset_animation()-{- m_current_frame_index = 0;- m_loops_completed = 0;- maybe_request_more_frames(m_current_frame_index);- notify_clients_did_update();+ if (m_compositor_host)+ m_compositor_host->remove_animated_image(m_first_frame.id());+ // NB: Session ids start over with each decoder, so a replacement may have given this id to another image.+ auto& image_codec = Platform::ImageCodecPlugin::the();+ if (image_codec.client_generation() == m_image_decoder_client_generation)+ image_codec.stop_animation_decode(m_session_id);}void AnimatedBitmapDecodedImageData::start_animation(){- // NB: We should only ever start the animation when the first client is registered, or when animation restarts, both- // of which should guarantee that we are at the beginning of the animation.- VERIFY(m_current_frame_index == 0 && m_loops_completed == 0);-- m_animation_timer->start(AK::Duration::from_milliseconds(frame_duration(0)));+ if (m_compositor_host)+ m_compositor_host->start_animated_image(m_first_frame.id());}void AnimatedBitmapDecodedImageData::stop_animation(){- m_animation_timer->stop();-}--void AnimatedBitmapDecodedImageData::advance_animation()-{- m_current_frame_index = (m_current_frame_index + 1) % m_frame_count;- maybe_request_more_frames(m_current_frame_index);-- auto current_frame_duration = frame_duration(m_current_frame_index);- if (AK::Duration::from_milliseconds(current_frame_duration) != m_animation_timer->interval())- m_animation_timer->restart(AK::Duration::from_milliseconds(current_frame_duration));-- if (m_current_frame_index == m_frame_count - 1) {- ++m_loops_completed;- if (animation_has_completed())- stop_animation();- }-- notify_clients_did_update();-}--AnimatedBitmapDecodedImageData::BufferSlot const* AnimatedBitmapDecodedImageData::find_slot(u32 frame_index) const-{- for (auto const& slot : m_buffer_slots) {- if (slot.frame_index == frame_index && slot.frame.has_value())- return &slot;- }- return nullptr;+ if (m_compositor_host)+ m_compositor_host->stop_animated_image(m_first_frame.id());}-AnimatedBitmapDecodedImageData::BufferSlot& AnimatedBitmapDecodedImageData::evict_oldest_slot()+Compositor::AnimatedImageState AnimatedBitmapDecodedImageData::state_for_testing() const{- BufferSlot* oldest = &m_buffer_slots[0];- for (auto& slot : m_buffer_slots) {- if (slot.generation < oldest->generation)- oldest = &slot;- }- return *oldest;+ if (m_compositor_host)+ return m_compositor_host->animated_image_state_for_testing(m_first_frame.id());+ return {};}-Optional<Gfx::DecodedImageFrame> AnimatedBitmapDecodedImageData::frame(size_t frame_index, Gfx::IntSize) const-{- if (frame_index >= m_frame_count)- return m_last_displayed_frame;-- if (auto const* slot = find_slot(frame_index)) {- m_last_displayed_frame = slot->frame;- return slot->frame;- }-- // Frame not in pool; return last displayed frame as fallback.- return m_last_displayed_frame;-}--Optional<Gfx::DecodedImageFrame> AnimatedBitmapDecodedImageData::default_frame(Gfx::IntSize size) const+Optional<Gfx::DecodedImageFrame> AnimatedBitmapDecodedImageData::default_frame(Gfx::IntSize) const{// FIXME: This should account for if the file specifies a default frame other than the first frame e.g. the// "static image" in APNG or the "primary image item" in AVIF.- // FIXME: This should bypass the "m_last_displayed_frame" fallback logic and always return the correct default frame- return frame(0, size);+ return m_default_frame;}-Optional<Gfx::DecodedImageFrame> AnimatedBitmapDecodedImageData::current_frame(Gfx::IntSize size) const+Optional<Gfx::DecodedImageFrame> AnimatedBitmapDecodedImageData::current_frame(Gfx::IntSize) const{- return frame(m_current_frame_index, size);+ return m_first_frame;}Optional<Gfx::Color> AnimatedBitmapDecodedImageData::color_if_single_pixel_bitmap() const{- auto frame = current_frame();- if (!frame.has_value())- return {};- auto const& bitmap = frame->bitmap();- if (bitmap.width() != 1 || bitmap.height() != 1)- return {};- return bitmap.get_pixel(0, 0);-}--int AnimatedBitmapDecodedImageData::frame_duration(size_t frame_index) const-{- if (frame_index >= m_durations.size())- return 0;- return m_durations[frame_index];+ // NB: The compositor moves through the frames, so the first frame's color says nothing about the others.+ return {};}Optional<CSSPixels> AnimatedBitmapDecodedImageData::intrinsic_width() const{- return m_size.width();+ return m_first_frame.width();}Optional<CSSPixels> AnimatedBitmapDecodedImageData::intrinsic_height() const{- return m_size.height();+ return m_first_frame.height();}Optional<CSSPixelFraction> AnimatedBitmapDecodedImageData::intrinsic_aspect_ratio() const{- return CSSPixels(m_size.width()) / CSSPixels(m_size.height());+ return CSSPixels(m_first_frame.width()) / CSSPixels(m_first_frame.height());}Optional<Painting::ImagePaint> AnimatedBitmapDecodedImageData::image_paint(Painting::ImagePaintRequest const&) const{- auto decoded_frame = current_frame();- if (!decoded_frame.has_value())- return {};- return Painting::ImagePaint { Painting::ImagePaint::DecodedFrame { .frame = *decoded_frame, .natural_size = m_size } };-}--void AnimatedBitmapDecodedImageData::receive_frames(Vector<NonnullRefPtr<Gfx::Bitmap>> bitmaps, u32 start_frame_index)-{- m_request_in_flight = false;-- for (u32 i = 0; i < bitmaps.size(); ++i) {- u32 frame_index = start_frame_index + i;- if (frame_index >= m_frame_count)- break;-- // Check if this frame is already in the pool.- if (find_slot(frame_index))- continue;-- auto& slot = evict_oldest_slot();- slot.frame_index = frame_index;- slot.frame = Gfx::DecodedImageFrame { *bitmaps[i], m_color_space };- slot.generation = ++m_write_generation;- }-}--void AnimatedBitmapDecodedImageData::maybe_request_more_frames(size_t current_frame_index)-{- if (m_request_in_flight)- return;-- // TODO: Once all `ImageProvider`s are `DecodedImageData::Client`s we can defer loading new frames if we have no- // clients-- // Count how many frames ahead of current are in the pool.- u32 frames_ahead = 0;- for (u32 offset = 1; offset <= BUFFER_POOL_SIZE; ++offset) {- u32 future_index = (current_frame_index + offset) % m_frame_count;- if (find_slot(future_index))- ++frames_ahead;- else- break;- }-- // Request more when buffer is less than half full, giving the decoder- // time to respond while we still have frames to display.- if (frames_ahead >= REQUEST_BATCH_SIZE)- return;-- // Determine which frame to request from.- u32 request_start = (current_frame_index + frames_ahead + 1) % m_frame_count;- u32 request_count = REQUEST_BATCH_SIZE;-- m_request_in_flight = true;- m_last_requested_start_frame = request_start;- Platform::ImageCodecPlugin::the().request_animation_frames(m_session_id, request_start, request_count);+ return Painting::ImagePaint { Painting::ImagePaint::DecodedFrame { .frame = m_first_frame, .natural_size = m_first_frame.size() } };}}diff --git a/Libraries/LibWeb/HTML/AnimatedBitmapDecodedImageData.h b/Libraries/LibWeb/HTML/AnimatedBitmapDecodedImageData.hindex 01bcdcd800b..ce1808689b0 100644--- a/Libraries/LibWeb/HTML/AnimatedBitmapDecodedImageData.h+++ b/Libraries/LibWeb/HTML/AnimatedBitmapDecodedImageData.h@@ -6,17 +6,18 @@#pragma once-#include <AK/Array.h>-#include <AK/HashMap.h>-#include <LibGC/Ptr.h>+#include <AK/WeakPtr.h>#include <LibGfx/ColorSpace.h>#include <LibGfx/DecodedImageFrame.h>#include <LibGfx/Forward.h>+#include <LibWeb/Compositor/CompositorHost.h>#include <LibWeb/HTML/AnimatedDecodedImageData.h>#include <LibWeb/HTML/DecodedImageData.h>namespace Web::HTML {+// A multi-frame image, which the compositor moves through by itself under the id of the first frame here. The display+// lists draw that frame, so they stay the same as the image advances, and the main thread has no part in it.class AnimatedBitmapDecodedImageData final : public AnimatedDecodedImageData {GC_CELL(AnimatedBitmapDecodedImageData, AnimatedDecodedImageData);GC_DECLARE_ALLOCATOR(AnimatedBitmapDecodedImageData);@@ -26,16 +27,13 @@ public:static GC::Ref<AnimatedBitmapDecodedImageData> create(DOM::Document&,i64 session_id,- u32 frame_count,u32 loop_count,- Gfx::IntSize,Gfx::ColorSpace,Vector<u32> durations,- Vector<NonnullRefPtr<Gfx::Bitmap>> initial_bitmaps);+ NonnullRefPtr<Gfx::Bitmap> first_bitmap);virtual ~AnimatedBitmapDecodedImageData() override;virtual void finalize() override;- virtual void visit_edges(Cell::Visitor&) override;virtual Optional<Gfx::DecodedImageFrame> default_frame(Gfx::IntSize = {}) const override;virtual Optional<Gfx::DecodedImageFrame> current_frame(Gfx::IntSize = {}) const override;@@ -48,66 +46,31 @@ public:virtual Optional<Painting::ImagePaint> image_paint(Painting::ImagePaintRequest const&) const override;- void receive_frames(Vector<NonnullRefPtr<Gfx::Bitmap>>, u32 start_frame_index);-- i64 session_id() const { return m_session_id; }-- static void deliver_frames_for_session(i64 session_id, Vector<NonnullRefPtr<Gfx::Bitmap>>);- static void install_frame_delivery_callback();-private:- static HashMap<i64, GC::RawPtr<AnimatedBitmapDecodedImageData>>& session_registry();-- static constexpr u32 BUFFER_POOL_SIZE = 8;- static constexpr u32 REQUEST_BATCH_SIZE = 4;-- struct BufferSlot {- Optional<u32> frame_index;- Optional<Gfx::DecodedImageFrame> frame;- u64 generation { 0 };- };-AnimatedBitmapDecodedImageData(i64 session_id,u32 frame_count,u32 loop_count,- Gfx::IntSize,- Gfx::ColorSpace,- Vector<u32> durations,- GC::Ref<Platform::Timer>,+ Gfx::DecodedImageFrame first_frame,GC::Ref<DOM::DocumentObserver>);virtual size_t external_memory_size() const override;- virtual void reset_animation() override;virtual void start_animation() override;virtual void stop_animation() override;- void advance_animation();- bool animation_has_completed() const;-- int frame_duration(size_t frame_index) const;- Optional<Gfx::DecodedImageFrame> frame(size_t frame_index, Gfx::IntSize = {}) const;-- BufferSlot const* find_slot(u32 frame_index) const;- BufferSlot& evict_oldest_slot();- void maybe_request_more_frames(size_t current_frame_index);+ Compositor::AnimatedImageState state_for_testing() const;i64 m_session_id;u32 m_frame_count;u32 m_loop_count;- Gfx::IntSize m_size;- Gfx::ColorSpace m_color_space;- Vector<u32> m_durations;-- Array<BufferSlot, BUFFER_POOL_SIZE> m_buffer_slots;- mutable Optional<Gfx::DecodedImageFrame> m_last_displayed_frame;- u64 m_write_generation { 0 };- bool m_request_in_flight { false };- u32 m_current_frame_index { 0 };- u32 m_last_requested_start_frame { 0 };- u32 m_loops_completed { 0 };- GC::Ref<Platform::Timer> m_animation_timer;+ Gfx::DecodedImageFrame m_first_frame;+ // NB: The compositor replaces the pixels of m_first_frame under its id, so what wants the default image rather than+ // the animation, such as feImage, gets the same pixels under an id of their own.+ Gfx::DecodedImageFrame m_default_frame;+ u64 m_image_decoder_client_generation { 0 };+ // NB: A page with no compositor host, such as that of an SVG image, shows the first frame.+ WeakPtr<Compositor::CompositorHost> m_compositor_host;};}diff --git a/Libraries/LibWeb/HTML/AnimatedDecodedImageData.cpp b/Libraries/LibWeb/HTML/AnimatedDecodedImageData.cppindex 568aec32408..c92bb08a969 100644--- a/Libraries/LibWeb/HTML/AnimatedDecodedImageData.cpp+++ b/Libraries/LibWeb/HTML/AnimatedDecodedImageData.cpp@@ -58,7 +58,6 @@ AnimatedDecodedImageData::AnimatedDecodedImageData(GC::Ref<DOM::DocumentObservervoid AnimatedDecodedImageData::restart_animation(){stop_animation();- reset_animation();start_animation_if_needed();}diff --git a/Libraries/LibWeb/HTML/AnimatedDecodedImageData.h b/Libraries/LibWeb/HTML/AnimatedDecodedImageData.hindex 76f485cb7c9..3173437ee1a 100644--- a/Libraries/LibWeb/HTML/AnimatedDecodedImageData.h+++ b/Libraries/LibWeb/HTML/AnimatedDecodedImageData.h@@ -23,7 +23,6 @@ protected:AnimatedDecodedImageData(GC::Ref<DOM::DocumentObserver>);virtual void start_animation() = 0;- virtual void reset_animation() = 0;virtual void stop_animation() = 0;virtual void on_client_registered() override;diff --git a/Libraries/LibWeb/HTML/SharedResourceRequest.cpp b/Libraries/LibWeb/HTML/SharedResourceRequest.cppindex 1c86e3da83c..c8b526ffe91 100644--- a/Libraries/LibWeb/HTML/SharedResourceRequest.cpp+++ b/Libraries/LibWeb/HTML/SharedResourceRequest.cpp@@ -321,23 +321,13 @@ void SharedResourceRequest::handle_successful_fetch(URL::URL const& url_string,auto handle_successful_bitmap_decode = [strong_this = GC::Root(*this), image_data_is_cors_cross_origin, encoded_data = move(encoded_data)](Web::Platform::DecodedImage& result) mutable -> ErrorOr<void> {if (result.session_id != 0) {// Streaming animated decode: create AnimatedBitmapDecodedImageData.- Vector<NonnullRefPtr<Gfx::Bitmap>> initial_bitmaps;- initial_bitmaps.ensure_capacity(result.frames.size());- for (auto& frame : result.frames)- initial_bitmaps.unchecked_append(*frame.bitmap);-- auto first_bitmap = result.frames.first().bitmap;- auto size = first_bitmap->size();-strong_this->m_image_data = AnimatedBitmapDecodedImageData::create(*strong_this->m_document,result.session_id,- result.frame_count,result.loop_count,- size,move(result.color_space),move(result.all_durations),- move(initial_bitmaps));+ *result.frames.first().bitmap);} else {// Single-shot decode: create BitmapDecodedImageData as before.Vector<BitmapDecodedImageData::Frame> frames;diff --git a/Libraries/LibWeb/Internals/Internals.cpp b/Libraries/LibWeb/Internals/Internals.cppindex f4026f81a43..87cf03e1616 100644--- a/Libraries/LibWeb/Internals/Internals.cpp+++ b/Libraries/LibWeb/Internals/Internals.cpp@@ -3313,11 +3313,13 @@ WebIDL::ExceptionOr<GC::Ref<JS::Object>> Internals::image_animation_state_for_urauto object = JS::Object::create(window().principal_realm(), nullptr);- object->define_direct_property("timerActive"_utf16_fly_string, JS::Value(animated_bitmap_data->m_animation_timer->is_active()), JS::default_attributes);+ auto state = animated_bitmap_data->state_for_testing();+ object->define_direct_property("isAnimating"_utf16_fly_string, JS::Value(state.is_animating), JS::default_attributes);object->define_direct_property("sessionID"_utf16_fly_string, JS::Value(static_cast<double>(animated_bitmap_data->m_session_id)), JS::default_attributes);- object->define_direct_property("frameIndex"_utf16_fly_string, JS::Value(animated_bitmap_data->m_current_frame_index), JS::default_attributes);+ object->define_direct_property("frameIndex"_utf16_fly_string, JS::Value(state.frame_index), JS::default_attributes);+ object->define_direct_property("shownFrameIndex"_utf16_fly_string, JS::Value(state.shown_frame_index), JS::default_attributes);object->define_direct_property("frameCount"_utf16_fly_string, JS::Value(animated_bitmap_data->m_frame_count), JS::default_attributes);- object->define_direct_property("loopsCompleted"_utf16_fly_string, JS::Value(animated_bitmap_data->m_loops_completed), JS::default_attributes);+ object->define_direct_property("loopsCompleted"_utf16_fly_string, JS::Value(state.loops_completed), JS::default_attributes);object->define_direct_property("loopCount"_utf16_fly_string, JS::Value(animated_bitmap_data->m_loop_count), JS::default_attributes);object->define_direct_property("clientCount"_utf16_fly_string, JS::Value(image_data->m_clients.size()), JS::default_attributes);diff --git a/Libraries/LibWeb/Platform/ImageCodecPlugin.h b/Libraries/LibWeb/Platform/ImageCodecPlugin.hindex 002838f443d..f27f02acef6 100644--- a/Libraries/LibWeb/Platform/ImageCodecPlugin.h+++ b/Libraries/LibWeb/Platform/ImageCodecPlugin.h@@ -12,6 +12,7 @@#include <LibCore/Promise.h>#include <LibGfx/ColorSpace.h>#include <LibGfx/Forward.h>+#include <LibIPC/Forward.h>#include <LibWeb/Export.h>namespace Web::Platform {@@ -50,11 +51,13 @@ public:// decoded before and has since discarded.virtual ErrorOr<DecodedFirstFrame> decode_first_frame_synchronously(ReadonlyBytes) = 0;- virtual void request_animation_frames(i64 session_id, u32 start_frame_index, u32 count) = 0;virtual void stop_animation_decode(i64 session_id) = 0;- Function<void(i64 session_id, Vector<NonnullRefPtr<Gfx::Bitmap>>)> on_animation_frames_decoded;- Function<void(i64 session_id)> on_animation_decode_failed;+ // Has the decoder take the other end of the channel as a client that can ask for frames of this client's animation+ // sessions.+ virtual void connect_frame_client(IPC::TransportHandle) = 0;+ // Changes when the decoder is replaced, which takes its sessions and frame clients with it.+ virtual u64 client_generation() const = 0;};}diff --git a/Libraries/LibWeb/Platform/RemoteImageCodecPlugin.cpp b/Libraries/LibWeb/Platform/RemoteImageCodecPlugin.cppindex adacd0fb3c3..01591359727 100644--- a/Libraries/LibWeb/Platform/RemoteImageCodecPlugin.cpp+++ b/Libraries/LibWeb/Platform/RemoteImageCodecPlugin.cpp@@ -6,6 +6,7 @@*/#include <LibGfx/Bitmap.h>+#include <LibIPC/TransportHandle.h>#include <LibImageDecoderClient/Client.h>#include <LibWeb/Platform/RemoteImageCodecPlugin.h>@@ -20,6 +21,7 @@ RemoteImageCodecPlugin::RemoteImageCodecPlugin(NonnullRefPtr<ImageDecoderClient:void RemoteImageCodecPlugin::set_client(NonnullRefPtr<ImageDecoderClient::Client> client){m_client = move(client);+ ++m_client_generation;setup_client_callbacks();}@@ -28,14 +30,6 @@ void RemoteImageCodecPlugin::setup_client_callbacks()m_client->on_death = [this] {m_client = nullptr;};- m_client->on_animation_frames_decoded = [this](i64 session_id, Vector<NonnullRefPtr<Gfx::Bitmap>> bitmaps) {- if (on_animation_frames_decoded)- on_animation_frames_decoded(session_id, move(bitmaps));- };- m_client->on_animation_decode_failed = [this](i64 session_id, String) {- if (on_animation_decode_failed)- on_animation_decode_failed(session_id);- };}RemoteImageCodecPlugin::~RemoteImageCodecPlugin() = default;@@ -85,16 +79,16 @@ ErrorOr<DecodedFirstFrame> RemoteImageCodecPlugin::decode_first_frame_synchronoureturn DecodedFirstFrame { move(result.bitmap), move(result.color_space) };}-void RemoteImageCodecPlugin::request_animation_frames(i64 session_id, u32 start_frame_index, u32 count)+void RemoteImageCodecPlugin::stop_animation_decode(i64 session_id){if (m_client)- m_client->request_animation_frames(session_id, start_frame_index, count);+ m_client->stop_animation_decode(session_id);}-void RemoteImageCodecPlugin::stop_animation_decode(i64 session_id)+void RemoteImageCodecPlugin::connect_frame_client(IPC::TransportHandle handle){if (m_client)- m_client->stop_animation_decode(session_id);+ m_client->async_connect_frame_client(handle);}}diff --git a/Libraries/LibWeb/Platform/RemoteImageCodecPlugin.h b/Libraries/LibWeb/Platform/RemoteImageCodecPlugin.hindex ae1e2a98b33..c4223c95fa7 100644--- a/Libraries/LibWeb/Platform/RemoteImageCodecPlugin.h+++ b/Libraries/LibWeb/Platform/RemoteImageCodecPlugin.h@@ -25,8 +25,9 @@ public:virtual ErrorOr<DecodedFirstFrame> decode_first_frame_synchronously(ReadonlyBytes) override;- virtual void request_animation_frames(i64 session_id, u32 start_frame_index, u32 count) override;virtual void stop_animation_decode(i64 session_id) override;+ virtual void connect_frame_client(IPC::TransportHandle) override;+ virtual u64 client_generation() const override { return m_client_generation; }void set_client(NonnullRefPtr<ImageDecoderClient::Client>);@@ -34,6 +35,7 @@ private:void setup_client_callbacks();RefPtr<ImageDecoderClient::Client> m_client;+ u64 m_client_generation { 0 };};}diff --git a/Services/Compositor/AnimatedImage.cpp b/Services/Compositor/AnimatedImage.cppnew file mode 100644index 00000000000..73d2defae29--- /dev/null+++ b/Services/Compositor/AnimatedImage.cpp@@ -0,0 +1,201 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <AK/Format.h>+#include <Compositor/AnimatedImage.h>+#include <LibGfx/Bitmap.h>++namespace Compositor {++AnimatedImage::AnimatedImage(Description description)+ : m_session_id(description.session_id)+ , m_size(description.size)+ , m_color_space(move(description.color_space))+ , m_frame_durations_in_milliseconds(move(description.frame_durations_in_milliseconds))+ , m_loop_count(description.loop_count)+{+ VERIFY(!m_frame_durations_in_milliseconds.is_empty());+ for (auto& duration : m_frame_durations_in_milliseconds) {+ duration = max(duration, MINIMUM_FRAME_DURATION_IN_MILLISECONDS);+ m_loop_duration_in_milliseconds += duration;+ }+}++void AnimatedImage::start(MonotonicTime now)+{+ // NB: With no decoder to ask for frames, the image stays on the frame it has.+ if (m_session_id == 0)+ return;+ m_start_time = now;+}++void AnimatedImage::stop()+{+ m_start_time.clear();+}++AnimatedImage::TimelinePosition AnimatedImage::position_at(MonotonicTime now) const+{+ VERIFY(m_start_time.has_value());+ auto elapsed_in_milliseconds = static_cast<u64>(max<i64>((now - *m_start_time).to_milliseconds(), 0));++ auto loops_completed = elapsed_in_milliseconds / m_loop_duration_in_milliseconds;+ if (m_loop_count > 0 && loops_completed >= m_loop_count)+ return { .loops_completed = m_loop_count, .frame_index = frame_count() - 1, .frame_end_in_milliseconds = m_loop_duration_in_milliseconds, .has_finished = true };++ auto time_in_loop = elapsed_in_milliseconds % m_loop_duration_in_milliseconds;+ u64 frame_end = 0;+ for (u32 frame_index = 0; frame_index < frame_count(); ++frame_index) {+ frame_end += m_frame_durations_in_milliseconds[frame_index];+ if (time_in_loop < frame_end)+ return { .loops_completed = loops_completed, .frame_index = frame_index, .frame_end_in_milliseconds = frame_end };+ }+ VERIFY_NOT_REACHED();+}++bool AnimatedImage::is_animating(MonotonicTime now) const+{+ return m_start_time.has_value() && !position_at(now).has_finished;+}++u32 AnimatedImage::frame_index_at(MonotonicTime now) const+{+ if (!m_start_time.has_value())+ return m_shown_frame_index;+ return position_at(now).frame_index;+}++u32 AnimatedImage::loops_completed_at(MonotonicTime now) const+{+ if (!m_start_time.has_value())+ return 0;+ return position_at(now).loops_completed;+}++MonotonicTime AnimatedImage::next_frame_time_after(MonotonicTime now) const+{+ auto position = position_at(now);+ auto elapsed_in_milliseconds = position.loops_completed * m_loop_duration_in_milliseconds + position.frame_end_in_milliseconds;+ return *m_start_time + AK::Duration::from_milliseconds(static_cast<i64>(elapsed_in_milliseconds));+}++// How far before the target frame a frame is, going round the loop.+u32 AnimatedImage::frames_behind(u32 frame_index, u32 target_frame_index) const+{+ return (target_frame_index + frame_count() - frame_index) % frame_count();+}++bool AnimatedImage::advance_to(MonotonicTime now)+{+ auto target_frame_index = frame_index_at(now);++ // A decoder that falls behind must not stop the image: take the newest frame that has arrived.+ BufferSlot const* best_slot = nullptr;+ auto fewest_frames_behind = frames_behind(m_shown_frame_index, target_frame_index);+ for (auto const& slot : m_buffer_slots) {+ if (!slot.frame_index.has_value())+ continue;+ auto slot_frames_behind = frames_behind(*slot.frame_index, target_frame_index);+ if (slot_frames_behind < fewest_frames_behind) {+ fewest_frames_behind = slot_frames_behind;+ best_slot = &slot;+ }+ }+ if (!best_slot)+ return false;++ m_shown_frame_index = *best_slot->frame_index;+ m_shown_frame = best_slot->frame;+ return true;+}++Optional<AnimatedImage::FrameRequest> AnimatedImage::take_frame_request(MonotonicTime now)+{+ if (m_request_in_flight || m_session_id == 0)+ return {};++ auto target_frame_index = frame_index_at(now);++ // Count how many frames ahead of the target are in the pool.+ u32 frames_ahead = 0;+ for (u32 offset = 1; offset <= BUFFER_POOL_SIZE; ++offset) {+ if (!find_slot((target_frame_index + offset) % frame_count()))+ break;+ ++frames_ahead;+ }++ // Ask for more when the pool is less than half full, which gives the decoder time to answer while frames remain.+ bool target_frame_is_missing = target_frame_index != m_shown_frame_index && !find_slot(target_frame_index);+ if (frames_ahead >= REQUEST_BATCH_SIZE && !target_frame_is_missing)+ return {};++ m_requested_start_frame_index = target_frame_is_missing ? target_frame_index : (target_frame_index + frames_ahead + 1) % frame_count();+ m_request_in_flight = true;+ return FrameRequest { .session_id = m_session_id, .start_frame_index = m_requested_start_frame_index, .count = REQUEST_BATCH_SIZE };+}++AnimatedImage::BufferSlot const* AnimatedImage::find_slot(u32 frame_index) const+{+ for (auto const& slot : m_buffer_slots) {+ if (slot.frame_index == frame_index)+ return &slot;+ }+ return nullptr;+}++AnimatedImage::BufferSlot& AnimatedImage::evict_oldest_slot()+{+ BufferSlot* oldest = &m_buffer_slots[0];+ for (auto& slot : m_buffer_slots) {+ if (slot.generation < oldest->generation)+ oldest = &slot;+ }+ return *oldest;+}++bool AnimatedImage::receive_frames(Vector<NonnullRefPtr<Gfx::Bitmap>> bitmaps)+{+ m_request_in_flight = false;++ bool received_new_frame = false;+ for (u32 i = 0; i < bitmaps.size(); ++i) {+ u32 frame_index = m_requested_start_frame_index + i;+ if (frame_index >= frame_count())+ break;++ // NB: The decoder parses untrusted data, so what it sends is checked rather than trusted.+ if (bitmaps[i]->size() != m_size) {+ dbgln("Compositor: Dropping an animated image frame of the wrong size");+ continue;+ }++ if (find_slot(frame_index))+ continue;++ auto& slot = evict_oldest_slot();+ slot.frame_index = frame_index;+ slot.frame = Gfx::DecodedImageFrame { *bitmaps[i], m_color_space };+ slot.generation = ++m_write_generation;+ received_new_frame = true;+ }+ return received_new_frame;+}++void AnimatedImage::decoding_failed()+{+ m_request_in_flight = false;+}++void AnimatedImage::lose_decoder()+{+ m_session_id = 0;+ m_request_in_flight = false;+ stop();+ for (auto& slot : m_buffer_slots)+ slot = {};+}++}diff --git a/Services/Compositor/AnimatedImage.h b/Services/Compositor/AnimatedImage.hnew file mode 100644index 00000000000..31f61ed910d--- /dev/null+++ b/Services/Compositor/AnimatedImage.h@@ -0,0 +1,115 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <AK/Array.h>+#include <AK/NonnullRefPtr.h>+#include <AK/Optional.h>+#include <AK/Time.h>+#include <AK/Types.h>+#include <AK/Vector.h>+#include <AK/kmalloc.h>+#include <LibGfx/ColorSpace.h>+#include <LibGfx/DecodedImageFrame.h>+#include <LibGfx/Forward.h>+#include <LibGfx/Size.h>++namespace Compositor {++// A multi-frame image that advances by the clock, whatever the page's main thread is doing. The frames come straight+// from the image decoder of the page's process, a few at a time.+class AnimatedImage {+public:+ AK_ALLOC_WITH_KMALLOC;++ struct Description {+ i64 session_id { 0 };+ Gfx::IntSize size;+ Gfx::ColorSpace color_space;+ Vector<u32> frame_durations_in_milliseconds;+ u32 loop_count { 0 };+ };++ struct FrameRequest {+ i64 session_id { 0 };+ u32 start_frame_index { 0 };+ u32 count { 0 };+ };++ explicit AnimatedImage(Description);++ i64 session_id() const { return m_session_id; }++ void start(MonotonicTime now);+ void stop();++ // Whether the image still has frames to move through.+ bool is_animating(MonotonicTime now) const;+ u32 frame_index_at(MonotonicTime now) const;+ u32 loops_completed_at(MonotonicTime now) const;+ MonotonicTime next_frame_time_after(MonotonicTime now) const;++ // Moves to the frame for the time, or as near it as the frames that have arrived allow. Returns whether the image+ // now shows another frame.+ bool advance_to(MonotonicTime now);+ Optional<Gfx::DecodedImageFrame> const& shown_frame() const { return m_shown_frame; }+ u32 shown_frame_index() const { return m_shown_frame_index; }++ // The frames to ask the decoder for next, if any. The caller must ask for them.+ Optional<FrameRequest> take_frame_request(MonotonicTime now);+ // Returns whether any of the frames is one the image did not have.+ bool receive_frames(Vector<NonnullRefPtr<Gfx::Bitmap>>);+ void decoding_failed();+ // The decoder this image's session was on is gone. The image keeps showing the frame it has.+ void lose_decoder();++private:+ static constexpr u32 BUFFER_POOL_SIZE = 8;+ static constexpr u32 REQUEST_BATCH_SIZE = 4;+ // NB: The decoders hand out what the file says, which can be 0 for each frame of a loop.+ static constexpr u32 MINIMUM_FRAME_DURATION_IN_MILLISECONDS = 10;++ struct BufferSlot {+ Optional<u32> frame_index;+ Optional<Gfx::DecodedImageFrame> frame;+ u64 generation { 0 };+ };++ struct TimelinePosition {+ u64 loops_completed { 0 };+ u32 frame_index { 0 };+ // When the frame ends, in milliseconds since the start of its loop.+ u64 frame_end_in_milliseconds { 0 };+ bool has_finished { false };+ };++ u32 frame_count() const { return m_frame_durations_in_milliseconds.size(); }+ TimelinePosition position_at(MonotonicTime now) const;+ BufferSlot const* find_slot(u32 frame_index) const;+ BufferSlot& evict_oldest_slot();+ u32 frames_behind(u32 frame_index, u32 target_frame_index) const;++ i64 m_session_id { 0 };+ Gfx::IntSize m_size;+ Gfx::ColorSpace m_color_space;+ Vector<u32> m_frame_durations_in_milliseconds;+ u64 m_loop_duration_in_milliseconds { 0 };+ u32 m_loop_count { 0 };++ Optional<MonotonicTime> m_start_time;++ Array<BufferSlot, BUFFER_POOL_SIZE> m_buffer_slots;+ u64 m_write_generation { 0 };+ bool m_request_in_flight { false };+ u32 m_requested_start_frame_index { 0 };++ // Until a frame arrives from the decoder, the display list's own frame 0 shows.+ Optional<Gfx::DecodedImageFrame> m_shown_frame;+ u32 m_shown_frame_index { 0 };+};++}diff --git a/Services/Compositor/CMakeLists.txt b/Services/Compositor/CMakeLists.txtindex 5eaf310ad9e..486095b478a 100644--- a/Services/Compositor/CMakeLists.txt+++ b/Services/Compositor/CMakeLists.txt@@ -1,4 +1,5 @@set(SOURCES+ AnimatedImage.cppAsyncScrollUpdateOutbox.cppBackingStoreManager.cppBitmapExport.cpp@@ -82,7 +83,7 @@ target_include_directories(compositorservice PRIVATE ${LADYBIRD_SOURCE_DIR}/Servtarget_link_libraries(Compositor PRIVATE compositorservice LibCore LibMain LibSandbox)# ANGLE must precede Skia so macOS GLES symbols bind to ANGLE rather than the# OpenGL framework pulled in by Skia.-target_link_libraries(compositorservice PRIVATE LibCore LibGfx LibIPC LibMedia LibCompositing ${ANGLE_TARGETS} skia)+target_link_libraries(compositorservice PRIVATE LibCore LibGfx LibImageDecoderClient LibIPC LibMedia LibCompositing ${ANGLE_TARGETS} skia)if (HAS_VULKAN)target_sources(compositorservice PRIVATE SkiaVulkanMemoryAllocator.cpp)diff --git a/Services/Compositor/CompositorState.cpp b/Services/Compositor/CompositorState.cppindex 9e520f3d997..7de9c42381b 100644--- a/Services/Compositor/CompositorState.cpp+++ b/Services/Compositor/CompositorState.cpp@@ -123,6 +123,7 @@ void CompositorState::destroy_contexts_for_web_content_client(CompositorStateWeb}m_video_sink_states.remove(&client);+ m_animated_images.remove(&client);m_placeholder_canvases.remove_all_matching([&](auto canvas_id, auto const& placeholder) {if (placeholder.owner != &client)@@ -289,6 +290,7 @@ void CompositorState::update_display_list(Web::CompositorContextId context_id, Ncontext->apply_display_list_resource_transaction(move(resource_transaction));context->install_display_list_update(move(display_list), move(visual_context_tree), move(scroll_state_snapshot));resolve_video_sinks(*context);+ show_animated_image_frames_in(*context);update_unpainted_video_update_scheduling();}@@ -298,6 +300,7 @@ void CompositorState::update_display_list_resources(Web::CompositorContextId conauto* context = context_if_present(context_id);VERIFY(context);context->apply_display_list_resource_transaction(move(resource_transaction));+ show_animated_image_frames_in(*context);}void CompositorState::update_visual_context_tree(Web::CompositorContextId context_id, Compositing::AccumulatedVisualContextTree visual_context_tree, Compositing::DisplayListResourceTransaction&& resource_transaction)@@ -306,6 +309,7 @@ void CompositorState::update_visual_context_tree(Web::CompositorContextId contexVERIFY(context);context->update_visual_context_tree(move(visual_context_tree), move(resource_transaction));+ show_animated_image_frames_in(*context);}void CompositorState::update_scroll_state(Web::CompositorContextId context_id, Compositing::ScrollStateSnapshot&& scroll_state_snapshot, Compositing::KeyboardScrollState keyboard_scroll_state)@@ -409,6 +413,161 @@ void CompositorState::update_unpainted_video_update_scheduling()}}+void CompositorState::add_animated_image(CompositorStateWebContentClient& client, Compositing::ImageFrameResourceId id, AnimatedImage::Description description)+{+ m_animated_images.ensure(&client).set(id.value(), make<AnimatedImage>(move(description)));+}++void CompositorState::remove_animated_image(CompositorStateWebContentClient& client, Compositing::ImageFrameResourceId id)+{+ if (auto images = m_animated_images.find(&client); images != m_animated_images.end())+ images->value.remove(id.value());+}++AnimatedImage* CompositorState::animated_image_mutable(CompositorStateWebContentClient& client, Compositing::ImageFrameResourceId id)+{+ auto images = m_animated_images.find(&client);+ if (images == m_animated_images.end())+ return nullptr;+ auto image = images->value.find(id.value());+ return image == images->value.end() ? nullptr : image->value.ptr();+}++AnimatedImage const* CompositorState::animated_image(CompositorStateWebContentClient& client, Compositing::ImageFrameResourceId id) const+{+ return const_cast<CompositorState*>(this)->animated_image_mutable(client, id);+}++AnimatedImage* CompositorState::animated_image_with_session(CompositorStateWebContentClient& client, i64 session_id)+{+ auto images = m_animated_images.find(&client);+ if (images == m_animated_images.end())+ return nullptr;+ for (auto& image : images->value) {+ if (image.value->session_id() == session_id)+ return image.value.ptr();+ }+ return nullptr;+}++void CompositorState::start_animated_image(CompositorStateWebContentClient& client, Compositing::ImageFrameResourceId id)+{+ if (auto* image = animated_image_mutable(client, id)) {+ image->start(MonotonicTime::now());+ schedule_animated_image_update({});+ }+}++void CompositorState::stop_animated_image(CompositorStateWebContentClient& client, Compositing::ImageFrameResourceId id)+{+ if (auto* image = animated_image_mutable(client, id))+ image->stop();+}++void CompositorState::animated_image_frames_decoded(CompositorStateWebContentClient& client, i64 session_id, Vector<NonnullRefPtr<Gfx::Bitmap>> bitmaps)+{+ // NB: Frames that brought nothing new must wait for the next tick, or the same request would go out again at once.+ if (auto* image = animated_image_with_session(client, session_id); image && image->receive_frames(move(bitmaps)))+ update_animated_images();+}++void CompositorState::animated_image_decode_failed(CompositorStateWebContentClient& client, i64 session_id)+{+ if (auto* image = animated_image_with_session(client, session_id))+ image->decoding_failed();+}++void CompositorState::animated_image_decoder_lost(CompositorStateWebContentClient& client)+{+ if (auto images = m_animated_images.find(&client); images != m_animated_images.end()) {+ for (auto& image : images->value)+ image.value->lose_decoder();+ }+}++bool CompositorState::animated_image_is_drawn(CompositorStateWebContentClient* client, Compositing::ImageFrameResourceId id)+{+ for (auto& context_entry : m_contexts) {+ auto& context = *context_entry.value;+ if (&context.web_content_client() == client && context_is_effectively_visible(context) && context.has_image_frame(id))+ return true;+ }+ return false;+}++void CompositorState::show_animated_image_frame(CompositorStateWebContentClient* client, Compositing::ImageFrameResourceId id, Gfx::DecodedImageFrame const& frame)+{+ for (auto& context_entry : m_contexts) {+ auto& context = *context_entry.value;+ if (&context.web_content_client() != client || !context.has_image_frame(id))+ continue;+ context.replace_image_frame_pixels(id, frame);+ if (!context_is_effectively_visible(context))+ continue;+ if (auto rect = context.presenter().self_present_rect(); rect.has_value())+ schedule_present_frame(context_entry.key, context, PendingFrame::repainting_changes(*rect));+ }+}++void CompositorState::show_animated_image_frames_in(ContextState& context)+{+ auto images = m_animated_images.find(&context.web_content_client());+ if (images == m_animated_images.end())+ return;+ for (auto& image_entry : images->value) {+ Compositing::ImageFrameResourceId id { image_entry.key };+ auto const& frame = image_entry.value->shown_frame();+ if (frame.has_value() && context.has_image_frame(id) && &context.image_frame(id).bitmap() != &frame->bitmap())+ context.replace_image_frame_pixels(id, *frame);+ }+ // An image that nothing drew has been waiting for a context to draw it.+ if (!images->value.is_empty())+ schedule_animated_image_update({});+}++void CompositorState::update_animated_images()+{+ auto now = MonotonicTime::now();+ Optional<MonotonicTime> next_update;+ for (auto& client_entry : m_animated_images) {+ auto* client = client_entry.key;+ for (auto& image_entry : client_entry.value) {+ Compositing::ImageFrameResourceId id { image_entry.key };+ auto& image = *image_entry.value;++ // An image nothing shows costs nothing. It finds its place by the clock once something shows it again.+ if (!animated_image_is_drawn(client, id))+ continue;++ if (image.advance_to(now))+ show_animated_image_frame(client, id, *image.shown_frame());++ auto is_animating = image.is_animating(now);+ if (is_animating || image.shown_frame_index() != image.frame_index_at(now)) {+ if (auto request = image.take_frame_request(now); request.has_value())+ client->request_animated_image_frames(*request);+ }+ if (is_animating) {+ auto next_frame_time = image.next_frame_time_after(now);+ if (!next_update.has_value() || next_frame_time < *next_update)+ next_update = next_frame_time;+ }+ }+ }+ if (next_update.has_value())+ schedule_animated_image_update(*next_update - now);+}++void CompositorState::schedule_animated_image_update(AK::Duration delay)+{+ if (!m_animated_image_update_timer) {+ m_animated_image_update_timer = Core::Timer::create_single_shot(AK::Duration::from_milliseconds(0), [this] {+ update_animated_images();+ });+ }+ m_animated_image_update_timer->restart(delay);+}+void CompositorState::present_contexts_drawing_video_sink(CompositorStateWebContentClient& client, Media::VideoSinkHandle handle){for (auto& context_entry : m_contexts) {@@ -1457,6 +1616,8 @@ void CompositorState::set_context_presents_from_cpu_memory(Web::CompositorContexvoid CompositorState::resume_presentation_after_becoming_visible(Web::CompositorContextId root_context_id, ContextState& root_context){+ schedule_animated_image_update({});+for (auto& context_entry : m_contexts) {auto& context = *context_entry.value;if (root_context_of(context) != &root_context)diff --git a/Services/Compositor/CompositorState.h b/Services/Compositor/CompositorState.hindex ee5c2c06ad4..718801f23ba 100644--- a/Services/Compositor/CompositorState.h+++ b/Services/Compositor/CompositorState.h@@ -12,6 +12,7 @@#include <AK/Optional.h>#include <AK/OwnPtr.h>#include <AK/RefCounted.h>+#include <Compositor/AnimatedImage.h>#include <Compositor/CanvasSurfaceRegistry.h>#include <Compositor/ContextState.h>#include <Compositor/DisplayListPlayerSkia.h>@@ -73,6 +74,7 @@ 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 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.virtual Compositing::CanvasSurfaceOwnerId canvas_surface_owner_id() const = 0;@@ -127,6 +129,15 @@ public:void remove_video_sink(CompositorStateWebContentClient&, Media::VideoSinkHandle);void set_video_sink_ticking(CompositorStateWebContentClient&, Media::VideoSinkHandle, bool should_tick);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);+ void start_animated_image(CompositorStateWebContentClient&, Compositing::ImageFrameResourceId);+ void stop_animated_image(CompositorStateWebContentClient&, Compositing::ImageFrameResourceId);+ void animated_image_frames_decoded(CompositorStateWebContentClient&, i64 session_id, Vector<NonnullRefPtr<Gfx::Bitmap>>);+ void animated_image_decode_failed(CompositorStateWebContentClient&, i64 session_id);+ // The client's images lost the decoder their sessions were on. Each keeps the frame it shows.+ void animated_image_decoder_lost(CompositorStateWebContentClient&);+ AnimatedImage const* animated_image(CompositorStateWebContentClient&, Compositing::ImageFrameResourceId) const;void invalidate_wheel_event_listener_state(Web::CompositorContextId, u64 generation);void invalidate_keyboard_scroll_state(Web::CompositorContextId, u64 generation);void handle_and_dispatch_key_event(Web::CompositorContextId, Web::KeyEvent, bool allow_keyboard_scroll);@@ -339,6 +350,17 @@ private:bool video_sink_is_painted_by_any_context(CompositorStateWebContentClient*, Media::VideoSinkHandle) const;void update_unpainted_video_update_scheduling();HashMap<CompositorStateWebContentClient*, HashMap<Media::VideoSinkHandle, VideoSinkState>> m_video_sink_states;++ AnimatedImage* animated_image_mutable(CompositorStateWebContentClient&, Compositing::ImageFrameResourceId);+ AnimatedImage* animated_image_with_session(CompositorStateWebContentClient&, i64 session_id);+ bool animated_image_is_drawn(CompositorStateWebContentClient*, Compositing::ImageFrameResourceId);+ void show_animated_image_frame(CompositorStateWebContentClient*, Compositing::ImageFrameResourceId, Gfx::DecodedImageFrame const&);+ // A frame that names an animated image brings frame 0 with it, whichever frame the image is at.+ void show_animated_image_frames_in(ContextState&);+ void update_animated_images();+ void schedule_animated_image_update(AK::Duration delay);+ HashMap<CompositorStateWebContentClient*, HashMap<u64, NonnullOwnPtr<AnimatedImage>>> m_animated_images;+ RefPtr<Core::Timer> m_animated_image_update_timer;RefPtr<Core::Timer> m_unpainted_video_update_timer;struct PlaceholderCanvas {diff --git a/Services/Compositor/CompositorWebContentServer.ipc b/Services/Compositor/CompositorWebContentServer.ipcindex 3fa29959c39..f4f6aa2c044 100644--- a/Services/Compositor/CompositorWebContentServer.ipc+++ b/Services/Compositor/CompositorWebContentServer.ipc@@ -29,6 +29,15 @@ endpoint CompositorWebContentServerrelease_video_frame_hold(Media::VideoSinkHandle video_sink_handle, u64 generation) =|set_video_sink_ticking(Media::VideoSinkHandle video_sink_handle, bool should_tick) =|+ // 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) =|+ // The image frame with the id shows the frames of the image decoder's session, once the image is started.+ add_animated_image(u64 frame_id, i64 session_id, Gfx::IntSize size, Gfx::ColorSpace color_space, Vector<u32> frame_durations_in_milliseconds, u32 loop_count) =|+ remove_animated_image(u64 frame_id) =|+ start_animated_image(u64 frame_id) =|+ stop_animated_image(u64 frame_id) =|+ animated_image_state_for_testing(u64 frame_id) => (bool is_animating, u32 frame_index, u32 shown_frame_index, u32 loops_completed)+set_parent_context(Web::CompositorContextId context_id, Optional<Web::CompositorContextId> parent_context_id) =|stop_presenting_to_client(Web::CompositorContextId context_id) =|destroy_context(Web::CompositorContextId context_id) =|diff --git a/Services/Compositor/ConnectionFromWebContent.cpp b/Services/Compositor/ConnectionFromWebContent.cppindex 43cc5accf7f..9c263e2e40f 100644--- a/Services/Compositor/ConnectionFromWebContent.cpp+++ b/Services/Compositor/ConnectionFromWebContent.cpp@@ -27,6 +27,7 @@ ConnectionFromWebContent::ConnectionFromWebContent(NonnullOwnPtr<IPC::Transport>void ConnectionFromWebContent::die(){auto protector = NonnullRefPtr { *this };+ drop_image_decoder();m_compositor_state->destroy_contexts_for_web_content_client(*this);if (m_on_death)m_on_death(*this);@@ -89,6 +90,80 @@ void ConnectionFromWebContent::pointer_rests_on_moving_content(Web::CompositorCom_render_clock_connection->async_pointer_rests_on_moving_content(context_id);}+void ConnectionFromWebContent::drop_image_decoder()+{+ if (!m_image_decoder)+ return;+ m_image_decoder->on_death = nullptr;+ m_image_decoder->on_animation_frames_decoded = nullptr;+ m_image_decoder->on_animation_decode_failed = nullptr;+ m_image_decoder = nullptr;+}++void ConnectionFromWebContent::connect_to_image_decoder(IPC::TransportHandle handle)+{+ // NB: A new channel means a new decoder, whose sessions the ones of the old decoder must not be confused with.+ m_compositor_state->animated_image_decoder_lost(*this);+ drop_image_decoder();++ auto transport_or_error = handle.create_transport();+ if (transport_or_error.is_error()) {+ dbgln("Compositor: Could not take up an image decoder channel: {}", transport_or_error.error());+ return;+ }+ m_image_decoder = make_ref_counted<ImageDecoderClient::Client>(transport_or_error.release_value());+ m_image_decoder->on_death = [this] {+ m_compositor_state->animated_image_decoder_lost(*this);+ drop_image_decoder();+ };+ m_image_decoder->on_animation_frames_decoded = [this](i64 session_id, Vector<NonnullRefPtr<Gfx::Bitmap>> bitmaps) {+ m_compositor_state->animated_image_frames_decoded(*this, session_id, move(bitmaps));+ };+ m_image_decoder->on_animation_decode_failed = [this](i64 session_id, String) {+ m_compositor_state->animated_image_decode_failed(*this, session_id);+ };+}++void ConnectionFromWebContent::add_animated_image(u64 frame_id, i64 session_id, Gfx::IntSize size, Gfx::ColorSpace color_space, Vector<u32> frame_durations_in_milliseconds, u32 loop_count)+{+ if (frame_durations_in_milliseconds.is_empty()) {+ did_misbehave("WebContent added an animated image with no frames");+ return;+ }+ m_compositor_state->add_animated_image(*this, Compositing::ImageFrameResourceId { frame_id },+ { .session_id = session_id, .size = size, .color_space = move(color_space), .frame_durations_in_milliseconds = move(frame_durations_in_milliseconds), .loop_count = loop_count });+}++void ConnectionFromWebContent::remove_animated_image(u64 frame_id)+{+ m_compositor_state->remove_animated_image(*this, Compositing::ImageFrameResourceId { frame_id });+}++void ConnectionFromWebContent::start_animated_image(u64 frame_id)+{+ m_compositor_state->start_animated_image(*this, Compositing::ImageFrameResourceId { frame_id });+}++void ConnectionFromWebContent::stop_animated_image(u64 frame_id)+{+ m_compositor_state->stop_animated_image(*this, Compositing::ImageFrameResourceId { frame_id });+}++Messages::CompositorWebContentServer::AnimatedImageStateForTestingResponse ConnectionFromWebContent::animated_image_state_for_testing(u64 frame_id)+{+ auto const* image = m_compositor_state->animated_image(*this, Compositing::ImageFrameResourceId { frame_id });+ if (!image)+ return { false, 0, 0, 0 };+ auto now = MonotonicTime::now();+ return { image->is_animating(now), image->frame_index_at(now), image->shown_frame_index(), image->loops_completed_at(now) };+}++void ConnectionFromWebContent::request_animated_image_frames(AnimatedImage::FrameRequest const& request)+{+ if (m_image_decoder)+ m_image_decoder->request_animation_frames(request.session_id, request.start_frame_index, request.count);+}+void ConnectionFromWebContent::add_video_sink(Media::VideoSinkHandle video_sink_handle, NonnullRefPtr<Compositing::VideoFramePresentationPage> presentation_page){m_video_frame_holds.add_sink(video_sink_handle, move(presentation_page));diff --git a/Services/Compositor/ConnectionFromWebContent.h b/Services/Compositor/ConnectionFromWebContent.hindex fef654ee53c..7aedc0ba3d8 100644--- a/Services/Compositor/ConnectionFromWebContent.h+++ b/Services/Compositor/ConnectionFromWebContent.h@@ -20,6 +20,7 @@#include <LibCore/AnonymousBuffer.h>#include <LibGfx/Size.h>#include <LibIPC/ConnectionFromClient.h>+#include <LibImageDecoderClient/Client.h>#include <LibMedia/VideoPresentation/VideoPresentationClientConnection.h>namespace Compositor {@@ -43,6 +44,12 @@ private:virtual void die() override;+ virtual void connect_to_image_decoder(IPC::TransportHandle) override;+ virtual void add_animated_image(u64 frame_id, i64 session_id, Gfx::IntSize, Gfx::ColorSpace, Vector<u32> frame_durations_in_milliseconds, u32 loop_count) override;+ virtual void remove_animated_image(u64 frame_id) override;+ virtual void start_animated_image(u64 frame_id) override;+ virtual void stop_animated_image(u64 frame_id) override;+ virtual Messages::CompositorWebContentServer::AnimatedImageStateForTestingResponse animated_image_state_for_testing(u64 frame_id) override;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;@@ -108,6 +115,7 @@ private:virtual void overlay_scrollbar_visibilities_changed(Vector<Web::OverlayScrollbarVisibility> const&) override;virtual void create_video_edge(Media::VideoSinkHandle) override;virtual void release_video_edge(Media::VideoSinkHandle) override;+ virtual void request_animated_image_frames(AnimatedImage::FrameRequest const&) override;virtual void video_sink_presented_frame(Media::VideoSinkHandle, RefPtr<Media::VideoFrame>, Media::DisplayingVideoSinkFrameCounts) override;virtual void video_sink_counted_frames(Media::VideoSinkHandle, Media::DisplayingVideoSinkFrameCounts) override;virtual void placeholder_canvas_committed(Compositing::CanvasId, Gfx::IntSize, bool origin_clean) override;@@ -130,6 +138,9 @@ private:// The presentation client end of this WebContent's video presentation channel (connect-only for now).RefPtr<Media::VideoPresentationClientConnection> m_video_presentation_connection;+ void drop_image_decoder();++ RefPtr<ImageDecoderClient::Client> m_image_decoder;RefPtr<RenderClockConnection> m_render_clock_connection;};diff --git a/Services/Compositor/ContextState.h b/Services/Compositor/ContextState.hindex d4203676af6..a196ea6f454 100644--- a/Services/Compositor/ContextState.h+++ b/Services/Compositor/ContextState.h@@ -190,6 +190,9 @@ public:void update_scroll_state(Compositing::ScrollStateSnapshot&&, Compositing::KeyboardScrollState);void set_video_sink(Compositing::VideoSinkResourceId, RefPtr<Media::DisplayingVideoSink>);HashMap<u64, Media::VideoSinkHandle> const& video_sink_handles() const { return m_scene.video_sink_handles(); }+ bool has_image_frame(Compositing::ImageFrameResourceId id) { return m_scene.resource_storage().has_image_frame(id); }+ Gfx::DecodedImageFrame const& image_frame(Compositing::ImageFrameResourceId id) { return m_scene.resource_storage().image_frame(id); }+ void replace_image_frame_pixels(Compositing::ImageFrameResourceId id, Gfx::DecodedImageFrame frame) { m_scene.resource_storage().replace_image_frame_pixels(id, move(frame)); }void invalidate_wheel_event_listener_state(u64 generation);void invalidate_keyboard_scroll_state(u64 generation);diff --git a/Services/WebContent/PageHost.cpp b/Services/WebContent/PageHost.cppindex 2c76b7a97f7..1e44a8fc0a9 100644--- a/Services/WebContent/PageHost.cpp+++ b/Services/WebContent/PageHost.cpp@@ -97,6 +97,8 @@ void PageHost::ensure_compositor_host()void PageHost::compositor_process_reconnected(){+ if (m_compositor_host)+ m_compositor_host->register_animated_images_with_new_compositor();for (auto& [_, page] : m_pages)page->compositor_process_reconnected();}diff --git a/Tests/LibWeb/Screenshot/input/animated-background-image-late-consumer-uses-first-consumer-timing.html b/Tests/LibWeb/Screenshot/input/animated-background-image-late-consumer-uses-first-consumer-timing.htmlindex 4fd05fe3e4f..821c9544dd2 100644--- a/Tests/LibWeb/Screenshot/input/animated-background-image-late-consumer-uses-first-consumer-timing.html+++ b/Tests/LibWeb/Screenshot/input/animated-background-image-late-consumer-uses-first-consumer-timing.html@@ -25,7 +25,7 @@const imageURL = "../data/red-then-green.gif";// Wait for the animation to start.- await waitForImageAnimationState(imageURL, state => state.timerActive);+ await waitForImageAnimationState(imageURL, state => state.isAnimating);// Wait for half of the first frame's durationawait timeout(250);@@ -36,7 +36,7 @@container.append(lateTarget);// Wait for the animation to advance to the second frame. Both consumers should be showing the second frame- await waitForImageAnimationState(imageURL, state => state.frameIndex > 0);+ await waitForImageAnimationState(imageURL, state => state.shownFrameIndex > 0);document.documentElement.classList.remove("reftest-wait");})();diff --git a/Tests/LibWeb/Screenshot/input/animated-background-image-repaints-on-advance.html b/Tests/LibWeb/Screenshot/input/animated-background-image-repaints-on-advance.htmlindex 6ea09301dbc..32488010701 100644--- a/Tests/LibWeb/Screenshot/input/animated-background-image-repaints-on-advance.html+++ b/Tests/LibWeb/Screenshot/input/animated-background-image-repaints-on-advance.html@@ -19,10 +19,10 @@const imageURL = "../data/red-then-green.gif";// Wait for the animation to start- await waitForImageAnimationState(imageURL, state => state.timerActive);+ await waitForImageAnimationState(imageURL, state => state.isAnimating);// Wait until the next frame- await waitForImageAnimationState(imageURL, state => state.frameIndex > 0);+ await waitForImageAnimationState(imageURL, state => state.shownFrameIndex > 0);// Take a screenshot - the image should have been invalidated and repainted.document.documentElement.classList.remove("reftest-wait");diff --git a/Tests/LibWeb/Screenshot/input/animated-mask-image-repaints-on-advance.html b/Tests/LibWeb/Screenshot/input/animated-mask-image-repaints-on-advance.htmlindex 3aee66e67d4..f0b92fed5ef 100644--- a/Tests/LibWeb/Screenshot/input/animated-mask-image-repaints-on-advance.html+++ b/Tests/LibWeb/Screenshot/input/animated-mask-image-repaints-on-advance.html@@ -25,10 +25,10 @@(async () => {// Wait for the animation to start- await waitForImageAnimationState(gifURL, state => state.timerActive);+ await waitForImageAnimationState(gifURL, state => state.isAnimating);// Wait until the next frame- await waitForImageAnimationState(gifURL, state => state.frameIndex > 0);+ await waitForImageAnimationState(gifURL, state => state.shownFrameIndex > 0);// Take a screenshot - the mask image should have been invalidated and repainted.document.documentElement.classList.remove("reftest-wait");diff --git a/Tests/LibWeb/TestFaviconDecoding.cpp b/Tests/LibWeb/TestFaviconDecoding.cppindex f499efbd3e7..fb4d415018f 100644--- a/Tests/LibWeb/TestFaviconDecoding.cpp+++ b/Tests/LibWeb/TestFaviconDecoding.cpp@@ -34,8 +34,9 @@ public:}virtual ErrorOr<Web::Platform::DecodedFirstFrame> decode_first_frame_synchronously(ReadonlyBytes) override { VERIFY_NOT_REACHED(); }- virtual void request_animation_frames(i64, u32, u32) override { VERIFY_NOT_REACHED(); }virtual void stop_animation_decode(i64) override { VERIFY_NOT_REACHED(); }+ virtual void connect_frame_client(IPC::TransportHandle) override { VERIFY_NOT_REACHED(); }+ virtual u64 client_generation() const override { VERIFY_NOT_REACHED(); }size_t decode_count { 0 };};diff --git a/Tests/LibWeb/Text/data/animated-image-loops-forever.gif b/Tests/LibWeb/Text/data/animated-image-loops-forever.gifnew file mode 100644index 00000000000..eccf5af3ec9Binary files /dev/null and b/Tests/LibWeb/Text/data/animated-image-loops-forever.gif differdiff --git a/Tests/LibWeb/Text/expected/css/animated-image-advances-while-main-thread-is-busy.txt b/Tests/LibWeb/Text/expected/css/animated-image-advances-while-main-thread-is-busy.txtnew file mode 100644index 00000000000..b886d868384--- /dev/null+++ b/Tests/LibWeb/Text/expected/css/animated-image-advances-while-main-thread-is-busy.txt@@ -0,0 +1 @@+image advanced while the main thread was busydiff --git a/Tests/LibWeb/Text/input/css/animated-background-image-finite-loop-stops-timer.html b/Tests/LibWeb/Text/input/css/animated-background-image-finite-loop-stops-timer.htmlindex 70ba6207dc5..623d7080749 100644--- a/Tests/LibWeb/Text/input/css/animated-background-image-finite-loop-stops-timer.html+++ b/Tests/LibWeb/Text/input/css/animated-background-image-finite-loop-stops-timer.html@@ -15,7 +15,7 @@console.log("A");// Wait for the animation to start.- await waitForImageAnimationState(imageURL, state => state.timerActive);+ await waitForImageAnimationState(imageURL, state => state.isAnimating);console.log("B");@@ -24,7 +24,7 @@console.log("C");- println(internals.imageAnimationStateForURL(imageURL).timerActive ? "FAIL" : "PASS");+ println(internals.imageAnimationStateForURL(imageURL).isAnimating ? "FAIL" : "PASS");console.log("D");});diff --git a/Tests/LibWeb/Text/input/css/animated-background-image-loads-from-overlay.html b/Tests/LibWeb/Text/input/css/animated-background-image-loads-from-overlay.htmlindex 2b8ae0f25b5..80b7a304f4e 100644--- a/Tests/LibWeb/Text/input/css/animated-background-image-loads-from-overlay.html+++ b/Tests/LibWeb/Text/input/css/animated-background-image-loads-from-overlay.html@@ -8,7 +8,7 @@promiseTest(async () => {target.animate({ backgroundImage: [`url("${imageURL}")`, `url("${imageURL}")`] }, { duration: 1000000 });internals.dumpLayoutTree(document);- const state = await waitForImageAnimationState(imageURL, state => state.timerActive);- println(`animated image loaded: ${state.timerActive}`);+ const state = await waitForImageAnimationState(imageURL, state => state.isAnimating);+ println(`animated image loaded: ${state.isAnimating}`);});</script>diff --git a/Tests/LibWeb/Text/input/css/animated-background-image-pauses-for-inactive-document.html b/Tests/LibWeb/Text/input/css/animated-background-image-pauses-for-inactive-document.htmlindex fdbefaaa0e8..785c36b40b5 100644--- a/Tests/LibWeb/Text/input/css/animated-background-image-pauses-for-inactive-document.html+++ b/Tests/LibWeb/Text/input/css/animated-background-image-pauses-for-inactive-document.html@@ -29,21 +29,21 @@const iframeWindow = iframe.contentWindow;// Wait the animation to progress to the second frame- await waitForImageAnimationState(imageURL, state => state.timerActive && state.frameIndex > 0, iframeWindow);+ await waitForImageAnimationState(imageURL, state => state.isAnimating && state.frameIndex > 0, iframeWindow);// Make the iframe document inactive - this should stop the animation.iframe.remove();- const stateAfterRemoval = await waitForImageAnimationState(imageURL, state => !state.timerActive, iframeWindow);+ const stateAfterRemoval = await waitForImageAnimationState(imageURL, state => !state.isAnimating, iframeWindow);- println(`timer stopped after iframe removal: ${!stateAfterRemoval.timerActive}`);+ println(`timer stopped after iframe removal: ${!stateAfterRemoval.isAnimating}`);// Make the iframe document active again - this should reset the animation.await loadIframe(iframe);const stateAfterReattach = iframe.contentWindow.internals.imageAnimationStateForURL(imageURL);println(- `animation restarted after iframe reattach: ${stateAfterReattach.timerActive && stateAfterReattach.frameIndex === 0 && stateAfterReattach.loopsCompleted === 0}`+ `animation restarted after iframe reattach: ${stateAfterReattach.isAnimating && stateAfterReattach.frameIndex === 0 && stateAfterReattach.loopsCompleted === 0}`);});</script>diff --git a/Tests/LibWeb/Text/input/css/animated-background-image-shared-resource-count.html b/Tests/LibWeb/Text/input/css/animated-background-image-shared-resource-count.htmlindex 85abdb7e422..96c5f01b1ac 100644--- a/Tests/LibWeb/Text/input/css/animated-background-image-shared-resource-count.html+++ b/Tests/LibWeb/Text/input/css/animated-background-image-shared-resource-count.html@@ -18,7 +18,7 @@internals.dumpLayoutTree(document);const state = internals.imageAnimationStateForURL(imageURL);- println(`timer active for shared animation: ${state.timerActive}`);+ println(`timer active for shared animation: ${state.isAnimating}`);println(`client count: ${state.clientCount}`);});</script>diff --git a/Tests/LibWeb/Text/input/css/animated-background-image-timer-count-is-document-scoped.html b/Tests/LibWeb/Text/input/css/animated-background-image-timer-count-is-document-scoped.htmlindex e03dea1f3ff..3bf0f0b8949 100644--- a/Tests/LibWeb/Text/input/css/animated-background-image-timer-count-is-document-scoped.html+++ b/Tests/LibWeb/Text/input/css/animated-background-image-timer-count-is-document-scoped.html@@ -30,6 +30,6 @@}println(`top document has animation state: ${topDocumentHasAnimationState}`);- println(`iframe document timer active: ${iframe.contentWindow.internals.imageAnimationStateForURL(imageURL).timerActive}`);+ println(`iframe document timer active: ${iframe.contentWindow.internals.imageAnimationStateForURL(imageURL).isAnimating}`);});</script>diff --git a/Tests/LibWeb/Text/input/css/animated-background-image-timer-doesnt-stop-after-base-change.html b/Tests/LibWeb/Text/input/css/animated-background-image-timer-doesnt-stop-after-base-change.htmlindex 52cd3810ca4..e1ffc07a1c3 100644--- a/Tests/LibWeb/Text/input/css/animated-background-image-timer-doesnt-stop-after-base-change.html+++ b/Tests/LibWeb/Text/input/css/animated-background-image-timer-doesnt-stop-after-base-change.html@@ -15,9 +15,9 @@await new Promise(resolve => window.addEventListener("load", resolve));internals.dumpLayoutTree(document);- const timerActiveBeforeBaseChange = internals.imageAnimationStateForURL(imageURL).timerActive;+ const isAnimatingBeforeBaseChange = internals.imageAnimationStateForURL(imageURL).isAnimating;println(- `timer active before base change: ${timerActiveBeforeBaseChange}`+ `timer active before base change: ${isAnimatingBeforeBaseChange}`);const base = document.createElement("base");@@ -26,7 +26,7 @@target.remove();internals.dumpLayoutTree(document);- const timerActiveAfterRemoval = internals.imageAnimationStateForURL(imageURL).timerActive;- println(`timer active after removal: ${timerActiveAfterRemoval}`);+ const isAnimatingAfterRemoval = internals.imageAnimationStateForURL(imageURL).isAnimating;+ println(`timer active after removal: ${isAnimatingAfterRemoval}`);});</script>diff --git a/Tests/LibWeb/Text/input/css/animated-background-image-timer-doesnt-stop-after-full-layout-tree-teardown.html b/Tests/LibWeb/Text/input/css/animated-background-image-timer-doesnt-stop-after-full-layout-tree-teardown.htmlindex 740899f22d5..b5570acba41 100644--- a/Tests/LibWeb/Text/input/css/animated-background-image-timer-doesnt-stop-after-full-layout-tree-teardown.html+++ b/Tests/LibWeb/Text/input/css/animated-background-image-timer-doesnt-stop-after-full-layout-tree-teardown.html@@ -16,14 +16,14 @@await new Promise(resolve => window.addEventListener("load", resolve));internals.dumpLayoutTree(document);- println(`timer active before teardown: ${internals.imageAnimationStateForURL(imageURL).timerActive}`);+ println(`timer active before teardown: ${internals.imageAnimationStateForURL(imageURL).isAnimating}`);dialog.showModal();internals.dumpLayoutTree(document);- println(`timer active after teardown: ${internals.imageAnimationStateForURL(imageURL).timerActive}`);+ println(`timer active after teardown: ${internals.imageAnimationStateForURL(imageURL).isAnimating}`);target.style.display = "none";internals.dumpLayoutTree(document);- println(`timer active after hiding: ${internals.imageAnimationStateForURL(imageURL).timerActive}`);+ println(`timer active after hiding: ${internals.imageAnimationStateForURL(imageURL).isAnimating}`);});</script>diff --git a/Tests/LibWeb/Text/input/css/animated-background-image-timer-doesnt-stop-after-layout-node-replacement.html b/Tests/LibWeb/Text/input/css/animated-background-image-timer-doesnt-stop-after-layout-node-replacement.htmlindex 996ac8d2497..c9412262057 100644--- a/Tests/LibWeb/Text/input/css/animated-background-image-timer-doesnt-stop-after-layout-node-replacement.html+++ b/Tests/LibWeb/Text/input/css/animated-background-image-timer-doesnt-stop-after-layout-node-replacement.html@@ -15,14 +15,14 @@await new Promise(resolve => window.addEventListener("load", resolve));internals.dumpLayoutTree(document);- println(`timer active before replacement: ${internals.imageAnimationStateForURL(imageURL).timerActive}`);+ println(`timer active before replacement: ${internals.imageAnimationStateForURL(imageURL).isAnimating}`);target.style.display = "inline";internals.dumpLayoutTree(document);- println(`timer active after replacement: ${internals.imageAnimationStateForURL(imageURL).timerActive}`);+ println(`timer active after replacement: ${internals.imageAnimationStateForURL(imageURL).isAnimating}`);target.style.display = "none";internals.dumpLayoutTree(document);- println(`timer active after hiding: ${internals.imageAnimationStateForURL(imageURL).timerActive}`);+ println(`timer active after hiding: ${internals.imageAnimationStateForURL(imageURL).isAnimating}`);});</script>diff --git a/Tests/LibWeb/Text/input/css/animated-background-image-timer-doesnt-stop-when-hidden.html b/Tests/LibWeb/Text/input/css/animated-background-image-timer-doesnt-stop-when-hidden.htmlindex 839ab1f75a4..ac167868b53 100644--- a/Tests/LibWeb/Text/input/css/animated-background-image-timer-doesnt-stop-when-hidden.html+++ b/Tests/LibWeb/Text/input/css/animated-background-image-timer-doesnt-stop-when-hidden.html@@ -15,11 +15,11 @@await new Promise(resolve => window.addEventListener("load", resolve));internals.dumpLayoutTree(document);- println(`timer active before hiding: ${internals.imageAnimationStateForURL(imageURL).timerActive}`);+ println(`timer active before hiding: ${internals.imageAnimationStateForURL(imageURL).isAnimating}`);target.style.display = "none";internals.dumpLayoutTree(document);- println(`timer active after hiding: ${internals.imageAnimationStateForURL(imageURL).timerActive}`);+ println(`timer active after hiding: ${internals.imageAnimationStateForURL(imageURL).isAnimating}`);});</script>diff --git a/Tests/LibWeb/Text/input/css/animated-generated-content-image-timer-doesnt-stop-when-hidden.html b/Tests/LibWeb/Text/input/css/animated-generated-content-image-timer-doesnt-stop-when-hidden.htmlindex 93107267c9c..f9ce73c8983 100644--- a/Tests/LibWeb/Text/input/css/animated-generated-content-image-timer-doesnt-stop-when-hidden.html+++ b/Tests/LibWeb/Text/input/css/animated-generated-content-image-timer-doesnt-stop-when-hidden.html@@ -13,11 +13,11 @@await new Promise(resolve => window.addEventListener("load", resolve));internals.dumpLayoutTree(document);- println(`timer active before hiding: ${internals.imageAnimationStateForURL(imageURL).timerActive}`);+ println(`timer active before hiding: ${internals.imageAnimationStateForURL(imageURL).isAnimating}`);target.style.display = "none";internals.dumpLayoutTree(document);- println(`timer active after hiding: ${internals.imageAnimationStateForURL(imageURL).timerActive}`);+ println(`timer active after hiding: ${internals.imageAnimationStateForURL(imageURL).isAnimating}`);});</script>diff --git a/Tests/LibWeb/Text/input/css/animated-image-advances-while-main-thread-is-busy.html b/Tests/LibWeb/Text/input/css/animated-image-advances-while-main-thread-is-busy.htmlnew file mode 100644index 00000000000..6369051a90a--- /dev/null+++ b/Tests/LibWeb/Text/input/css/animated-image-advances-while-main-thread-is-busy.html@@ -0,0 +1,18 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<img id="image" src="../../data/animated-image-loops-forever.gif">+<script>+ const imageURL = "../../data/animated-image-loops-forever.gif";++ promiseTest(async () => {+ await waitForImageAnimationState(imageURL, state => state.isAnimating);+ await animationFrame();+ await animationFrame();++ // This script does not yield to the event loop, so nothing but the compositor can show the next frame.+ const shownFrameIndex = internals.imageAnimationStateForURL(imageURL).shownFrameIndex;+ while (internals.imageAnimationStateForURL(imageURL).shownFrameIndex === shownFrameIndex) { }++ println("image advanced while the main thread was busy");+ });+</script>diff --git a/Tests/LibWeb/Text/input/css/animated-img-restart-shared-resource.html b/Tests/LibWeb/Text/input/css/animated-img-restart-shared-resource.htmlindex 0730fd893d5..f61c173e155 100644--- a/Tests/LibWeb/Text/input/css/animated-img-restart-shared-resource.html+++ b/Tests/LibWeb/Text/input/css/animated-img-restart-shared-resource.html@@ -21,7 +21,7 @@const stateAfterRestart = internals.imageAnimationStateForURL(imageURL);println(`session unchanged after restart: ${stateAfterRestart.sessionID === stateBeforeRestart.sessionID}`);println(- `animation restarted after src reset: ${stateAfterRestart.frameIndex === 0 && stateAfterRestart.loopsCompleted === 0 && stateAfterRestart.timerActive}`+ `animation restarted after src reset: ${stateAfterRestart.frameIndex === 0 && stateAfterRestart.loopsCompleted === 0 && stateAfterRestart.isAnimating}`);println(`client count after restart: ${stateAfterRestart.clientCount}`);});diff --git a/Tests/LibWeb/Text/input/css/animation-keyframe-relative-url.html b/Tests/LibWeb/Text/input/css/animation-keyframe-relative-url.htmlindex 2bc1d5771f5..9d80b065722 100644--- a/Tests/LibWeb/Text/input/css/animation-keyframe-relative-url.html+++ b/Tests/LibWeb/Text/input/css/animation-keyframe-relative-url.html@@ -7,7 +7,7 @@promiseTest(async () => {internals.dumpLayoutTree(document);- const state = await waitForImageAnimationState(imageURL, state => state.timerActive);- println(`stylesheet-relative image loaded: ${state.timerActive}`);+ const state = await waitForImageAnimationState(imageURL, state => state.isAnimating);+ println(`stylesheet-relative image loaded: ${state.isAnimating}`);});</script>diff --git a/Tests/LibWeb/Text/input/css/inline-relative-css-image-base-url.html b/Tests/LibWeb/Text/input/css/inline-relative-css-image-base-url.htmlindex 18b2a51784e..d15ce4dd399 100644--- a/Tests/LibWeb/Text/input/css/inline-relative-css-image-base-url.html+++ b/Tests/LibWeb/Text/input/css/inline-relative-css-image-base-url.html@@ -14,8 +14,8 @@asyncTest(done => {window.addEventListener("load", () => {internals.dumpLayoutTree(document);- const timerActiveBeforeBaseChange =- internals.imageAnimationStateForURL(imageURL).timerActive;+ const isAnimatingBeforeBaseChange =+ internals.imageAnimationStateForURL(imageURL).isAnimating;const beforeBaseChange = getComputedStyle(target).backgroundImage.replace(imageURL, "[image-url]");const base = document.createElement("base");@@ -24,18 +24,18 @@const afterBaseChange = getComputedStyle(target).backgroundImage.replace(imageURL, "[image-url]");internals.dumpLayoutTree(document);- const timerActiveAfterBaseChange =- internals.imageAnimationStateForURL(imageURL).timerActive;+ const isAnimatingAfterBaseChange =+ internals.imageAnimationStateForURL(imageURL).isAnimating;println(`Computed URL before base change: ${beforeBaseChange}`);println(`Computed URL after base change: ${afterBaseChange}`);println(- `timer active before base change: ${timerActiveBeforeBaseChange}`+ `timer active before base change: ${isAnimatingBeforeBaseChange}`);println(- `timer active after base change: ${timerActiveAfterBaseChange}`+ `timer active after base change: ${isAnimatingAfterBaseChange}`);done();});diff --git a/Tests/LibWeb/Text/input/css/substituted-relative-url-stylesheet-context.html b/Tests/LibWeb/Text/input/css/substituted-relative-url-stylesheet-context.htmlindex 9c7ccc92672..9664cc3917c 100644--- a/Tests/LibWeb/Text/input/css/substituted-relative-url-stylesheet-context.html+++ b/Tests/LibWeb/Text/input/css/substituted-relative-url-stylesheet-context.html@@ -8,7 +8,7 @@promiseTest(async () => {await new Promise(resolve => window.addEventListener("load", resolve));internals.dumpLayoutTree(document);- const state = await waitForImageAnimationState(imageURL, state => state.timerActive);- println(`timer active: ${state.timerActive}`);+ const state = await waitForImageAnimationState(imageURL, state => state.isAnimating);+ println(`timer active: ${state.isAnimating}`);});</script>