Skip to content

Truly independent web browser

LibWeb+ImageDecoder: Discard idle decoded image frames over a budget

Andreas Klingb269107de7fd
diff --git a/Libraries/LibGfx/DecodedImageFrame.h b/Libraries/LibGfx/DecodedImageFrame.h
index 4fa590c91df..102df1dc027 100644
--- a/Libraries/LibGfx/DecodedImageFrame.h
+++ b/Libraries/LibGfx/DecodedImageFrame.h
@@ -34,6 +34,14 @@ public:
{
}
+ // For the same pixels decoded again, which caches keyed by the id of a frame may still hold.
+ static DecodedImageFrame with_id(u64 id, NonnullRefPtr<Bitmap const> bitmap, ColorSpace color_space = {})
+ {
+ DecodedImageFrame frame { move(bitmap), move(color_space) };
+ frame.m_id = id;
+ return frame;
+ }
+
DecodedImageFrame(Bitmap const& bitmap, AlphaType alpha_type, ColorSpace color_space = {})
: DecodedImageFrame(bitmap_with_alpha_type(bitmap, alpha_type), move(color_space))
{
diff --git a/Libraries/LibImageDecoderClient/Client.cpp b/Libraries/LibImageDecoderClient/Client.cpp
index a79d41a97f0..675d0400aad 100644
--- a/Libraries/LibImageDecoderClient/Client.cpp
+++ b/Libraries/LibImageDecoderClient/Client.cpp
@@ -58,6 +58,27 @@ NonnullRefPtr<Core::Promise<DecodedImage>> Client::decode_image(ReadonlyBytes en
return promise;
}
+ErrorOr<DecodedFirstFrame> Client::decode_first_frame_synchronously(ReadonlyBytes encoded_data, Optional<ByteString> mime_type)
+{
+ verify_event_loop();
+ if (encoded_data.is_empty())
+ return Error::from_string_literal("No encoded data");
+
+ auto encoded_buffer = TRY(Core::AnonymousBuffer::create_with_size(encoded_data.size()));
+ memcpy(encoded_buffer.data<void>(), encoded_data.data(), encoded_data.size());
+
+ auto response_or_error = try_decode_first_frame_synchronously(move(encoded_buffer), move(mime_type));
+ if (response_or_error.is_error())
+ return Error::from_string_literal("ImageDecoder disconnected");
+ auto response = response_or_error.release_value();
+
+ // NB: The decoder parses untrusted data, so its reply is checked rather than trusted.
+ auto bitmaps = response.take_bitmaps().bitmaps;
+ if (bitmaps.size() != 1 || !bitmaps[0])
+ return Error::from_string_literal("Image decoding failed");
+ return DecodedFirstFrame { bitmaps[0].release_nonnull(), response.take_color_profile() };
+}
+
void Client::did_decode_image(i64 request_id, bool is_animated, u32 loop_count, Gfx::BitmapSequence bitmap_sequence, Vector<u32> durations, Gfx::FloatPoint scale, Gfx::ColorSpace color_space, i64 session_id)
{
verify_event_loop();
diff --git a/Libraries/LibImageDecoderClient/Client.h b/Libraries/LibImageDecoderClient/Client.h
index 40b82a77e48..4f391b9be77 100644
--- a/Libraries/LibImageDecoderClient/Client.h
+++ b/Libraries/LibImageDecoderClient/Client.h
@@ -32,6 +32,11 @@ struct DecodedImage {
i64 session_id { 0 };
};
+struct DecodedFirstFrame {
+ NonnullRefPtr<Gfx::Bitmap> bitmap;
+ Gfx::ColorSpace color_space;
+};
+
class Client final
: public IPC::ConnectionToServer<ImageDecoderClientEndpoint, ImageDecoderServerEndpoint>
, public ImageDecoderClientEndpoint {
@@ -42,6 +47,8 @@ public:
NonnullRefPtr<Core::Promise<DecodedImage>> decode_image(ReadonlyBytes, Function<ErrorOr<void>(DecodedImage&)> on_resolved, Function<void(Error&)> on_rejected, Optional<Gfx::IntSize> ideal_size = {}, Optional<ByteString> mime_type = {});
+ ErrorOr<DecodedFirstFrame> decode_first_frame_synchronously(ReadonlyBytes, Optional<ByteString> mime_type = {});
+
void request_animation_frames(i64 session_id, u32 start_frame_index, u32 count);
void stop_animation_decode(i64 session_id);
diff --git a/Libraries/LibWeb/HTML/BitmapDecodedImageData.cpp b/Libraries/LibWeb/HTML/BitmapDecodedImageData.cpp
index 1075e4f450f..9d41ccf6740 100644
--- a/Libraries/LibWeb/HTML/BitmapDecodedImageData.cpp
+++ b/Libraries/LibWeb/HTML/BitmapDecodedImageData.cpp
@@ -4,73 +4,280 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+#include <LibCore/Timer.h>
#include <LibGC/Heap.h>
+#include <LibGC/Weak.h>
+#include <LibGC/WeakInlines.h>
#include <LibGfx/Bitmap.h>
#include <LibJS/Runtime/ExternalMemory.h>
#include <LibWeb/CSS/ComputedValues.h>
#include <LibWeb/HTML/BitmapDecodedImageData.h>
+#include <LibWeb/Platform/ImageCodecPlugin.h>
namespace Web::HTML {
GC_DEFINE_ALLOCATOR(BitmapDecodedImageData);
-ErrorOr<GC::Ref<BitmapDecodedImageData>> BitmapDecodedImageData::create(Vector<Frame>&& frames, size_t loop_count, bool animated)
+// NB: A page can hold on to many more images than it shows, e.g. a map that keeps the image of every tile it has
+// uploaded to a WebGL texture. Once the frames of images that can be decoded again add up to more than this, the
+// ones that have not been used for a while are discarded, least recently used first.
+static constexpr size_t discardable_frame_budget = 128 * MiB;
+static constexpr AK::Duration frame_idle_time_before_discard = AK::Duration::from_seconds(5);
+// NB: Frames that something else holds may be let go of at any time, which nothing tells us about, so they are looked
+// at again after this long.
+static constexpr AK::Duration held_frame_recheck_delay = AK::Duration::from_seconds(30);
+// NB: Discarding a small frame saves little, so the encoded data of such an image is not kept.
+static constexpr size_t minimum_discardable_frame_size = 32 * KiB;
+// NB: Decoding again can fail for a while, e.g. while the image decoder is restarted, so it is tried again after this,
+// with the delay doubling after each failure, until it has failed this many times.
+static constexpr AK::Duration delay_before_decoding_again_after_failure = AK::Duration::from_seconds(1);
+static constexpr u8 max_failed_attempts_to_decode_again = 5;
+
+static size_t s_discardable_frame_bytes = 0;
+static MonotonicTime s_next_discard_of_idle_frames;
+
+static BitmapDecodedImageData::DiscardableFrameList& discardable_frames()
+{
+ static auto* list = new BitmapDecodedImageData::DiscardableFrameList;
+ return *list;
+}
+
+ErrorOr<GC::Ref<BitmapDecodedImageData>> BitmapDecodedImageData::create(Vector<Frame>&& frames, size_t loop_count, bool animated, ByteBuffer encoded_data)
{
(void)loop_count;
(void)animated;
if (frames.is_empty())
return Error::from_string_literal("Bitmap image has no frames");
- return GC::Heap::the().allocate<BitmapDecodedImageData>(move(frames[0].frame));
+ // NB: Only the first frame is kept, so only an image that has just the one can be decoded again.
+ if (frames.size() != 1 || frames[0].frame.bitmap().data_size() < minimum_discardable_frame_size) {
+ encoded_data.clear();
+ } else if (encoded_data.capacity() > encoded_data.size()) {
+ // NB: The encoded data is kept for as long as the image, so it should not keep the room it was received into.
+ // Keeping that room is better than failing to create the image, though.
+ if (auto copy = ByteBuffer::copy(encoded_data.bytes()); !copy.is_error())
+ encoded_data = copy.release_value();
+ }
+ return GC::Heap::the().allocate<BitmapDecodedImageData>(move(frames[0].frame), move(encoded_data));
}
-BitmapDecodedImageData::BitmapDecodedImageData(Gfx::DecodedImageFrame&& frame)
+BitmapDecodedImageData::BitmapDecodedImageData(Gfx::DecodedImageFrame&& frame, ByteBuffer encoded_data)
: m_frame(move(frame))
+ , m_size(m_frame->size())
+ , m_encoded_data(move(encoded_data))
+ , m_frame_id(m_frame->id())
{
+ if (!m_encoded_data.is_empty())
+ did_decode_frame();
}
BitmapDecodedImageData::~BitmapDecodedImageData() = default;
+void BitmapDecodedImageData::finalize()
+{
+ Base::finalize();
+ // NB: Clients that die along with the image data cannot unregister from it, since their weak pointers to it are
+ // cleared first. So the image data leaves the list now, before a discard can look at those clients, instead of
+ // when it is swept.
+ leave_discardable_frames();
+}
+
+void BitmapDecodedImageData::leave_discardable_frames() const
+{
+ if (!m_discardable_frame_list_node.is_in_list())
+ return;
+ s_discardable_frame_bytes -= m_frame->bitmap().data_size();
+ m_discardable_frame_list_node.remove();
+}
+
+void BitmapDecodedImageData::did_decode_frame() const
+{
+ VERIFY(m_frame.has_value());
+ VERIFY(!m_discardable_frame_list_node.is_in_list());
+ discardable_frames().append(const_cast<BitmapDecodedImageData&>(*this));
+ s_discardable_frame_bytes += m_frame->bitmap().data_size();
+ if (s_discardable_frame_bytes > discardable_frame_budget)
+ schedule_discard_of_idle_frames(frame_idle_time_before_discard);
+}
+
+void BitmapDecodedImageData::discard_frame() const
+{
+ VERIFY(m_discardable_frame_list_node.is_in_list());
+ leave_discardable_frames();
+ m_frame.clear();
+}
+
+void BitmapDecodedImageData::schedule_discard_of_idle_frames(AK::Duration delay)
+{
+ static auto* timer = &Core::Timer::create_single_shot(frame_idle_time_before_discard, [] {
+ discard_idle_frames();
+ }).leak_ref();
+ // NB: A discard that is due sooner than the one already scheduled takes its place.
+ auto deadline = MonotonicTime::now_coarse() + delay;
+ if (timer->is_active() && s_next_discard_of_idle_frames <= deadline)
+ return;
+ s_next_discard_of_idle_frames = deadline;
+ timer->start(delay);
+}
+
+void BitmapDecodedImageData::discard_idle_frames()
+{
+ auto now = MonotonicTime::now_coarse();
+ bool has_frames_that_become_idle_later = false;
+ bool has_held_frames = false;
+ for (auto it = discardable_frames().begin(); it != discardable_frames().end() && s_discardable_frame_bytes > discardable_frame_budget;) {
+ auto& image_data = *it;
+ ++it;
+ // NB: The list is in order of last use, so once a frame is in use, all the frames after it are as well.
+ if (now - image_data.m_last_used < frame_idle_time_before_discard) {
+ has_frames_that_become_idle_later = true;
+ break;
+ }
+ // NB: The frame of an image that may be painted is needed by the next paint, which would decode it again. A
+ // bitmap that something else still holds, e.g. a display list or a pending texture upload, would stay in
+ // memory. Discarding either would save nothing.
+ if (image_data.has_clients_that_may_render() || image_data.m_frame->bitmap().ref_count() > 1) {
+ has_held_frames = true;
+ continue;
+ }
+ image_data.discard_frame();
+ }
+ if (s_discardable_frame_bytes <= discardable_frame_budget)
+ return;
+ if (has_frames_that_become_idle_later)
+ schedule_discard_of_idle_frames(frame_idle_time_before_discard);
+ else if (has_held_frames)
+ schedule_discard_of_idle_frames(held_frame_recheck_delay);
+}
+
+size_t BitmapDecodedImageData::discard_all_discardable_frames()
+{
+ size_t count = 0;
+ auto& list = discardable_frames();
+ while (!list.is_empty()) {
+ list.first()->discard_frame();
+ ++count;
+ }
+ return count;
+}
+
+Optional<Gfx::DecodedImageFrame> BitmapDecodedImageData::ensure_frame() const
+{
+ if (m_encoded_data.is_empty())
+ return m_frame;
+
+ auto now = MonotonicTime::now_coarse();
+ m_last_used = now;
+
+ if (m_frame.has_value()) {
+ // NB: Move the frame to the end of the list, which keeps the list in order of last use.
+ auto& self = const_cast<BitmapDecodedImageData&>(*this);
+ m_discardable_frame_list_node.remove();
+ discardable_frames().append(self);
+ return m_frame;
+ }
+
+ // NB: A decode that failed is not tried again until the retry timer fires, so that a frame that cannot be had for a
+ // while does not cost a synchronous decode request on each use.
+ if (m_retry_decoding_again_timer && m_retry_decoding_again_timer->is_active())
+ return {};
+
+ auto decoded_or_error = Platform::ImageCodecPlugin::the().decode_first_frame_synchronously(m_encoded_data);
+ if (decoded_or_error.is_error()) {
+ dbgln("BitmapDecodedImageData: Could not decode discarded frame again: {}", decoded_or_error.error());
+ did_fail_to_decode_again();
+ return {};
+ }
+ auto decoded = decoded_or_error.release_value();
+
+ // NB: The decoder parses untrusted data, so a frame of another size than the first decode gave is not trusted.
+ if (decoded.bitmap->size() != m_size) {
+ dbgln("BitmapDecodedImageData: Frame decoded again has size {}, expected {}", decoded.bitmap->size(), m_size);
+ give_up_decoding_again();
+ return {};
+ }
+
+ m_failed_attempts_to_decode_again = 0;
+ // NB: The pixels are those of the discarded frame, so the frame keeps its id, by which caches may still hold it.
+ m_frame = Gfx::DecodedImageFrame::with_id(m_frame_id, move(decoded.bitmap), move(decoded.color_space));
+ did_decode_frame();
+ return m_frame;
+}
+
+void BitmapDecodedImageData::did_fail_to_decode_again() const
+{
+ if (++m_failed_attempts_to_decode_again >= max_failed_attempts_to_decode_again) {
+ give_up_decoding_again();
+ return;
+ }
+ auto delay = AK::Duration::from_milliseconds(delay_before_decoding_again_after_failure.to_milliseconds() << (m_failed_attempts_to_decode_again - 1));
+ // NB: The image went without its frame, so tell its clients once it may be decoded again, which makes a client
+ // that paints it paint again.
+ if (!m_retry_decoding_again_timer) {
+ m_retry_decoding_again_timer = Core::Timer::create_single_shot(delay, GC::weak_callback(const_cast<BitmapDecodedImageData&>(*this), [](auto& self) {
+ self.notify_clients_did_update();
+ }));
+ }
+ m_retry_decoding_again_timer->start(delay);
+}
+
+void BitmapDecodedImageData::give_up_decoding_again() const
+{
+ // NB: Without its encoded data, the image is one whose frame cannot be decoded again, and it no longer keeps data it
+ // cannot use.
+ m_encoded_data.clear();
+ if (m_retry_decoding_again_timer)
+ m_retry_decoding_again_timer->stop();
+}
+
size_t BitmapDecodedImageData::external_memory_size() const
{
- return m_frame.bitmap().data_size();
+ size_t size = m_encoded_data.capacity();
+ if (m_frame.has_value())
+ size = JS::saturating_add_external_memory_size(size, m_frame->bitmap().data_size());
+ return size;
}
Optional<Gfx::DecodedImageFrame> BitmapDecodedImageData::current_frame(Gfx::IntSize) const
{
- return m_frame;
+ return ensure_frame();
}
Optional<Gfx::DecodedImageFrame> BitmapDecodedImageData::default_frame(Gfx::IntSize) const
{
- return m_frame;
+ return ensure_frame();
}
Optional<CSSPixels> BitmapDecodedImageData::intrinsic_width() const
{
- return m_frame.width();
+ return m_size.width();
}
Optional<CSSPixels> BitmapDecodedImageData::intrinsic_height() const
{
- return m_frame.height();
+ return m_size.height();
}
Optional<CSSPixelFraction> BitmapDecodedImageData::intrinsic_aspect_ratio() const
{
- return CSSPixels(m_frame.width()) / CSSPixels(m_frame.height());
+ return CSSPixels(m_size.width()) / CSSPixels(m_size.height());
}
Optional<Gfx::Color> BitmapDecodedImageData::color_if_single_pixel_bitmap() const
{
- auto const& bitmap = m_frame.bitmap();
- if (bitmap.width() != 1 || bitmap.height() != 1)
+ if (m_size.width() != 1 || m_size.height() != 1)
+ return {};
+ auto frame = ensure_frame();
+ if (!frame.has_value())
return {};
- return bitmap.get_pixel(0, 0);
+ return frame->bitmap().get_pixel(0, 0);
}
Optional<Painting::ImagePaint> BitmapDecodedImageData::image_paint(Painting::ImagePaintRequest const&) const
{
- return Painting::ImagePaint { Painting::ImagePaint::DecodedFrame { .frame = m_frame, .natural_size = m_frame.size() } };
+ auto frame = ensure_frame();
+ if (!frame.has_value())
+ return {};
+ return Painting::ImagePaint { Painting::ImagePaint::DecodedFrame { .frame = frame.release_value(), .natural_size = m_size } };
}
}
diff --git a/Libraries/LibWeb/HTML/BitmapDecodedImageData.h b/Libraries/LibWeb/HTML/BitmapDecodedImageData.h
index 155d252f724..c13c2ae8997 100644
--- a/Libraries/LibWeb/HTML/BitmapDecodedImageData.h
+++ b/Libraries/LibWeb/HTML/BitmapDecodedImageData.h
@@ -6,6 +6,10 @@
#pragma once
+#include <AK/ByteBuffer.h>
+#include <AK/IntrusiveList.h>
+#include <AK/Time.h>
+#include <LibCore/Forward.h>
#include <LibGfx/DecodedImageFrame.h>
#include <LibGfx/Forward.h>
#include <LibWeb/HTML/DecodedImageData.h>
@@ -22,7 +26,9 @@ public:
int duration { 0 };
};
- static ErrorOr<GC::Ref<BitmapDecodedImageData>> create(Vector<Frame>&&, size_t loop_count, bool animated);
+ // With the encoded data the image was decoded from, the decoded frame may be discarded while it is not in use and
+ // decoded again when it is needed.
+ static ErrorOr<GC::Ref<BitmapDecodedImageData>> create(Vector<Frame>&&, size_t loop_count, bool animated, ByteBuffer encoded_data = {});
virtual ~BitmapDecodedImageData() override;
virtual Optional<Gfx::DecodedImageFrame> default_frame(Gfx::IntSize = {}) const override;
@@ -36,12 +42,37 @@ public:
virtual Optional<Painting::ImagePaint> image_paint(Painting::ImagePaintRequest const&) const override;
+ // For tests: discards the frame of every image that can be decoded again, in use or not.
+ static size_t discard_all_discardable_frames();
+
private:
- BitmapDecodedImageData(Gfx::DecodedImageFrame&& frame);
+ BitmapDecodedImageData(Gfx::DecodedImageFrame&& frame, ByteBuffer encoded_data);
+
+ virtual void finalize() override;
virtual size_t external_memory_size() const override;
- Gfx::DecodedImageFrame m_frame;
+ Optional<Gfx::DecodedImageFrame> ensure_frame() const;
+ void did_decode_frame() const;
+ void discard_frame() const;
+ void leave_discardable_frames() const;
+ void did_fail_to_decode_again() const;
+ void give_up_decoding_again() const;
+
+ static void discard_idle_frames();
+ static void schedule_discard_of_idle_frames(AK::Duration delay);
+
+ mutable Optional<Gfx::DecodedImageFrame> m_frame;
+ Gfx::IntSize m_size;
+ mutable ByteBuffer m_encoded_data;
+ u64 m_frame_id { 0 };
+ mutable MonotonicTime m_last_used { MonotonicTime::now_coarse() };
+ mutable u8 m_failed_attempts_to_decode_again { 0 };
+ mutable RefPtr<Core::Timer> m_retry_decoding_again_timer;
+ mutable IntrusiveListNode<BitmapDecodedImageData> m_discardable_frame_list_node;
+
+public:
+ using DiscardableFrameList = IntrusiveList<&BitmapDecodedImageData::m_discardable_frame_list_node>;
};
}
diff --git a/Libraries/LibWeb/HTML/DecodedImageData.cpp b/Libraries/LibWeb/HTML/DecodedImageData.cpp
index 7af7063953c..dd221977469 100644
--- a/Libraries/LibWeb/HTML/DecodedImageData.cpp
+++ b/Libraries/LibWeb/HTML/DecodedImageData.cpp
@@ -42,6 +42,15 @@ Optional<Compositing::DisplayListResource> DecodedImageData::record_display_list
return {};
}
+bool DecodedImageData::has_clients_that_may_render() const
+{
+ for (auto* client : m_clients) {
+ if (client->decoded_image_data_may_be_rendered())
+ return true;
+ }
+ return false;
+}
+
void DecodedImageData::notify_clients_did_update()
{
for (auto* client : m_clients)
diff --git a/Libraries/LibWeb/HTML/DecodedImageData.h b/Libraries/LibWeb/HTML/DecodedImageData.h
index 5ce0eaacdf7..99f79120861 100644
--- a/Libraries/LibWeb/HTML/DecodedImageData.h
+++ b/Libraries/LibWeb/HTML/DecodedImageData.h
@@ -32,6 +32,8 @@ public:
public:
virtual GC::Ptr<DecodedImageData> decoded_image_data() const = 0;
virtual void decoded_image_data_did_update() = 0;
+ // Whether the client may paint the image data, so that its pixels may be needed for the next paint.
+ virtual bool decoded_image_data_may_be_rendered() const { return true; }
protected:
void register_with_decoded_image_data_if_needed();
@@ -65,6 +67,7 @@ public:
virtual Optional<Gfx::Color> color_if_single_pixel_bitmap() const { return {}; }
bool has_clients() const { return !m_clients.is_empty(); }
+ bool has_clients_that_may_render() const;
protected:
DecodedImageData();
diff --git a/Libraries/LibWeb/HTML/HTMLImageElement.h b/Libraries/LibWeb/HTML/HTMLImageElement.h
index ecefb4764af..8b8e87f4f76 100644
--- a/Libraries/LibWeb/HTML/HTMLImageElement.h
+++ b/Libraries/LibWeb/HTML/HTMLImageElement.h
@@ -169,6 +169,7 @@ private:
void record_box_kind();
virtual void decoded_image_data_did_update() override;
+ virtual bool decoded_image_data_may_be_rendered() const override { return has_layout_box(); }
Optional<DOM::DocumentLoadEventDelayer> m_load_event_delayer;
diff --git a/Libraries/LibWeb/HTML/SharedResourceRequest.cpp b/Libraries/LibWeb/HTML/SharedResourceRequest.cpp
index 2d04df074c2..b0f6d9c59b7 100644
--- a/Libraries/LibWeb/HTML/SharedResourceRequest.cpp
+++ b/Libraries/LibWeb/HTML/SharedResourceRequest.cpp
@@ -260,7 +260,11 @@ void SharedResourceRequest::handle_successful_fetch(URL::URL const& url_string,
return;
}
- auto handle_successful_bitmap_decode = [strong_this = GC::Root(*this), image_data_is_cors_cross_origin](Web::Platform::DecodedImage& result) -> ErrorOr<void> {
+ // NB: Keeping the encoded data lets the decoded image data discard its frame while it is not in use. The decode
+ // request copies the bytes before it returns, so the handler can own the buffer they are read from.
+ auto encoded_data = make<ByteBuffer>(move(data));
+ auto encoded_bytes = encoded_data->bytes();
+ 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;
@@ -289,7 +293,7 @@ void SharedResourceRequest::handle_successful_fetch(URL::URL const& url_string,
.duration = static_cast<int>(frame.duration),
});
}
- strong_this->m_image_data = BitmapDecodedImageData::create(move(frames), result.loop_count, result.is_animated).release_value_but_fixme_should_propagate_errors();
+ strong_this->m_image_data = BitmapDecodedImageData::create(move(frames), result.loop_count, result.is_animated, move(*encoded_data)).release_value_but_fixme_should_propagate_errors();
}
strong_this->m_image_data->set_is_cors_cross_origin(image_data_is_cors_cross_origin);
strong_this->handle_successful_resource_load();
@@ -300,7 +304,7 @@ void SharedResourceRequest::handle_successful_fetch(URL::URL const& url_string,
strong_this->handle_failed_fetch();
};
- (void)Web::Platform::ImageCodecPlugin::the().decode_image(data.bytes(), move(handle_successful_bitmap_decode), move(handle_failed_decode));
+ (void)Web::Platform::ImageCodecPlugin::the().decode_image(encoded_bytes, move(handle_successful_bitmap_decode), move(handle_failed_decode));
}
void SharedResourceRequest::handle_failed_fetch()
diff --git a/Libraries/LibWeb/Internals/Internals.cpp b/Libraries/LibWeb/Internals/Internals.cpp
index d60ea95fe30..f8fe1252fb6 100644
--- a/Libraries/LibWeb/Internals/Internals.cpp
+++ b/Libraries/LibWeb/Internals/Internals.cpp
@@ -69,6 +69,7 @@
#include <LibWeb/Geometry/DOMRect.h>
#include <LibWeb/HTML/AnimatedBitmapDecodedImageData.h>
#include <LibWeb/HTML/AutoplaySettings.h>
+#include <LibWeb/HTML/BitmapDecodedImageData.h>
#include <LibWeb/HTML/BrowsingContext.h>
#include <LibWeb/HTML/EventLoop/EventLoop.h>
#include <LibWeb/HTML/EventLoop/TaskQueue.h>
@@ -418,6 +419,11 @@ void Internals::gc_async(GC::Ref<WebIDL::Promise> promise)
});
}
+WebIDL::UnsignedLongLong Internals::discard_decoded_image_frames()
+{
+ return HTML::BitmapDecodedImageData::discard_all_discardable_frames();
+}
+
WebIDL::ExceptionOr<void> Internals::mark_as_garbage(Utf16String const& variable_name)
{
auto& vm = window().principal_realm().vm();
diff --git a/Libraries/LibWeb/Internals/Internals.h b/Libraries/LibWeb/Internals/Internals.h
index 324b87ee405..6a20da232ec 100644
--- a/Libraries/LibWeb/Internals/Internals.h
+++ b/Libraries/LibWeb/Internals/Internals.h
@@ -72,6 +72,7 @@ public:
void gc();
void gc_async(GC::Ref<WebIDL::Promise>);
+ WebIDL::UnsignedLongLong discard_decoded_image_frames();
WebIDL::ExceptionOr<void> mark_as_garbage(Utf16String const& variable_name);
bool wrapper_is_preserved(JS::Object&);
bool has_activity_root(JS::Object&);
diff --git a/Libraries/LibWeb/Internals/Internals.idl b/Libraries/LibWeb/Internals/Internals.idl
index c59f6cd4466..a6fe6846c08 100644
--- a/Libraries/LibWeb/Internals/Internals.idl
+++ b/Libraries/LibWeb/Internals/Internals.idl
@@ -30,6 +30,8 @@ interface Internals {
undefined gc();
[CreatesPromise] Promise<undefined> gcAsync();
+ // Discards every decoded image frame that can be decoded again, and returns how many were discarded.
+ unsigned long long discardDecodedImageFrames();
// Clears a named environment binding and forces its current cell to be treated as garbage.
// This does not work for values stored only in optimized locals or registers.
undefined markAsGarbage(DOMString variableName);
diff --git a/Libraries/LibWeb/Platform/ImageCodecPlugin.h b/Libraries/LibWeb/Platform/ImageCodecPlugin.h
index 682f2304684..002838f443d 100644
--- a/Libraries/LibWeb/Platform/ImageCodecPlugin.h
+++ b/Libraries/LibWeb/Platform/ImageCodecPlugin.h
@@ -31,6 +31,11 @@ struct DecodedImage {
i64 session_id { 0 };
};
+struct DecodedFirstFrame {
+ NonnullRefPtr<Gfx::Bitmap> bitmap;
+ Gfx::ColorSpace color_space;
+};
+
class WEB_API ImageCodecPlugin {
public:
static ImageCodecPlugin& the();
@@ -41,6 +46,10 @@ public:
virtual NonnullRefPtr<Core::Promise<DecodedImage>> decode_image(ReadonlyBytes, ESCAPING Function<ErrorOr<void>(DecodedImage&)> on_resolved, ESCAPING Function<void(Error&)> on_rejected) = 0;
+ // Decodes the first frame of an image while the caller waits, for a caller that needs the pixels of an image it
+ // 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;
diff --git a/Libraries/LibWeb/Platform/RemoteImageCodecPlugin.cpp b/Libraries/LibWeb/Platform/RemoteImageCodecPlugin.cpp
index 33c261b5c9c..adacd0fb3c3 100644
--- a/Libraries/LibWeb/Platform/RemoteImageCodecPlugin.cpp
+++ b/Libraries/LibWeb/Platform/RemoteImageCodecPlugin.cpp
@@ -77,6 +77,14 @@ NonnullRefPtr<Core::Promise<DecodedImage>> RemoteImageCodecPlugin::decode_image(
return promise;
}
+ErrorOr<DecodedFirstFrame> RemoteImageCodecPlugin::decode_first_frame_synchronously(ReadonlyBytes bytes)
+{
+ if (!m_client)
+ return Error::from_string_literal("ImageDecoderClient is disconnected");
+ auto result = TRY(m_client->decode_first_frame_synchronously(bytes));
+ return DecodedFirstFrame { move(result.bitmap), move(result.color_space) };
+}
+
void RemoteImageCodecPlugin::request_animation_frames(i64 session_id, u32 start_frame_index, u32 count)
{
if (m_client)
diff --git a/Libraries/LibWeb/Platform/RemoteImageCodecPlugin.h b/Libraries/LibWeb/Platform/RemoteImageCodecPlugin.h
index 23be46fbd02..ae1e2a98b33 100644
--- a/Libraries/LibWeb/Platform/RemoteImageCodecPlugin.h
+++ b/Libraries/LibWeb/Platform/RemoteImageCodecPlugin.h
@@ -23,6 +23,8 @@ public:
virtual NonnullRefPtr<Core::Promise<DecodedImage>> decode_image(ReadonlyBytes, Function<ErrorOr<void>(DecodedImage&)> on_resolved, Function<void(Error&)> on_rejected) override;
+ 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;
diff --git a/Libraries/LibWeb/SVG/SVGImageElement.h b/Libraries/LibWeb/SVG/SVGImageElement.h
index ca29e235f01..871f9b0c2f9 100644
--- a/Libraries/LibWeb/SVG/SVGImageElement.h
+++ b/Libraries/LibWeb/SVG/SVGImageElement.h
@@ -65,6 +65,7 @@ private:
virtual CSS::ElementBoxKind box_kind() const override;
virtual void decoded_image_data_did_update() override;
+ virtual bool decoded_image_data_may_be_rendered() const override { return has_layout_box(); }
Optional<URL::URL> m_href;
diff --git a/Services/ImageDecoder/ConnectionFromClient.cpp b/Services/ImageDecoder/ConnectionFromClient.cpp
index bdecadec42a..1139d769195 100644
--- a/Services/ImageDecoder/ConnectionFromClient.cpp
+++ b/Services/ImageDecoder/ConnectionFromClient.cpp
@@ -203,6 +203,33 @@ void ConnectionFromClient::decode_image(Core::AnonymousBuffer encoded_buffer, Op
m_pending_jobs.set(request_id, start_decode_image_job(request_id, move(encoded_buffer), ideal_size, move(mime_type)));
}
+Messages::ImageDecoderServer::DecodeFirstFrameSynchronouslyResponse ConnectionFromClient::decode_first_frame_synchronously(Core::AnonymousBuffer encoded_buffer, Optional<ByteString> mime_type)
+{
+ // NB: The client asks for this when it needs the pixels of an image it decoded before and has since discarded, so
+ // it is waiting on the reply and the decode runs right here instead of on the thread pool.
+ if (!encoded_buffer.is_valid())
+ return { Gfx::BitmapSequence {}, Gfx::ColorSpace {} };
+
+ auto decoder_or_error = Gfx::ImageDecoder::try_create_for_raw_bytes(ReadonlyBytes { encoded_buffer.data<u8>(), encoded_buffer.size() }, mime_type);
+ if (decoder_or_error.is_error() || !decoder_or_error.value() || decoder_or_error.value()->frame_count() == 0)
+ return { Gfx::BitmapSequence {}, Gfx::ColorSpace {} };
+ auto decoder = decoder_or_error.release_value();
+
+ auto frame_or_error = decoder->frame(0);
+ if (frame_or_error.is_error())
+ return { Gfx::BitmapSequence {}, Gfx::ColorSpace {} };
+ auto bitmap = frame_or_error.release_value().image;
+ bitmap->set_alpha_type_destructive(Gfx::AlphaType::Premultiplied);
+
+ Gfx::ColorSpace color_space;
+ if (auto maybe_color_space = decoder->color_space(); !maybe_color_space.is_error())
+ color_space = maybe_color_space.release_value();
+
+ Vector<RefPtr<Gfx::Bitmap>> bitmaps;
+ bitmaps.append(move(bitmap));
+ return { Gfx::BitmapSequence { move(bitmaps) }, move(color_space) };
+}
+
void ConnectionFromClient::cancel_decoding(i64 request_id)
{
if (auto job = m_pending_jobs.take(request_id); job.has_value()) {
diff --git a/Services/ImageDecoder/ConnectionFromClient.h b/Services/ImageDecoder/ConnectionFromClient.h
index bc396f590d7..b6c9e5f441b 100644
--- a/Services/ImageDecoder/ConnectionFromClient.h
+++ b/Services/ImageDecoder/ConnectionFromClient.h
@@ -65,6 +65,7 @@ private:
explicit ConnectionFromClient(NonnullOwnPtr<IPC::Transport>);
virtual void decode_image(Core::AnonymousBuffer, Optional<Gfx::IntSize> ideal_size, Optional<ByteString> mime_type, i64 request_id) override;
+ virtual Messages::ImageDecoderServer::DecodeFirstFrameSynchronouslyResponse decode_first_frame_synchronously(Core::AnonymousBuffer, Optional<ByteString> mime_type) override;
virtual void cancel_decoding(i64 request_id) 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;
diff --git a/Services/ImageDecoder/ImageDecoderServer.ipc b/Services/ImageDecoder/ImageDecoderServer.ipc
index b3dfcfc8b28..0cd05534e31 100644
--- a/Services/ImageDecoder/ImageDecoderServer.ipc
+++ b/Services/ImageDecoder/ImageDecoderServer.ipc
@@ -1,10 +1,13 @@
#include <LibCore/AnonymousBuffer.h>
+#include <LibGfx/BitmapSequence.h>
+#include <LibGfx/ColorSpace.h>
#include <LibGfx/Size.h>
endpoint ImageDecoderServer
{
decode_image(Core::AnonymousBuffer data, Optional<Gfx::IntSize> ideal_size, Optional<ByteString> mime_type, i64 request_id) =|
cancel_decoding(i64 request_id) =|
+ decode_first_frame_synchronously(Core::AnonymousBuffer data, Optional<ByteString> mime_type) => (Gfx::BitmapSequence bitmaps, Gfx::ColorSpace color_profile)
request_animation_frames(i64 session_id, u32 start_frame_index, u32 count) =|
stop_animation_decode(i64 session_id) =|
diff --git a/Tests/LibWeb/Crash/HTML/collect-images-with-discardable-frames.html b/Tests/LibWeb/Crash/HTML/collect-images-with-discardable-frames.html
new file mode 100644
index 00000000000..e0a27cf9c3d
--- /dev/null
+++ b/Tests/LibWeb/Crash/HTML/collect-images-with-discardable-frames.html
@@ -0,0 +1,36 @@
+<!DOCTYPE html>
+<html class="test-wait">
+<body>
+<script>
+ // Image data whose decoded frame can be discarded is collected while that frame is still decoded.
+ (async () => {
+ const canvas = document.createElement("canvas");
+ // NB: Only frames of at least 32 KiB can be discarded.
+ canvas.width = 128;
+ canvas.height = 64;
+ const context = canvas.getContext("2d");
+ for (let round = 0; round < 3; ++round) {
+ const iframe = document.createElement("iframe");
+ document.body.appendChild(iframe);
+ const childDocument = iframe.contentDocument;
+ const loads = [];
+ for (let i = 0; i < 8; ++i) {
+ context.fillStyle = `rgb(${round}, ${i}, 0)`;
+ context.fillRect(0, 0, 128, 64);
+ const image = childDocument.createElement("img");
+ image.src = canvas.toDataURL();
+ childDocument.body.appendChild(image);
+ loads.push(new Promise(resolve => {
+ image.onload = resolve;
+ image.onerror = resolve;
+ }));
+ }
+ await Promise.all(loads);
+ iframe.remove();
+ }
+ internals.gc();
+ // A collection first finishes the sweep of the one before it, which destroys the image data.
+ internals.gc();
+ document.documentElement.classList.remove("test-wait");
+ })();
+</script>
diff --git a/Tests/LibWeb/Ref/expected/HTML/discarded-image-frame-repaints-ref.html b/Tests/LibWeb/Ref/expected/HTML/discarded-image-frame-repaints-ref.html
new file mode 100644
index 00000000000..d119c9fd016
--- /dev/null
+++ b/Tests/LibWeb/Ref/expected/HTML/discarded-image-frame-repaints-ref.html
@@ -0,0 +1,6 @@
+<!DOCTYPE html>
+<style>
+ body { margin: 0; }
+ img { position: relative; left: 10px; }
+</style>
+<img src="../../../Assets/120.png">
diff --git a/Tests/LibWeb/Ref/input/HTML/discarded-image-frame-repaints.html b/Tests/LibWeb/Ref/input/HTML/discarded-image-frame-repaints.html
new file mode 100644
index 00000000000..f22149aa425
--- /dev/null
+++ b/Tests/LibWeb/Ref/input/HTML/discarded-image-frame-repaints.html
@@ -0,0 +1,21 @@
+<!DOCTYPE html>
+<html class="reftest-wait">
+<link rel="match" href="../../expected/HTML/discarded-image-frame-repaints-ref.html" />
+<style>
+ body { margin: 0; }
+ img { position: relative; left: 0; }
+</style>
+<img id="image" src="../../../Assets/120.png">
+<script>
+ // An image that is painted again after its decoded frame was discarded is decoded again for the paint.
+ const nextFrame = () => new Promise(resolve => requestAnimationFrame(resolve));
+ window.onload = async () => {
+ await nextFrame();
+ await nextFrame();
+ internals.discardDecodedImageFrames();
+ document.getElementById("image").style.left = "10px";
+ await nextFrame();
+ await nextFrame();
+ document.documentElement.classList.remove("reftest-wait");
+ };
+</script>
diff --git a/Tests/LibWeb/TestFaviconDecoding.cpp b/Tests/LibWeb/TestFaviconDecoding.cpp
index bc708b8b8a1..f499efbd3e7 100644
--- a/Tests/LibWeb/TestFaviconDecoding.cpp
+++ b/Tests/LibWeb/TestFaviconDecoding.cpp
@@ -33,6 +33,7 @@ public:
return promise;
}
+ 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(); }
diff --git a/Tests/LibWeb/Text/expected/HTML/discarded-image-frame-is-decoded-again.txt b/Tests/LibWeb/Text/expected/HTML/discarded-image-frame-is-decoded-again.txt
new file mode 100644
index 00000000000..29fd1cfe78b
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/HTML/discarded-image-frame-is-decoded-again.txt
@@ -0,0 +1,5 @@
+discarded at least one frame: true
+natural size after discard: 128x64
+left pixel: 255,0,0,255
+right pixel: 0,0,255,255
+frame decoded again can be discarded again: true
diff --git a/Tests/LibWeb/Text/input/HTML/discarded-image-frame-is-decoded-again.html b/Tests/LibWeb/Text/input/HTML/discarded-image-frame-is-decoded-again.html
new file mode 100644
index 00000000000..2e81cf0cff3
--- /dev/null
+++ b/Tests/LibWeb/Text/input/HTML/discarded-image-frame-is-decoded-again.html
@@ -0,0 +1,40 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<body>
+<script>
+ // A decoded image frame that is discarded to save memory is decoded again, with the same pixels, when it is used.
+ promiseTest(async () => {
+ const source = document.createElement("canvas");
+ // NB: Only frames of at least 32 KiB can be discarded.
+ source.width = 128;
+ source.height = 64;
+ const sourceContext = source.getContext("2d");
+ sourceContext.fillStyle = "rgb(255, 0, 0)";
+ sourceContext.fillRect(0, 0, 64, 64);
+ sourceContext.fillStyle = "rgb(0, 0, 255)";
+ sourceContext.fillRect(64, 0, 64, 64);
+
+ const image = document.createElement("img");
+ image.src = source.toDataURL("image/png");
+ document.body.appendChild(image);
+ await new Promise((resolve, reject) => {
+ image.onload = resolve;
+ image.onerror = () => reject(new Error("Failed to load image"));
+ });
+
+ println(`discarded at least one frame: ${internals.discardDecodedImageFrames() > 0}`);
+ println(`natural size after discard: ${image.naturalWidth}x${image.naturalHeight}`);
+
+ const target = document.createElement("canvas");
+ target.width = 128;
+ target.height = 64;
+ const targetContext = target.getContext("2d");
+ targetContext.drawImage(image, 0, 0);
+ const left = targetContext.getImageData(0, 0, 1, 1).data;
+ const right = targetContext.getImageData(127, 63, 1, 1).data;
+ println(`left pixel: ${left[0]},${left[1]},${left[2]},${left[3]}`);
+ println(`right pixel: ${right[0]},${right[1]},${right[2]},${right[3]}`);
+
+ println(`frame decoded again can be discarded again: ${internals.discardDecodedImageFrames() > 0}`);
+ });
+</script>