Truly independent web browser
LibGfx+LibWeb: Read canvas pixels back as image frames
Aliaksandr Kalenik807e14a07e28
diff --git a/Libraries/LibCompositing/Rust/src/display_list/canvas_2d_recorder.rs b/Libraries/LibCompositing/Rust/src/display_list/canvas_2d_recorder.rsindex 25be0e9e3bd..216bb5efe31 100644--- a/Libraries/LibCompositing/Rust/src/display_list/canvas_2d_recorder.rs+++ b/Libraries/LibCompositing/Rust/src/display_list/canvas_2d_recorder.rs@@ -42,11 +42,10 @@ pub enum ColorSpace {pub trait Transport {/// A Gfx::Font, lent to the call that takes it.type Font: ?Sized;- /// A Gfx::DecodedImageFrame, lent to the call that takes it.- type ImageFrame: ?Sized;+ /// A Gfx::DecodedImageFrame.+ type ImageFrame;/// A Compositing::VideoFrameHold, lent to the call that takes it.type VideoFrameHold: ?Sized;- type Bitmap;fn create_context(&self, size: IntSize, alpha: bool, will_read_frequently: bool, color_space: ColorSpace) -> bool;fn canvas_id(&self) -> Option<CanvasId>;@@ -64,7 +63,12 @@ pub trait Transport {fn flush(&self);/// Unpremultiplied pixels come back as RGBA8888, premultiplied pixels as BGRA8888, in the color space.- fn read_back_pixels(&self, rect: IntRect, alpha_type: AlphaType, color_space: ColorSpace) -> Option<Self::Bitmap>;+ fn read_back_pixels(+ &self,+ rect: IntRect,+ alpha_type: AlphaType,+ color_space: ColorSpace,+ ) -> Option<Self::ImageFrame>;}pub struct Recorder<T: Transport> {@@ -103,7 +107,12 @@ impl<T: Transport> Recorder<T> {self.transport.flush();}- pub fn read_back_pixels(&self, rect: IntRect, alpha_type: AlphaType, color_space: ColorSpace) -> Option<T::Bitmap> {+ pub fn read_back_pixels(+ &self,+ rect: IntRect,+ alpha_type: AlphaType,+ color_space: ColorSpace,+ ) -> Option<T::ImageFrame> {self.transport.read_back_pixels(rect, alpha_type, color_space)}@@ -263,10 +272,12 @@ mod tests {RetainVideoFrameHold(u32),Present,Flush,+ ReadBackPixels(IntRect),}- // Plays the stream: a font and an image frame are their ids, a video frame hold is a number, and a bitmap is the- // rect it was read back from.+ const ID_OF_FRAME_READ_BACK: u64 = 7;++ // Plays the stream: a font and an image frame are their ids, and a video frame hold is a number.#[derive(Default)]struct FakeTransport {events: RefCell<Vec<Event>>,@@ -278,7 +289,6 @@ mod tests {type Font = u64;type ImageFrame = u64;type VideoFrameHold = u32;- type Bitmap = IntRect;fn create_context(&self,@@ -333,8 +343,9 @@ mod tests {self.pending_command_count.set(0);}- fn read_back_pixels(&self, rect: IntRect, _alpha_type: AlphaType, _color_space: ColorSpace) -> Option<IntRect> {- Some(rect)+ fn read_back_pixels(&self, rect: IntRect, _alpha_type: AlphaType, _color_space: ColorSpace) -> Option<u64> {+ self.events.borrow_mut().push(Event::ReadBackPixels(rect));+ Some(ID_OF_FRAME_READ_BACK)}}@@ -435,9 +446,12 @@ mod tests {let rect = IntRect::new(1, 1, 1, 1);assert_eq!(recorder.read_back_pixels(rect, AlphaType::Premultiplied, ColorSpace::Srgb),- Some(rect)+ Some(ID_OF_FRAME_READ_BACK));recorder.destroy_context();- assert_eq!(*recorder.transport.events.borrow(), [Event::Present, Event::Flush]);+ assert_eq!(+ *recorder.transport.events.borrow(),+ [Event::Present, Event::Flush, Event::ReadBackPixels(rect)]+ );}}diff --git a/Libraries/LibGfx/DecodedImageFrame.cpp b/Libraries/LibGfx/DecodedImageFrame.cppindex c3417f0753c..01b2cc10bc1 100644--- a/Libraries/LibGfx/DecodedImageFrame.cpp+++ b/Libraries/LibGfx/DecodedImageFrame.cpp@@ -16,6 +16,9 @@ void* ladybird_gfx_decoded_image_frame_retain(void const*, Gfx::FFI::FfiImageFravoid ladybird_gfx_decoded_image_frame_release(void*);}+static_assert(to_underlying(Gfx::BitmapFormat::RGBA8888) == 4);+static_assert(to_underlying(Gfx::AlphaType::Unpremultiplied) == 1);+extern "C" void* ladybird_gfx_decoded_image_frame_retain(void const* frame, Gfx::FFI::FfiImageFrameSnapshot* out_snapshot){VERIFY(frame);@@ -25,6 +28,9 @@ extern "C" void* ladybird_gfx_decoded_image_frame_retain(void const* frame, Gfx:.id = typed_frame.id(),.width = typed_frame.width(),.height = typed_frame.height(),+ .bitmap_format_value = to_underlying(typed_frame.format()),+ .alpha_type_value = to_underlying(typed_frame.alpha_type()),+ .pixels = typed_frame.pixels().data(),};return new Gfx::DecodedImageFrame(typed_frame);}diff --git a/Libraries/LibGfx/DecodedImageFrame.h b/Libraries/LibGfx/DecodedImageFrame.hindex 059c69afb6c..889c11733be 100644--- a/Libraries/LibGfx/DecodedImageFrame.h+++ b/Libraries/LibGfx/DecodedImageFrame.h@@ -38,6 +38,13 @@ public:return frame;}+ DecodedImageFrame with_pixels_reinterpreted_in(ColorSpace color_space) const+ {+ auto frame = with_new_id();+ frame.m_color_space = move(color_space);+ return frame;+ }+ColorSpace const& color_space() const { return m_color_space; }u64 id() const { return m_id; }diff --git a/Libraries/LibGfx/Rust/src/image_frame.rs b/Libraries/LibGfx/Rust/src/image_frame.rsindex e7181b911fd..131a76c3e4b 100644--- a/Libraries/LibGfx/Rust/src/image_frame.rs+++ b/Libraries/LibGfx/Rust/src/image_frame.rs@@ -17,13 +17,33 @@ unsafe extern "C" {}#[repr(C)]-#[derive(Clone, Copy, Debug, Default)]+#[derive(Clone, Copy, Debug)]pub struct FfiImageFrameSnapshot {pub id: u64,pub width: i32,pub height: i32,+ pub bitmap_format_value: i32,+ pub alpha_type_value: i32,+ pub pixels: *const u8,}+impl Default for FfiImageFrameSnapshot {+ fn default() -> Self {+ Self {+ id: 0,+ width: 0,+ height: 0,+ bitmap_format_value: 0,+ alpha_type_value: 0,+ pixels: std::ptr::null(),+ }+ }+}++const BYTES_PER_PIXEL: usize = 4;+const BITMAP_FORMAT_VALUE_OF_RGBA8888: i32 = 4;+const ALPHA_TYPE_VALUE_OF_UNPREMULTIPLIED: i32 = 1;+struct ImageFrameEntry {snapshot: FfiImageFrameSnapshot,raw: NonNull<c_void>,@@ -88,10 +108,49 @@ impl ImageFrameHandle {self.0.snapshot.height}+ #[inline]+ pub fn bitmap_format_value(&self) -> i32 {+ self.0.snapshot.bitmap_format_value+ }++ #[inline]+ pub fn alpha_type_value(&self) -> i32 {+ self.0.snapshot.alpha_type_value+ }++ #[inline]+ pub fn has_unpremultiplied_rgba8888_pixels(&self) -> bool {+ self.bitmap_format_value() == BITMAP_FORMAT_VALUE_OF_RGBA8888+ && self.alpha_type_value() == ALPHA_TYPE_VALUE_OF_UNPREMULTIPLIED+ }++ #[inline]+ pub fn pitch(&self) -> usize {+ usize::try_from(self.width()).expect("a frame has a width") * BYTES_PER_PIXEL+ }++ #[inline]+ pub fn size_in_bytes(&self) -> usize {+ self.pitch() * usize::try_from(self.height()).expect("a frame has a height")+ }++ /// The first of `size_in_bytes()` bytes of pixels, in rows `pitch()` bytes apart, which the handle keeps mapped.+ #[inline]+ pub fn pixels(&self) -> NonNull<u8> {+ NonNull::new(self.0.snapshot.pixels.cast_mut()).expect("a frame has pixels")+ }+#[inline]pub fn as_raw(&self) -> *const c_void {self.0.raw.as_ptr()}++ /// A copy of the frame that C++ allocates with `new` and takes over: the opposite of `adopt`.+ pub fn hand_over_copy(&self) -> *mut c_void {+ let mut snapshot_of_the_copy = self.0.snapshot;+ // SAFETY: The handle keeps the frame live, and the out-pointer addresses a local.+ unsafe { ladybird_gfx_decoded_image_frame_retain(self.as_raw(), &raw mut snapshot_of_the_copy) }+ }}impl PartialEq for ImageFrameHandle {diff --git a/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/context.rs b/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/context.rsindex 9bc90dbc498..598d1dad9da 100644--- a/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/context.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/context.rs@@ -10,20 +10,20 @@use core::cell::{Cell, Ref as CellRef, RefCell, RefMut};use core::marker::PhantomData;use core::ops::Deref;-use core::ptr::NonNull;use ak::Utf16String;use ak::math;use libcompositing_rust::display_list::canvas_2d::{Compositing, Paint, Stroke};use libcompositing_rust::display_list::canvas_2d_recorder::{AlphaType, ColorSpace, Recorder};use libcompositing_rust::display_list::commands::{Canvas2DShadow, CanvasId};+use libgfx_rust::image_frame::ImageFrameHandle;use libgfx_rust::path::Path;use libgfx_rust::{AffineTransform, Color, CompositingAndBlendingOperator, FloatRect, IntRect, IntSize, WindingRule};use libjs_rust::api::{DeferGc, ForeignCellSlot, Gc, GcRefCell, GcRefMut, Realm, Trace, Visitor, Vm};use super::canvas::{Canvas, FontMetricsSource, FontSelection, ResolvedFont, StyleValue, parse_color};use super::drawing_state::{CanvasColor, DrawingState, FillOrStrokeStyle};-use super::host::{Bitmap, CppTransport, LentImageFrame};+use super::host::CppTransport;use crate::bindings::interface::Wrappable;use crate::html::canvas_rendering_context2d::CanvasDirection;use crate::html::canvas_rendering_context2d_settings::CanvasRenderingContext2DSettings;@@ -104,7 +104,7 @@ impl Drop for BackingStorage {/// A readback of the pixels of a rectangle of the canvas.#[derive(Clone)]struct CachedReadback {- pixels: Bitmap,+ pixels: ImageFrameHandle,rect: IntRect,alpha_type: AlphaType,color_space: ColorSpace,@@ -182,10 +182,7 @@ pub(crate) fn paint_of<'a>(// SAFETY: Nothing adds a stop to the gradient while the recorder records the paint.FillOrStrokeStyle::Gradient(gradient) => unsafe { gradient.paint_unguarded(color_space) },FillOrStrokeStyle::Pattern(pattern) => Paint::Pattern {- image: pattern.image().map(|frame| {- let frame = NonNull::new(frame.as_raw().cast_mut()).expect("an image frame has a frame");- recorder.add_image_frame(&LentImageFrame(frame))- }),+ image: pattern.image().map(|frame| recorder.add_image_frame(frame)),repetition: pattern.repetition(),transform: pattern.transform(),},@@ -423,7 +420,12 @@ impl ContextState {/// The pixels of the rectangle of the canvas, read back from the Compositor and converted to the color space./// Unpremultiplied pixels come back as RGBA8888, and premultiplied pixels as BGRA8888.- pub(crate) fn read_pixels(&self, rect: IntRect, alpha_type: AlphaType, color_space: ColorSpace) -> Option<Bitmap> {+ pub(crate) fn read_pixels(+ &self,+ rect: IntRect,+ alpha_type: AlphaType,+ color_space: ColorSpace,+ ) -> Option<ImageFrameHandle> {if !self.has_backing_storage() {return None;}diff --git a/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/exports.rsindex 23fc926400c..429db98991e 100644--- a/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/exports.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/exports.rs@@ -174,8 +174,8 @@ pub extern "C" fn web_canvas_2d_context_color_space(context: &ContextCell) -> Cowith_context(context, |context| context.context_attributes.color_space.into())}-/// A Gfx::Bitmap with a reference that the caller takes over, or null. Unpremultiplied pixels come back as RGBA8888,-/// and premultiplied pixels as BGRA8888, in the color space.+/// A Gfx::DecodedImageFrame allocated with new that the caller takes over, or null. Unpremultiplied pixels come back+/// as RGBA8888, and premultiplied pixels as BGRA8888, in the color space.#[unsafe(no_mangle)]pub extern "C" fn web_canvas_2d_context_read_pixels(context: &ContextCell,@@ -184,7 +184,7 @@ pub extern "C" fn web_canvas_2d_context_read_pixels(color_space: ColorSpace,) -> *mut c_void {with_context(context, |context| context.read_pixels(rect, alpha_type, color_space))- .map_or(core::ptr::null_mut(), super::host::Bitmap::into_raw)+ .map_or(core::ptr::null_mut(), |frame| frame.hand_over_copy())}#[unsafe(no_mangle)]diff --git a/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/host.rs b/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/host.rsindex 8fbaeab8c9c..69ead4a2f6c 100644--- a/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/host.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/host.rs@@ -43,101 +43,14 @@ unsafe extern "C" {alpha_type: AlphaType,color_space: ColorSpace,) -> *mut c_void;- fn web_canvas_2d_bitmap_ref(bitmap: *mut c_void);- fn web_canvas_2d_bitmap_unref(bitmap: *mut c_void);- fn web_canvas_2d_bitmap_size_in_bytes(bitmap: *mut c_void) -> usize;- fn web_canvas_2d_image_frame_from_bitmap(bitmap: *mut c_void, color_space: ColorSpace) -> *mut c_void;- fn web_canvas_2d_bitmap_unpremultiplied_rgba_pixels(- bitmap: *mut c_void,- out_pixels: *mut *const u8,- out_pitch: *mut usize,- out_width: *mut i32,- out_height: *mut i32,- ) -> bool;}/// A Gfx::Font that C++ lends.pub(crate) struct LentFont(pub(crate) NonNull<c_void>);-/// A Gfx::DecodedImageFrame that C++ lends.-pub(crate) struct LentImageFrame(pub(crate) NonNull<c_void>);-/// A Compositing::VideoFrameHold that C++ lends.pub(crate) struct LentVideoFrameHold(pub(crate) NonNull<c_void>);-/// A Gfx::Bitmap, one reference to which the value owns.-pub(crate) struct Bitmap(NonNull<c_void>);--/// The pixels of a bitmap that are RGBA8888 and unpremultiplied, as a readback of a canvas gives them: `height` rows of-/// `width` pixels, `pitch` bytes apart.-pub(crate) struct UnpremultipliedRgbaPixels {- pub(crate) first_row: NonNull<u8>,- pub(crate) pitch: usize,- pub(crate) width: i32,- pub(crate) height: i32,-}--// SAFETY (of every call below): The value owns a reference to the bitmap.-impl Bitmap {- pub(crate) fn into_raw(self) -> *mut c_void {- let bitmap = self.0.as_ptr();- core::mem::forget(self);- bitmap- }-- /// A frame of the pixels of the bitmap, which are in the color space, or none if one cannot be made.- pub(crate) fn into_image_frame(self, color_space: ColorSpace) -> Option<ImageFrameHandle> {- let frame = unsafe { web_canvas_2d_image_frame_from_bitmap(self.into_raw(), color_space) };- if frame.is_null() {- return None;- }- // SAFETY: LibWeb hands over a frame that it allocated with new.- Some(unsafe { ImageFrameHandle::adopt(frame) })- }-- pub(crate) fn size_in_bytes(&self) -> usize {- unsafe { web_canvas_2d_bitmap_size_in_bytes(self.0.as_ptr()) }- }-- /// The pixels, which stay valid while the value lives, if the bitmap is RGBA8888 and unpremultiplied.- pub(crate) fn unpremultiplied_rgba_pixels(&self) -> Option<UnpremultipliedRgbaPixels> {- let (mut first_row, mut pitch, mut width, mut height) = (core::ptr::null(), 0, 0, 0);- let is_rgba = unsafe {- web_canvas_2d_bitmap_unpremultiplied_rgba_pixels(- self.0.as_ptr(),- &raw mut first_row,- &raw mut pitch,- &raw mut width,- &raw mut height,- )- };- if !is_rgba {- return None;- }- Some(UnpremultipliedRgbaPixels {- first_row: NonNull::new(first_row.cast_mut()).expect("a bitmap has pixels"),- pitch,- width,- height,- })- }-}--impl Clone for Bitmap {- fn clone(&self) -> Self {- // SAFETY: The value owns a reference to the bitmap, so it is live.- unsafe { web_canvas_2d_bitmap_ref(self.0.as_ptr()) };- Self(self.0)- }-}--impl Drop for Bitmap {- fn drop(&mut self) {- // SAFETY: The value owns one reference to the bitmap.- unsafe { web_canvas_2d_bitmap_unref(self.0.as_ptr()) };- }-}-pub(crate) struct CppTransport(NonNull<c_void>);impl CppTransport {@@ -164,9 +77,8 @@ impl Drop for CppTransport {// video frame hold passed are lent for the call.impl Transport for CppTransport {type Font = LentFont;- type ImageFrame = LentImageFrame;+ type ImageFrame = ImageFrameHandle;type VideoFrameHold = LentVideoFrameHold;- type Bitmap = Bitmap;fn create_context(&self, size: IntSize, alpha: bool, will_read_frequently: bool, color_space: ColorSpace) -> bool {unsafe {@@ -198,8 +110,8 @@ impl Transport for CppTransport {FontResourceId(unsafe { web_canvas_2d_transport_add_font(self.as_ptr(), font.0.as_ptr()) })}- fn add_image_frame(&self, frame: &LentImageFrame) -> ImageFrameResourceId {- ImageFrameResourceId(unsafe { web_canvas_2d_transport_add_image_frame(self.as_ptr(), frame.0.as_ptr()) })+ fn add_image_frame(&self, frame: &ImageFrameHandle) -> ImageFrameResourceId {+ ImageFrameResourceId(unsafe { web_canvas_2d_transport_add_image_frame(self.as_ptr(), frame.as_raw()) })}fn retain_video_frame_hold(&self, hold: &LentVideoFrameHold) {@@ -218,8 +130,13 @@ impl Transport for CppTransport {unsafe { web_canvas_2d_transport_flush(self.as_ptr()) };}- fn read_back_pixels(&self, rect: IntRect, alpha_type: AlphaType, color_space: ColorSpace) -> Option<Bitmap> {- let bitmap = unsafe {+ fn read_back_pixels(+ &self,+ rect: IntRect,+ alpha_type: AlphaType,+ color_space: ColorSpace,+ ) -> Option<ImageFrameHandle> {+ let frame = unsafe {web_canvas_2d_transport_read_back_pixels(self.as_ptr(),rect.x,@@ -230,6 +147,7 @@ impl Transport for CppTransport {color_space,)};- NonNull::new(bitmap).map(Bitmap)+ // SAFETY: LibWeb hands over a frame that it allocated with new, or null.+ (!frame.is_null()).then(|| unsafe { ImageFrameHandle::adopt(frame) })}}diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/canvas_draw_image.rs b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_draw_image.rsindex bc1dd87da4b..9e2ccd31a48 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/canvas_draw_image.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_draw_image.rs@@ -6,8 +6,6 @@//! https://html.spec.whatwg.org/multipage/canvas.html#canvasdrawimage-use core::ptr::NonNull;-use ak::Utf16String;use libcompositing_rust::display_list::commands::CanvasId;use libgfx_rust::image_frame::ImageFrameHandle;@@ -20,7 +18,7 @@ use crate::bindings::{CallContext, Exception, WebIdlResult};use crate::canvas_2d::canvas::{CanvasImageSourceKind, Usability, capture_video_frame};use crate::canvas_2d::context::{CanvasKind, ContextState, RenderingContext2D};use crate::canvas_2d::float;-use crate::canvas_2d::host::{LentImageFrame, LentVideoFrameHold};+use crate::canvas_2d::host::LentVideoFrameHold;/// The union CanvasImageSource of HTML/Canvas/CanvasDrawImage.idl, whose members the bindings convert.#[derive(Clone, Copy)]@@ -321,7 +319,6 @@ impl ContextState {// only afterwards.if self.recorder_is_ready() {let state = self.drawing_state();- let frame = LentImageFrame(NonNull::new(frame.as_raw().cast_mut()).expect("an image frame has a frame"));self.record(|recorder| {recorder.draw_image_frame(&frame,diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/canvas_image_data.rs b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_image_data.rsindex 94d8734923c..9dff4b9319c 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/canvas_image_data.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_image_data.rs@@ -22,7 +22,6 @@ use crate::bindings::interface::Ref;use crate::bindings::{CallContext, Exception, WebIdlResult};use crate::canvas_2d::canvas::image_frame_from_pixels;use crate::canvas_2d::context::{CanvasKind, ContextState, RenderingContext2D};-use crate::canvas_2d::host::LentImageFrame;/// The size of a pixel of an ImageData and of a readback, whose pixels are RGBA8888.const BYTES_PER_PIXEL: usize = 4;@@ -180,10 +179,9 @@ impl ContextState {.into());};- let lent_frame = LentImageFrame(NonNull::new(frame.as_raw().cast_mut()).expect("an image frame has a frame"));self.record(|recorder| {recorder.put_image_frame(- &lent_frame,+ &frame,IntPoint {x: destination_rect.x,y: destination_rect.y,@@ -318,10 +316,10 @@ impl<K: CanvasKind> RenderingContext2D<K> {// source rectangle in the bitmap's coordinate space units, converted from this's color space to imageData's// colorSpace using 'relative-colorimetric' rendering intent.// NB: The pixels of imageData are RGBA8888 and unpremultiplied.- let Some(readback_pixels) = readback.unpremultiplied_rgba_pixels() else {+ if !readback.has_unpremultiplied_rgba8888_pixels() {return Ok(image_data);- };- if readback_pixels.width != readback_rect.width || readback_pixels.height != readback_rect.height {+ }+ if readback.width() != readback_rect.width || readback.height() != readback_rect.height {return Ok(image_data);}let image_data_pixels = image_data.pixels().expect("a new ImageData has room for its pixels");@@ -334,12 +332,12 @@ impl<K: CanvasKind> RenderingContext2D<K> {let rows = to_usize(i64::from(readback_rect.height));assert!(destination_x * BYTES_PER_PIXEL + row_size <= destination_pitch);assert!(destination_y + rows <= height as usize);- assert!(row_size <= readback_pixels.pitch);+ assert!(row_size <= readback.pitch());for row in 0..rows {// SAFETY: The row is inside both the readback and the pixels of the new ImageData, as asserted above, and// the two do not overlap.unsafe {- let source = readback_pixels.first_row.as_ptr().add(row * readback_pixels.pitch);+ let source = readback.pixels().as_ptr().add(row * readback.pitch());let destination = image_data_pixels.as_ptr().add((destination_y + row) * destination_pitch + destination_x * BYTES_PER_PIXEL);diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/canvas_pattern.rs b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_pattern.rsindex 45a3d866a64..c0af67c74ce 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/canvas_pattern.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_pattern.rs@@ -78,9 +78,9 @@ pub(crate) fn read_back_current_video_frame(video: CppInterface, color_space: Co},);recorder.flush();- let bitmap = recorder.read_back_pixels(frame_rect, AlphaType::Premultiplied, color_space);+ let frame = recorder.read_back_pixels(frame_rect, AlphaType::Premultiplied, color_space);recorder.destroy_context();- bitmap?.into_image_frame(color_space)+ frame}#[derive(Trace)]diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/exports.rsindex 7da31075e20..e4a37eefc1b 100644--- a/Libraries/LibWeb/Bindings/Rust/src/web_gl/exports.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/exports.rs@@ -223,7 +223,7 @@ pub extern "C" fn web_webgl_context_clear_drawing_buffer(context: &ContextCell)with_context(context, |context| context.proxy.clear_drawing_buffer());}-/// A Gfx::Bitmap with a reference that the caller takes over, or null.+/// A Gfx::DecodedImageFrame allocated with new that the caller takes over, or null.#[unsafe(no_mangle)]pub extern "C" fn web_webgl_context_read_back_drawing_buffer(context: &ContextCell,@@ -232,10 +232,10 @@ pub extern "C" fn web_webgl_context_read_back_drawing_buffer(width: i32,height: i32,) -> *mut c_void {- let bitmap = with_context(context, |context| {+ let frame = with_context(context, |context| {context.proxy.read_back_drawing_buffer(x, y, width, height)});- bitmap.map_or(core::ptr::null_mut(), super::host::Bitmap::into_raw)+ frame.map_or(core::ptr::null_mut(), |frame| frame.hand_over_copy())}/// False when the context was lost already.diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/host.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/host.rsindex 582e5ae0146..7bbf9b7c3ea 100644--- a/Libraries/LibWeb/Bindings/Rust/src/web_gl/host.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/host.rs@@ -10,6 +10,8 @@use core::ffi::c_void;use core::ptr::{self, NonNull};+use libgfx_rust::image_frame::ImageFrameHandle;+use super::proxy::transport::{ReadPixelsResult, SharedMemory, Transport};unsafe extern "C" {@@ -72,7 +74,6 @@ unsafe extern "C" {safe fn web_webgl_anonymous_buffer_create(size: usize, out_data: &mut *mut u8) -> *mut c_void;fn web_webgl_anonymous_buffer_destroy(anonymous_buffer: *mut c_void);fn web_webgl_frame_destroy(frame: *mut c_void);- fn web_webgl_bitmap_unref(bitmap: *mut c_void);}pub(crate) struct AnonymousBuffer {@@ -125,23 +126,6 @@ impl Drop for Frame {}}-pub(crate) struct Bitmap(NonNull<c_void>);--impl Bitmap {- pub(crate) fn into_raw(self) -> *mut c_void {- let bitmap = self.0.as_ptr();- core::mem::forget(self);- bitmap- }-}--impl Drop for Bitmap {- fn drop(&mut self) {- // SAFETY: The value owns one reference to the bitmap.- unsafe { web_webgl_bitmap_unref(self.0.as_ptr()) };- }-}-pub(crate) struct CppTransport(NonNull<c_void>);impl CppTransport {@@ -180,7 +164,7 @@ unsafe extern "C" fn append_reply(reply_sink: *mut c_void, reply: *const u8, repimpl Transport for CppTransport {type SharedMemory = AnonymousBuffer;type Frame = Frame;- type Bitmap = Bitmap;+ type DrawingBufferPixels = ImageFrameHandle;fn max_frames_per_message(&self) -> usize {web_webgl_max_frames_per_message()@@ -292,8 +276,9 @@ impl Transport for CppTransport {unsafe { web_webgl_transport_read_buffer_sub_data(self.as_ptr(), target, offset, size, data.buffer.as_ptr()) }}- fn read_back_drawing_buffer(&self, x: i32, y: i32, width: i32, height: i32) -> Option<Bitmap> {- let bitmap = unsafe { web_webgl_transport_read_back_drawing_buffer(self.as_ptr(), x, y, width, height) };- NonNull::new(bitmap).map(Bitmap)+ fn read_back_drawing_buffer(&self, x: i32, y: i32, width: i32, height: i32) -> Option<ImageFrameHandle> {+ let frame = unsafe { web_webgl_transport_read_back_drawing_buffer(self.as_ptr(), x, y, width, height) };+ // SAFETY: LibWeb hands over a frame that it allocated with new, or null.+ (!frame.is_null()).then(|| unsafe { ImageFrameHandle::adopt(frame) })}}diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/recorder.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/recorder.rsindex 2037dcf594e..08b2dc21f0e 100644--- a/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/recorder.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/recorder.rs@@ -482,7 +482,13 @@ impl<T: Transport> Proxy<T> {self.transport().clear_drawing_buffer();}- pub(crate) fn read_back_drawing_buffer(&self, x: i32, y: i32, width: i32, height: i32) -> Option<T::Bitmap> {+ pub(crate) fn read_back_drawing_buffer(+ &self,+ x: i32,+ y: i32,+ width: i32,+ height: i32,+ ) -> Option<T::DrawingBufferPixels> {if self.lost.get() {return None;}diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/tests.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/tests.rsindex 59bb123928d..f01dc471b72 100644--- a/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/tests.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/tests.rs@@ -234,7 +234,7 @@ struct MockTransport {impl Transport for MockTransport {type SharedMemory = MockMemory;type Frame = u32;- type Bitmap = (i32, i32, i32, i32);+ type DrawingBufferPixels = (i32, i32, i32, i32);fn max_frames_per_message(&self) -> usize {self.replayer.max_frames_per_message.get()diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/transport.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/transport.rsindex 3b51a137b68..a330d8c7f04 100644--- a/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/transport.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/transport.rs@@ -26,7 +26,7 @@ pub(crate) trait Transport {type SharedMemory: SharedMemory;/// An image that a command names by its position among the frames sent with the commands.type Frame;- type Bitmap;+ type DrawingBufferPixels;fn max_frames_per_message(&self) -> usize;fn create_shared_memory(&self, size: usize) -> Option<Self::SharedMemory>;@@ -67,5 +67,5 @@ pub(crate) trait Transport {pixels: Option<&Self::SharedMemory>,) -> ReadPixelsResult;fn read_buffer_sub_data(&self, target: u32, offset: i64, size: i64, data: &Self::SharedMemory) -> bool;- fn read_back_drawing_buffer(&self, x: i32, y: i32, width: i32, height: i32) -> Option<Self::Bitmap>;+ fn read_back_drawing_buffer(&self, x: i32, y: i32, width: i32, height: i32) -> Option<Self::DrawingBufferPixels>;}diff --git a/Libraries/LibWeb/Compositor/CompositorHost.cpp b/Libraries/LibWeb/Compositor/CompositorHost.cppindex 60efe96ea9e..ff2b9cd6637 100644--- a/Libraries/LibWeb/Compositor/CompositorHost.cpp+++ b/Libraries/LibWeb/Compositor/CompositorHost.cpp@@ -334,14 +334,17 @@ private:m_connection->update_canvas_2d_stream(*m_stream);}- virtual RefPtr<Gfx::Bitmap> read_back_pixels(Gfx::IntRect const& rect, Gfx::AlphaType alpha_type, Gfx::ColorSpace const& color_space) override+ virtual Optional<Gfx::DecodedImageFrame> read_back_pixels(Gfx::IntRect const& rect, Gfx::AlphaType alpha_type, Gfx::ColorSpace const& color_space) override{if (!m_canvas_id.has_value())- return nullptr;+ return {};auto shareable_bitmap = m_connection->get_canvas_pixels(*m_canvas_id, rect, alpha_type, color_space);if (!shareable_bitmap.is_valid())- return nullptr;- return shareable_bitmap.bitmap();+ return {};+ auto frame = Gfx::DecodedImageFrame::create(*shareable_bitmap.bitmap(), color_space);+ if (frame.is_error())+ return {};+ return frame.release_value();}NonnullRefPtr<CompositorConnection> m_connection;diff --git a/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cpp b/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cppindex fd1ac2db445..df6ca5da987 100644--- a/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cpp+++ b/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cpp@@ -258,12 +258,12 @@ Bindings::PredefinedColorSpace Canvas2DContextBase::color_space() constreturn predefined_color_space_from_underlying(web_canvas_2d_context_color_space(cell_of(*this)));}-RefPtr<Gfx::Bitmap> Canvas2DContextBase::read_pixels(Gfx::IntRect const& rect, Gfx::AlphaType alpha_type, Bindings::PredefinedColorSpace color_space)+Optional<Gfx::DecodedImageFrame> Canvas2DContextBase::read_pixels(Gfx::IntRect const& rect, Gfx::AlphaType alpha_type, Bindings::PredefinedColorSpace color_space){- auto* bitmap = static_cast<Gfx::Bitmap*>(web_canvas_2d_context_read_pixels(this, rect, to_underlying(alpha_type), to_underlying(color_space)));- if (!bitmap)- return nullptr;- return adopt_ref(*bitmap);+ auto frame = adopt_own_if_nonnull(static_cast<Gfx::DecodedImageFrame*>(web_canvas_2d_context_read_pixels(this, rect, to_underlying(alpha_type), to_underlying(color_space))));+ if (!frame)+ return {};+ return move(*frame);}bool Canvas2DContextBase::draw_image(ImageBitmap& image_bitmap, float x, float y)diff --git a/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.h b/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.hindex 7f507d413c4..45f2752da4e 100644--- a/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.h+++ b/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.h@@ -12,6 +12,7 @@#include <AK/RefPtr.h>#include <LibCompositing/DisplayList/DisplayListResourceIds.h>#include <LibGfx/Bitmap.h>+#include <LibGfx/DecodedImageFrame.h>#include <LibGfx/Forward.h>#include <LibGfx/Rect.h>#include <LibGfx/Size.h>@@ -49,7 +50,7 @@ public:Bindings::PredefinedColorSpace color_space() const;// The pixels of the rectangle of the output bitmap, converted to the color space.- RefPtr<Gfx::Bitmap> read_pixels(Gfx::IntRect const&, Gfx::AlphaType = Gfx::AlphaType::Premultiplied, Bindings::PredefinedColorSpace = Bindings::PredefinedColorSpace::Srgb);+ Optional<Gfx::DecodedImageFrame> read_pixels(Gfx::IntRect const&, Gfx::AlphaType = Gfx::AlphaType::Premultiplied, Bindings::PredefinedColorSpace = Bindings::PredefinedColorSpace::Srgb);// Draws the ImageBitmap at the point as drawImage() does, and returns whether that threw nothing.bool draw_image(ImageBitmap&, float x, float y);diff --git a/Libraries/LibWeb/HTML/Canvas/CanvasHost.cpp b/Libraries/LibWeb/HTML/Canvas/CanvasHost.cppindex e002627a653..e8e078490ef 100644--- a/Libraries/LibWeb/HTML/Canvas/CanvasHost.cpp+++ b/Libraries/LibWeb/HTML/Canvas/CanvasHost.cpp@@ -10,7 +10,6 @@#include <LibGfx/Rect.h>#include <LibWeb/HTML/Canvas/Canvas2DContextBase.h>#include <LibWeb/HTML/Canvas/CanvasHost.h>-#include <LibWeb/HTML/Canvas/PredefinedColorSpace.h>#include <LibWeb/HTML/Canvas/SerializeBitmap.h>#include <LibWeb/HTML/ImageBitmapRenderingContext.h>#include <LibWeb/WebGL/WebGLRenderingContextBase.h>@@ -38,36 +37,29 @@ Gfx::IntSize CanvasHost::bitmap_size_for_dimensions(u64 width, u64 height)return { static_cast<int>(width), static_cast<int>(height) };}-static RefPtr<Gfx::Bitmap> create_transparent_canvas_bitmap(Gfx::IntSize size)+static Optional<Gfx::DecodedImageFrame> transparent_canvas_frame(Gfx::IntSize size){- auto bitmap_or_error = Gfx::Bitmap::create(Gfx::BitmapFormat::BGRA8888, Gfx::AlphaType::Premultiplied, size);- if (bitmap_or_error.is_error())- return nullptr;- return bitmap_or_error.release_value();-}--static Optional<Gfx::DecodedImageFrame> frame_of_bitmap(Gfx::Bitmap const& bitmap, Gfx::ColorSpace color_space = {})-{- auto frame = Gfx::DecodedImageFrame::create(bitmap, move(color_space));+ auto bitmap = Gfx::Bitmap::create_shareable(Gfx::BitmapFormat::BGRA8888, Gfx::AlphaType::Premultiplied, size);+ if (bitmap.is_error())+ return {};+ auto frame = Gfx::DecodedImageFrame::create(*bitmap.value());if (frame.is_error())return {};return frame.release_value();}-RefPtr<Gfx::Bitmap> CanvasHost::get_bitmap_from_surface()+Optional<Gfx::DecodedImageFrame> CanvasHost::get_srgb_frame_from_surface(){auto const size = bitmap_size_for_canvas();if (size.is_empty())- return nullptr;+ return {};// NB: A blank output bitmap of an ImageBitmapRenderingContext is the transparent bitmap below.if (auto* context = canvas_bitmap_renderer_context(); context && !context->is_blank()) {// FIXME: Convert bitmap data that isn't in the sRGB color space.- if (auto const* frame = context->frame(); frame) {- if (auto bitmap = frame->bitmap_sharing_pixels()->clone(); !bitmap.is_error())- return bitmap.release_value();- }- return nullptr;+ if (auto const* frame = context->frame(); frame)+ return frame->with_pixels_reinterpreted_in({});+ return {};}if (auto* webgl_context = canvas_webgl_context())@@ -75,12 +67,12 @@ RefPtr<Gfx::Bitmap> CanvasHost::get_bitmap_from_surface()if (auto* context = canvas_2d_context()) {context->ensure_backing_storage();- if (auto pixels = context->read_pixels({ {}, size }); pixels && pixels->size() == size)+ if (auto pixels = context->read_pixels({ {}, size }); pixels.has_value() && pixels->size() == size)return pixels;- return nullptr;+ return {};}- return create_transparent_canvas_bitmap(size);+ return transparent_canvas_frame(size);}Optional<Gfx::DecodedImageFrame> CanvasHost::get_frame_from_surface()@@ -97,26 +89,19 @@ Optional<Gfx::DecodedImageFrame> CanvasHost::get_frame_from_surface()if (size.is_empty())return {};context->ensure_backing_storage();- auto color_space = context->color_space();- if (auto pixels = context->read_pixels({ {}, size }, Gfx::AlphaType::Premultiplied, color_space); pixels && pixels->size() == size)- return frame_of_bitmap(*pixels, gfx_color_space_for(color_space));+ if (auto pixels = context->read_pixels({ {}, size }, Gfx::AlphaType::Premultiplied, context->color_space()); pixels.has_value() && pixels->size() == size)+ return pixels;return {};}- auto bitmap = get_bitmap_from_surface();- if (!bitmap)- return {};- return frame_of_bitmap(*bitmap);+ return get_srgb_frame_from_surface();}Optional<Gfx::DecodedImageFrame> CanvasHost::get_frame_for_serialization(Utf16View type){if (serialization_of_the_bitmap_supports_color_profiles(type))return get_frame_from_surface();- auto bitmap = get_bitmap_from_surface();- if (!bitmap)- return {};- return frame_of_bitmap(*bitmap);+ return get_srgb_frame_from_surface();}// https://html.spec.whatwg.org/multipage/canvas.html#concept-canvas-origin-cleandiff --git a/Libraries/LibWeb/HTML/Canvas/CanvasHost.h b/Libraries/LibWeb/HTML/Canvas/CanvasHost.hindex 4c4be0ee219..aaad24a82fa 100644--- a/Libraries/LibWeb/HTML/Canvas/CanvasHost.h+++ b/Libraries/LibWeb/HTML/Canvas/CanvasHost.h@@ -42,7 +42,7 @@ public:virtual CSSPixelRect canvas_viewport_rect() const = 0;// The bitmap of the canvas, converted to sRGB.- virtual RefPtr<Gfx::Bitmap> get_bitmap_from_surface();+ virtual Optional<Gfx::DecodedImageFrame> get_srgb_frame_from_surface();// The bitmap of the canvas in the color space of its context, with that color space.Optional<Gfx::DecodedImageFrame> get_frame_from_surface();// The bitmap of the canvas as a serialization of it as a file of the type takes it: in the color space of itsdiff --git a/Libraries/LibWeb/HTML/Canvas/RemoteCanvas2DTransport.h b/Libraries/LibWeb/HTML/Canvas/RemoteCanvas2DTransport.hindex e64ad53025b..65a1fb541c6 100644--- a/Libraries/LibWeb/HTML/Canvas/RemoteCanvas2DTransport.h+++ b/Libraries/LibWeb/HTML/Canvas/RemoteCanvas2DTransport.h@@ -14,6 +14,7 @@#include <LibCompositing/DisplayList/DisplayListResourceIds.h>#include <LibCompositing/Video/VideoFrameHold.h>#include <LibGfx/ColorSpace.h>+#include <LibGfx/DecodedImageFrame.h>#include <LibGfx/Forward.h>#include <LibWeb/Export.h>#include <LibWeb/Forward.h>@@ -45,7 +46,7 @@ public:virtual void flush() = 0;// Unpremultiplied pixels come back as RGBA8888 and premultiplied pixels as BGRA8888, in the color space.- virtual RefPtr<Gfx::Bitmap> read_back_pixels(Gfx::IntRect const&, Gfx::AlphaType, Gfx::ColorSpace const&) = 0;+ virtual Optional<Gfx::DecodedImageFrame> read_back_pixels(Gfx::IntRect const&, Gfx::AlphaType, Gfx::ColorSpace const&) = 0;};}diff --git a/Libraries/LibWeb/HTML/Canvas/RemoteCanvas2DTransportFFI.cpp b/Libraries/LibWeb/HTML/Canvas/RemoteCanvas2DTransportFFI.cppindex 8ce28ab5ef9..5e0c997ea46 100644--- a/Libraries/LibWeb/HTML/Canvas/RemoteCanvas2DTransportFFI.cpp+++ b/Libraries/LibWeb/HTML/Canvas/RemoteCanvas2DTransportFFI.cpp@@ -46,11 +46,6 @@ void web_canvas_2d_transport_record_present(void* transport);size_t web_canvas_2d_transport_pending_command_count(void const* transport);void web_canvas_2d_transport_flush(void* transport);void* web_canvas_2d_transport_read_back_pixels(void* transport, i32 x, i32 y, i32 width, i32 height, u8 alpha_type, u8 color_space);-void web_canvas_2d_bitmap_ref(void* bitmap);-void web_canvas_2d_bitmap_unref(void* bitmap);-size_t web_canvas_2d_bitmap_size_in_bytes(void* bitmap);-bool web_canvas_2d_bitmap_unpremultiplied_rgba_pixels(void* bitmap, u8 const** out_pixels, size_t* out_pitch, i32* out_width, i32* out_height);-void* web_canvas_2d_image_frame_from_bitmap(void* bitmap, u8 color_space);}static RemoteCanvas2DTransport& transport_from(void* transport)@@ -121,46 +116,8 @@ void web_canvas_2d_transport_flush(void* transport)void* web_canvas_2d_transport_read_back_pixels(void* transport, i32 x, i32 y, i32 width, i32 height, u8 alpha_type, u8 color_space){VERIFY(Gfx::is_valid_alpha_type(alpha_type));- auto bitmap = transport_from(transport).read_back_pixels({ x, y, width, height }, static_cast<Gfx::AlphaType>(alpha_type), gfx_color_space_for(predefined_color_space_from_underlying(color_space)));- if (!bitmap)- return nullptr;- return &bitmap.release_nonnull().leak_ref();-}--void web_canvas_2d_bitmap_ref(void* bitmap)-{- static_cast<Gfx::Bitmap*>(bitmap)->ref();-}--void web_canvas_2d_bitmap_unref(void* bitmap)-{- static_cast<Gfx::Bitmap*>(bitmap)->unref();-}--size_t web_canvas_2d_bitmap_size_in_bytes(void* bitmap)-{- return static_cast<Gfx::Bitmap*>(bitmap)->size_in_bytes();-}--bool web_canvas_2d_bitmap_unpremultiplied_rgba_pixels(void* bitmap, u8 const** out_pixels, size_t* out_pitch, i32* out_width, i32* out_height)-{- auto const& typed_bitmap = *static_cast<Gfx::Bitmap const*>(bitmap);- if (typed_bitmap.format() != Gfx::BitmapFormat::RGBA8888 || typed_bitmap.alpha_type() != Gfx::AlphaType::Unpremultiplied)- return false;- *out_pixels = typed_bitmap.scanline_u8(0);- *out_pitch = typed_bitmap.pitch();- *out_width = typed_bitmap.width();- *out_height = typed_bitmap.height();- return true;-}--// A Gfx::DecodedImageFrame of the pixels of the bitmap, which are in the color space, allocated with new, or null if-// one cannot be made. The reference to the bitmap is taken over either way.-void* web_canvas_2d_image_frame_from_bitmap(void* bitmap, u8 color_space)-{- NonnullRefPtr<Gfx::Bitmap const> adopted_bitmap = adopt_ref(*static_cast<Gfx::Bitmap*>(bitmap));- auto frame = Gfx::DecodedImageFrame::create(*adopted_bitmap, gfx_color_space_for(predefined_color_space_from_underlying(color_space)));- if (frame.is_error())+ auto frame = transport_from(transport).read_back_pixels({ x, y, width, height }, static_cast<Gfx::AlphaType>(alpha_type), gfx_color_space_for(predefined_color_space_from_underlying(color_space)));+ if (!frame.has_value())return nullptr;return new Gfx::DecodedImageFrame { frame.release_value() };}diff --git a/Libraries/LibWeb/HTML/HTMLCanvasElement.cpp b/Libraries/LibWeb/HTML/HTMLCanvasElement.cppindex 1b59a62db5b..a863acd1a2e 100644--- a/Libraries/LibWeb/HTML/HTMLCanvasElement.cpp+++ b/Libraries/LibWeb/HTML/HTMLCanvasElement.cpp@@ -661,22 +661,24 @@ void HTMLCanvasElement::did_commit_placeholder_frame(Gfx::IntSize size, bool ori}));}-RefPtr<Gfx::Bitmap> HTMLCanvasElement::get_bitmap_from_surface()+Optional<Gfx::DecodedImageFrame> HTMLCanvasElement::get_srgb_frame_from_surface(){if (!m_is_placeholder)- return CanvasHost::get_bitmap_from_surface();+ return CanvasHost::get_srgb_frame_from_surface();auto size = bitmap_size_for_canvas();if (size.is_empty())- return nullptr;+ return {};if (m_placeholder_canvas_id.has_value() && document().page().has_compositor_host()) {- auto frame = document().page().compositor_host().read_placeholder_canvas_pixels(*m_placeholder_canvas_id, { {}, size });- m_placeholder_frame_is_origin_clean = frame.origin_clean;- if (frame.bitmap && frame.bitmap->size() == size)- return frame.bitmap;+ auto placeholder_pixels = document().page().compositor_host().read_placeholder_canvas_pixels(*m_placeholder_canvas_id, { {}, size });+ m_placeholder_frame_is_origin_clean = placeholder_pixels.origin_clean;+ if (placeholder_pixels.bitmap && placeholder_pixels.bitmap->size() == size) {+ if (auto frame = Gfx::DecodedImageFrame::create(*placeholder_pixels.bitmap); !frame.is_error())+ return frame.release_value();+ }}- return CanvasHost::get_bitmap_from_surface();+ return CanvasHost::get_srgb_frame_from_surface();}// https://html.spec.whatwg.org/multipage/canvas.html#concept-canvas-origin-cleandiff --git a/Libraries/LibWeb/HTML/HTMLCanvasElement.h b/Libraries/LibWeb/HTML/HTMLCanvasElement.hindex c3db0311e75..8011a7cb30d 100644--- a/Libraries/LibWeb/HTML/HTMLCanvasElement.h+++ b/Libraries/LibWeb/HTML/HTMLCanvasElement.h@@ -44,7 +44,7 @@ public:virtual CSS::ComputationContext canvas_font_computation_context() override;virtual CSS::ColorResolutionStyle canvas_color_resolution_style() override;virtual CSSPixelRect canvas_viewport_rect() const override;- virtual RefPtr<Gfx::Bitmap> get_bitmap_from_surface() override;+ virtual Optional<Gfx::DecodedImageFrame> get_srgb_frame_from_surface() override;virtual bool is_origin_clean() const override;JS::ThrowCompletionOr<RenderingContext> get_context(Utf16View type, JS::Value options);diff --git a/Libraries/LibWeb/WebDriver/Screenshot.cpp b/Libraries/LibWeb/WebDriver/Screenshot.cppindex e0f832ba2d9..4e1a5fb1917 100644--- a/Libraries/LibWeb/WebDriver/Screenshot.cpp+++ b/Libraries/LibWeb/WebDriver/Screenshot.cpp@@ -114,12 +114,12 @@ Response encode_canvas_element(HTML::HTMLCanvasElement& canvas)return Error::from_code(ErrorCode::UnableToCaptureScreen, "Captured screenshot is empty"sv);// 3. Let file be a serialization of the canvas element’s bitmap as a file, using "image/png" as an argument.- auto bitmap = canvas.get_bitmap_from_surface();- if (!bitmap)+ auto frame = canvas.get_srgb_frame_from_surface();+ if (!frame.has_value())return Error::from_code(ErrorCode::UnableToCaptureScreen, "Captured screenshot is empty"sv);Gfx::PNGWriterOptions png_options;png_options.compression = Gfx::PNGCompression::Fast;- auto file = Gfx::PNGWriter::encode(*bitmap, png_options);+ auto file = Gfx::PNGWriter::encode(*frame->bitmap_sharing_pixels(), png_options);if (file.is_error())return Error::from_code(ErrorCode::UnableToCaptureScreen, "Failed to serialize canvas"sv);diff --git a/Libraries/LibWeb/WebGL/RemoteWebGLTransportFFI.cpp b/Libraries/LibWeb/WebGL/RemoteWebGLTransportFFI.cppindex c1e8fd36178..ace91e10809 100644--- a/Libraries/LibWeb/WebGL/RemoteWebGLTransportFFI.cpp+++ b/Libraries/LibWeb/WebGL/RemoteWebGLTransportFFI.cpp@@ -77,7 +77,6 @@ void web_webgl_constants_restated_in_rust(ConstantsRestatedInRust* out_constantsvoid* web_webgl_anonymous_buffer_create(size_t size, u8** out_data);void web_webgl_anonymous_buffer_destroy(void* anonymous_buffer);void web_webgl_frame_destroy(void* frame);-void web_webgl_bitmap_unref(void* bitmap);}static RemoteWebGLTransport& transport_from(void* transport)@@ -180,7 +179,10 @@ void* web_webgl_transport_read_back_drawing_buffer(void* transport, i32 x, i32 yauto shareable_bitmap = transport_from(transport).read_back_drawing_buffer({ x, y, width, height });if (!shareable_bitmap.is_valid())return nullptr;- return &NonnullRefPtr<Gfx::Bitmap> { *shareable_bitmap.bitmap() }.leak_ref();+ auto frame = Gfx::DecodedImageFrame::create(*shareable_bitmap.bitmap());+ if (frame.is_error())+ return nullptr;+ return new Gfx::DecodedImageFrame { frame.release_value() };}size_t web_webgl_max_frames_per_message()@@ -228,9 +230,4 @@ void web_webgl_frame_destroy(void* frame)delete static_cast<ImageSourceFrameOwnedByRecorder*>(frame);}-void web_webgl_bitmap_unref(void* bitmap)-{- static_cast<Gfx::Bitmap*>(bitmap)->unref();-}-}diff --git a/Libraries/LibWeb/WebGL/WebGLRenderingContextBase.cpp b/Libraries/LibWeb/WebGL/WebGLRenderingContextBase.cppindex 6c4fba52e0a..f4774b058db 100644--- a/Libraries/LibWeb/WebGL/WebGLRenderingContextBase.cpp+++ b/Libraries/LibWeb/WebGL/WebGLRenderingContextBase.cpp@@ -298,12 +298,12 @@ void WebGLRenderingContextBase::clear_drawing_buffer()web_webgl_context_clear_drawing_buffer(this);}-RefPtr<Gfx::Bitmap> WebGLRenderingContextBase::read_back_drawing_buffer(Gfx::IntRect const& rect)+Optional<Gfx::DecodedImageFrame> WebGLRenderingContextBase::read_back_drawing_buffer(Gfx::IntRect const& rect){- auto* bitmap = static_cast<Gfx::Bitmap*>(web_webgl_context_read_back_drawing_buffer(this, rect.x(), rect.y(), rect.width(), rect.height()));- if (!bitmap)- return nullptr;- return adopt_ref(*bitmap);+ auto frame = adopt_own_if_nonnull(static_cast<Gfx::DecodedImageFrame*>(web_webgl_context_read_back_drawing_buffer(this, rect.x(), rect.y(), rect.width(), rect.height())));+ if (!frame)+ return {};+ return move(*frame);}void WebGLRenderingContextBase::lose_context_from_compositor_loss()@@ -413,16 +413,12 @@ TexImageSourceResult web_webgl_read_tex_image_source(void* source_wrapper, TexImframe = image_frame.release_value();break;case TexImageSourceKind::HTMLCanvasElement:- if (auto bitmap = Bindings::impl_from<HTML::HTMLCanvasElement>(wrapper).get_bitmap_from_surface()) {- if (auto canvas_frame = Gfx::DecodedImageFrame::create(*bitmap); !canvas_frame.is_error())- frame = canvas_frame.release_value();- }+ if (auto canvas_frame = Bindings::impl_from<HTML::HTMLCanvasElement>(wrapper).get_srgb_frame_from_surface(); canvas_frame.has_value())+ frame = canvas_frame.release_value();break;case TexImageSourceKind::OffscreenCanvas:- if (auto bitmap = Bindings::impl_from<HTML::OffscreenCanvas>(wrapper).get_bitmap_from_surface()) {- if (auto canvas_frame = Gfx::DecodedImageFrame::create(*bitmap); !canvas_frame.is_error())- frame = canvas_frame.release_value();- }+ if (auto canvas_frame = Bindings::impl_from<HTML::OffscreenCanvas>(wrapper).get_srgb_frame_from_surface(); canvas_frame.has_value())+ frame = canvas_frame.release_value();break;case TexImageSourceKind::HTMLVideoElement:if (auto captured_frame = Bindings::impl_from<HTML::HTMLVideoElement>(wrapper).capture_current_video_frame(); captured_frame.has_value())diff --git a/Libraries/LibWeb/WebGL/WebGLRenderingContextBase.h b/Libraries/LibWeb/WebGL/WebGLRenderingContextBase.hindex 202be608ef6..1f86bb8c52a 100644--- a/Libraries/LibWeb/WebGL/WebGLRenderingContextBase.h+++ b/Libraries/LibWeb/WebGL/WebGLRenderingContextBase.h@@ -11,6 +11,7 @@#include <AK/Variant.h>#include <LibCompositing/DisplayList/DisplayListResourceIds.h>#include <LibGC/Ptr.h>+#include <LibGfx/DecodedImageFrame.h>#include <LibGfx/Forward.h>#include <LibGfx/Rect.h>#include <LibGfx/Size.h>@@ -39,7 +40,7 @@ public:void reset_to_default_state() { }void prepare_for_compositing();void clear_drawing_buffer();- RefPtr<Gfx::Bitmap> read_back_drawing_buffer(Gfx::IntRect const&);+ Optional<Gfx::DecodedImageFrame> read_back_drawing_buffer(Gfx::IntRect const&);// https://registry.khronos.org/webgl/specs/latest/1.0/#CONTEXT_LOST// The compositor process (and with it the GL state) went away: set the context lost