Truly independent web browser
LibWeb: Serialize the pixels and color spaces of images from Rust
Shannon Booth310db375bdb6
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rsindex fb0ddd1420b..5ba8759619e 100644--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rs@@ -33,6 +33,8 @@ use crate::html::structured_serialize::{unsafe extern "C" {fn web_bindings_serialize_value(serialized: *mut c_void, value: u64) -> RawNativeFunctionResult;+ fn web_bindings_serialize_u8(serialized: *mut c_void, value: u8);+ fn web_bindings_serialize_i32(serialized: *mut c_void, value: i32);fn web_bindings_serialize_u32(serialized: *mut c_void, value: u32);fn web_bindings_serialize_u64(serialized: *mut c_void, value: u64);fn web_bindings_serialize_f64(serialized: *mut c_void, value: f64);@@ -42,6 +44,9 @@ unsafe extern "C" {fn web_bindings_serialize_utf16_string(serialized: *mut c_void, string: usize);fn web_bindings_serialize_bytes(serialized: *mut c_void, bytes: ak::Span<'_, u8>);fn web_bindings_deserialize_value(serialized: *mut c_void) -> RawNativeFunctionResult;+ fn web_bindings_deserialize_is_for_storage(serialized: *mut c_void) -> bool;+ fn web_bindings_deserialize_u8(serialized: *mut c_void, out_value: &mut u8) -> RawNativeFunctionResult;+ fn web_bindings_deserialize_i32(serialized: *mut c_void, out_value: &mut i32) -> RawNativeFunctionResult;fn web_bindings_deserialize_u32(serialized: *mut c_void, out_value: &mut u32) -> RawNativeFunctionResult;fn web_bindings_deserialize_u64(serialized: *mut c_void, out_value: &mut u64) -> RawNativeFunctionResult;fn web_bindings_deserialize_f64(serialized: *mut c_void, out_value: &mut f64) -> RawNativeFunctionResult;@@ -114,6 +119,16 @@ impl SerializationWriter<'_> {Ok(())}+ pub(crate) fn write_u8(&mut self, value: u8) {+ // SAFETY: The writer is lent for the steps.+ unsafe { web_bindings_serialize_u8(self.raw.as_ptr(), value) };+ }++ pub(crate) fn write_i32(&mut self, value: i32) {+ // SAFETY: The writer is lent for the steps.+ unsafe { web_bindings_serialize_i32(self.raw.as_ptr(), value) };+ }+pub(crate) fn write_u32(&mut self, value: u32) {// SAFETY: The writer is lent for the steps.unsafe { web_bindings_serialize_u32(self.raw.as_ptr(), value) };@@ -190,6 +205,26 @@ impl SerializationReader<'_> {Ok(unsafe { web_bindings_deserialize_value(self.raw.as_ptr()) }.into_completion()?)}+ /// Whether the record is one for storage, rather than for IPC.+ pub(crate) fn is_for_storage(&mut self) -> bool {+ // SAFETY: The reader is lent for the steps.+ unsafe { web_bindings_deserialize_is_for_storage(self.raw.as_ptr()) }+ }++ pub(crate) fn read_u8(&mut self) -> WebIdlResult<u8> {+ let mut value = 0;+ // SAFETY: The reader is lent for the steps.+ unsafe { web_bindings_deserialize_u8(self.raw.as_ptr(), &mut value) }.into_completion()?;+ Ok(value)+ }++ pub(crate) fn read_i32(&mut self) -> WebIdlResult<i32> {+ let mut value = 0;+ // SAFETY: The reader is lent for the steps.+ unsafe { web_bindings_deserialize_i32(self.raw.as_ptr(), &mut value) }.into_completion()?;+ Ok(value)+ }+pub(crate) fn read_u32(&mut self) -> WebIdlResult<u32> {let mut value = 0;// SAFETY: The reader is lent for the steps.diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/image_bitmap.rs b/Libraries/LibWeb/Bindings/Rust/src/html/image_bitmap.rsindex 92a50c300ff..c44e8b1e19b 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/image_bitmap.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/image_bitmap.rs@@ -1,4 +1,5 @@/*+ * Copyright (c) 2024, Lucas Chollet <[email protected]>* Copyright (c) 2026-present, the Ladybird developers.** SPDX-License-Identifier: BSD-2-Clause@@ -19,13 +20,32 @@ use crate::bindings::structured_data::{};use crate::bindings::{CallContext, Exception, WebIdlResult};+/// The bitmap data of a frame as Libraries/LibWeb/HTML/ImageBitmap.cpp hands it over and creates a frame from: the+/// values of its Gfx::Bitmap and Gfx::ColorSpace, and bytes that borrow from the frame or from the caller.+#[repr(C)]+struct FramePixels {+ width: i32,+ height: i32,+ pitch: u64,+ format: i32,+ alpha_type: i32,+ data: *const u8,+ data_size: usize,+ color_space_kind: u8,+ color_primaries: u8,+ transfer_characteristics: u8,+ icc_profile: *const u8,+ icc_profile_size: usize,+}+unsafe extern "C" {- // Defined in Libraries/LibWeb/HTML/ImageBitmap.cpp, which encodes and decodes the Gfx::Bitmap of a frame. A frame- // that it hands over is a Gfx::DecodedImageFrame allocated with new, or null for none.+ // Defined in Libraries/LibWeb/HTML/ImageBitmap.cpp, which encodes and decodes the Gfx::Bitmap of a transferred+ // frame. A frame that it hands over is a Gfx::DecodedImageFrame allocated with new, or null for none.fn web_image_bitmap_frame_size_in_bytes(frame: *const c_void) -> usize;- fn web_image_bitmap_serialize_bitmap(serialized: *mut c_void, frame: *const c_void);- fn web_image_bitmap_deserialize_bitmap(- serialized: *mut c_void,+ fn web_image_bitmap_frame_pixels(frame: *const c_void, pixels: &mut FramePixels);+ fn web_image_bitmap_create_frame(+ realm: *mut c_void,+ pixels: &FramePixels,out_frame: &mut *mut c_void,) -> RawNativeFunctionResult;fn web_image_bitmap_transfer_bitmap(data_holder: *mut c_void, frame: *const c_void) -> RawNativeFunctionResult;@@ -61,6 +81,170 @@ impl BitmapData {}}+const BITMAP_KIND_NONE: u8 = 0;+const BITMAP_KIND_SRGB: u8 = 1;+const BITMAP_KIND_WITH_COLOR_SPACE: u8 = 2;++const COLOR_SPACE_KIND_SRGB: u8 = 0;+const COLOR_SPACE_KIND_CICP: u8 = 1;+const COLOR_SPACE_KIND_ICC_PROFILE: u8 = 2;++const BITMAP_FORMATS: [(i32, &[u8]); 4] = [(1, b"BGRx8888"), (2, b"BGRA8888"), (3, b"RGBx8888"), (4, b"RGBA8888")];++const ALPHA_TYPES: [(i32, &[u8]); 2] = [(0, b"premultiplied"), (1, b"unpremultiplied")];++fn data_clone_error(message: &[u8]) -> Exception {+ Exception::Dom("DataCloneError", Utf16String::from_ascii(message))+}++/// Writes a value of Gfx as a record holds one: by its identifier in a storage record, and by its underlying value in+/// one for IPC.+fn serialize_enumeration(serialized: &mut SerializationWriter, values: &[(i32, &[u8])], value: i32, for_storage: bool) {+ if !for_storage {+ serialized.write_i32(value);+ return;+ }+ let (_, identifier) = values+ .iter()+ .find(|(underlying_value, _)| *underlying_value == value)+ .expect("a bitmap has a format and an alpha type that a record holds");+ serialized.write_utf16_string(&Utf16String::from_ascii(identifier));+}++/// Reads what serialize_enumeration() writes, which throws a "DataCloneError" DOMException with the message of an+/// invalid underlying value or of an unknown identifier for one that it does not know.+fn deserialize_enumeration(+ serialized: &mut SerializationReader,+ values: &[(i32, &[u8])],+ invalid_message: &[u8],+ unknown_message: &[u8],+) -> WebIdlResult<i32> {+ if !serialized.is_for_storage() {+ let value = serialized.read_i32()?;+ if !values.iter().any(|(underlying_value, _)| *underlying_value == value) {+ return Err(data_clone_error(invalid_message));+ }+ return Ok(value);+ }+ let identifier = serialized.read_utf16_string()?;+ values+ .iter()+ .find(|(_, value_identifier)| identifier == Utf16String::from_ascii(value_identifier))+ .map(|(value, _)| *value)+ .ok_or_else(|| data_clone_error(unknown_message))+}++/// Writes a copy of the bitmap data of the frame, or that there is none.+fn serialize_bitmap_data(serialized: &mut SerializationWriter, frame: *const c_void, for_storage: bool) {+ if frame.is_null() {+ serialized.write_u8(BITMAP_KIND_NONE);+ return;+ }+ let mut pixels = FramePixels {+ width: 0,+ height: 0,+ pitch: 0,+ format: 0,+ alpha_type: 0,+ data: core::ptr::null(),+ data_size: 0,+ color_space_kind: COLOR_SPACE_KIND_SRGB,+ color_primaries: 0,+ transfer_characteristics: 0,+ icc_profile: core::ptr::null(),+ icc_profile_size: 0,+ };+ // SAFETY: The frame is live.+ unsafe { web_image_bitmap_frame_pixels(frame, &mut pixels) };++ let has_color_space = pixels.color_space_kind != COLOR_SPACE_KIND_SRGB;+ serialized.write_u8(if has_color_space {+ BITMAP_KIND_WITH_COLOR_SPACE+ } else {+ BITMAP_KIND_SRGB+ });+ serialized.write_i32(pixels.width);+ serialized.write_i32(pixels.height);+ serialized.write_u64(pixels.pitch);+ serialize_enumeration(serialized, &BITMAP_FORMATS, pixels.format, for_storage);+ serialize_enumeration(serialized, &ALPHA_TYPES, pixels.alpha_type, for_storage);+ // SAFETY: The bytes borrow from the frame, which lives for the call.+ serialized.write_bytes(unsafe { ak::slice_from_raw_parts(pixels.data, pixels.data_size) });+ if !has_color_space {+ return;+ }+ serialized.write_u8(pixels.color_space_kind);+ if pixels.color_space_kind == COLOR_SPACE_KIND_CICP {+ serialized.write_u8(pixels.color_primaries);+ serialized.write_u8(pixels.transfer_characteristics);+ } else {+ // SAFETY: The bytes borrow from the frame, which lives for the call.+ serialized.write_bytes(unsafe { ak::slice_from_raw_parts(pixels.icc_profile, pixels.icc_profile_size) });+ }+}++/// Reads what serialize_bitmap_data() writes, and creates the bitmap data in the realm of the call context.+fn deserialize_bitmap_data(cx: &CallContext, serialized: &mut SerializationReader) -> WebIdlResult<Option<BitmapData>> {+ let kind = serialized.read_u8()?;+ if kind == BITMAP_KIND_NONE {+ return Ok(None);+ }+ if kind != BITMAP_KIND_SRGB && kind != BITMAP_KIND_WITH_COLOR_SPACE {+ return Err(data_clone_error(b"Invalid ImageBitmap bitmap data"));+ }+ let width = serialized.read_i32()?;+ let height = serialized.read_i32()?;+ let pitch = serialized.read_u64()?;+ let format = deserialize_enumeration(+ serialized,+ &BITMAP_FORMATS,+ b"Invalid structured serialize bitmap format",+ b"Unknown structured serialize bitmap format",+ )?;+ let alpha_type = deserialize_enumeration(+ serialized,+ &ALPHA_TYPES,+ b"Invalid structured serialize alpha type",+ b"Unknown structured serialize alpha type",+ )?;+ let data = serialized.read_bytes()?;++ let (mut color_space_kind, mut color_primaries, mut transfer_characteristics) = (COLOR_SPACE_KIND_SRGB, 0, 0);+ let mut icc_profile = Vec::new();+ if kind == BITMAP_KIND_WITH_COLOR_SPACE {+ color_space_kind = serialized.read_u8()?;+ match color_space_kind {+ COLOR_SPACE_KIND_SRGB => {}+ COLOR_SPACE_KIND_CICP => {+ color_primaries = serialized.read_u8()?;+ transfer_characteristics = serialized.read_u8()?;+ }+ COLOR_SPACE_KIND_ICC_PROFILE => icc_profile = serialized.read_bytes()?,+ _ => return Err(data_clone_error(b"Invalid ImageBitmap color space")),+ }+ }++ let pixels = FramePixels {+ width,+ height,+ pitch,+ format,+ alpha_type,+ data: data.as_ptr(),+ data_size: data.len(),+ color_space_kind,+ color_primaries,+ transfer_characteristics,+ icc_profile: icc_profile.as_ptr(),+ icc_profile_size: icc_profile.len(),+ };+ let mut frame = core::ptr::null_mut();+ // SAFETY: The realm is live, and the call borrows the bytes.+ unsafe { web_image_bitmap_create_frame(cx.realm().as_ptr().cast(), &pixels, &mut frame) }.into_completion()?;+ // SAFETY: C++ hands over the frame it created.+ Ok(unsafe { BitmapData::from_handed_over_frame(frame) })+}+#[derive(Trace)]#[gc(crate = libjs_rust)]pub(crate) struct ImageBitmap {@@ -191,7 +375,7 @@ impl Serializable for ImageBitmap {&self,_: &mut CallContext,serialized: &mut SerializationWriter,- _for_storage: bool,+ for_storage: bool,) -> WebIdlResult<()> {// 1. If value's origin-clean flag is not set, then throw a "DataCloneError" DOMException.if !self.origin_clean.get() {@@ -202,20 +386,15 @@ impl Serializable for ImageBitmap {}// 2. Set serialized.[[BitmapData]] to a copy of value's bitmap data.- // SAFETY: The writer is lent for the steps, and the frame lives while the bitmap data is set.- unsafe { web_image_bitmap_serialize_bitmap(serialized.as_raw(), self.raw_frame()) };+ serialize_bitmap_data(serialized, self.raw_frame(), for_storage);Ok(())}/// https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#the-imagebitmap-interface:deserialization-steps- fn deserialization_steps(_: &mut CallContext, serialized: &mut SerializationReader) -> WebIdlResult<Self> {+ fn deserialization_steps(cx: &mut CallContext, serialized: &mut SerializationReader) -> WebIdlResult<Self> {// 1. Set value's bitmap data to serialized.[[BitmapData]].- let mut frame = core::ptr::null_mut();- // SAFETY: The reader is lent for the steps.- unsafe { web_image_bitmap_deserialize_bitmap(serialized.as_raw(), &mut frame) }.into_completion()?;- // SAFETY: C++ hands over the frame it decoded, or null.- Ok(Self::new(unsafe { BitmapData::from_handed_over_frame(frame) }))+ Ok(Self::new(deserialize_bitmap_data(cx, serialized)?))}}diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/image_data.rs b/Libraries/LibWeb/Bindings/Rust/src/html/image_data.rsindex b4a4437af38..8ee69f9e4be 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/image_data.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/image_data.rs@@ -6,14 +6,13 @@//! https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#imagedata-use core::ffi::c_void;use core::ptr::NonNull;use ak::Utf16String;use libjs_rust::api::{- ArrayBuffer, ArrayBufferOrder, ArrayBufferShared, Gc, RawNativeFunctionResult, Trace, TypedArrayBase,- TypedArrayKind, Value, create_typed_array_on_buffer, is_typed_array_out_of_bounds,- make_typed_array_with_buffer_witness_record, typed_array_byte_length,+ ArrayBuffer, ArrayBufferOrder, ArrayBufferShared, Gc, Trace, TypedArrayBase, TypedArrayKind, Value,+ create_typed_array_on_buffer, is_typed_array_out_of_bounds, make_typed_array_with_buffer_witness_record,+ typed_array_byte_length,};use super::predefined_color_space::PredefinedColorSpace;@@ -21,16 +20,6 @@ use crate::bindings::interface::{Ref, Wrappable, allocate};use crate::bindings::structured_data::{Serializable, SerializationReader, SerializationWriter};use crate::bindings::{CallContext, Exception, WebIdlResult};-unsafe extern "C" {- // Defined in Libraries/LibWeb/HTML/ImageData.cpp, which encodes the color space as StructuredSerialize encodes a- // Web::Bindings::PredefinedColorSpace.- fn web_image_data_serialize_color_space(serialized: *mut c_void, color_space: PredefinedColorSpace);- fn web_image_data_deserialize_color_space(- serialized: *mut c_void,- out_color_space: &mut u8,- ) -> RawNativeFunctionResult;-}-/// https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#imagedatasettings#[derive(Clone, Copy, Debug, Default)]pub(crate) struct ImageDataSettings {@@ -267,13 +256,56 @@ fn invalid_state_error(message: &[u8]) -> Exception {Exception::Dom("InvalidStateError", Utf16String::from_ascii(message))}+/// The identifier by which a storage record holds a color space.+fn color_space_storage_identifier(color_space: PredefinedColorSpace) -> &'static [u8] {+ match color_space {+ PredefinedColorSpace::Srgb => b"srgb",+ PredefinedColorSpace::SrgbLinear => b"srgb-linear",+ PredefinedColorSpace::DisplayP3 => b"display-p3",+ PredefinedColorSpace::DisplayP3Linear => b"display-p3-linear",+ }+}++/// Writes the color space as a record holds one: by its identifier in a storage record, and by its underlying value in+/// one for IPC.+fn serialize_color_space(serialized: &mut SerializationWriter, color_space: PredefinedColorSpace, for_storage: bool) {+ if for_storage {+ serialized.write_utf16_string(&Utf16String::from_ascii(color_space_storage_identifier(color_space)));+ } else {+ serialized.write_u8(color_space as u8);+ }+}++/// Reads what serialize_color_space() writes.+fn deserialize_color_space(serialized: &mut SerializationReader) -> WebIdlResult<PredefinedColorSpace> {+ let color_space = if serialized.is_for_storage() {+ let identifier = serialized.read_utf16_string()?;+ [+ PredefinedColorSpace::Srgb,+ PredefinedColorSpace::SrgbLinear,+ PredefinedColorSpace::DisplayP3,+ PredefinedColorSpace::DisplayP3Linear,+ ]+ .into_iter()+ .find(|&color_space| identifier == Utf16String::from_ascii(color_space_storage_identifier(color_space)))+ } else {+ PredefinedColorSpace::from_u8(serialized.read_u8()?)+ };+ color_space.ok_or_else(|| {+ Exception::Dom(+ "DataCloneError",+ Utf16String::from_ascii(b"Unknown structured serialize color space"),+ )+ })+}+impl Serializable for ImageData {/// https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#the-imagedata-interface:serialization-stepsfn serialization_steps(&self,_: &mut CallContext,serialized: &mut SerializationWriter,- _for_storage: bool,+ for_storage: bool,) -> WebIdlResult<()> {// 1. Set serialized.[[Data]] to the sub-serialization of the value of value's data attribute.serialized.write_value(Value::from_object(self.data))?;@@ -285,8 +317,7 @@ impl Serializable for ImageData {serialized.write_u32(self.height);// 4. Set serialized.[[ColorSpace]] to the value of value's colorSpace attribute.- // SAFETY: The writer is lent for the steps.- unsafe { web_image_data_serialize_color_space(serialized.as_raw(), self.color_space) };+ serialize_color_space(serialized, self.color_space, for_storage);// FIXME: 5. Set serialized.[[PixelFormat]] to the value of value's pixelFormat attribute.@@ -316,10 +347,7 @@ impl Serializable for ImageData {let height = serialized.read_u32()?;// 4. Initialize value's colorSpace attribute to serialized.[[ColorSpace]].- let mut color_space = 0;- // SAFETY: The reader is lent for the steps.- unsafe { web_image_data_deserialize_color_space(serialized.as_raw(), &mut color_space) }.into_completion()?;- let color_space = PredefinedColorSpace::from_u8(color_space).expect("C++ decodes a color space");+ let color_space = deserialize_color_space(serialized)?;// FIXME: 5. Initialize value's pixelFormat attribute to serialized.[[PixelFormat]].diff --git a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp b/Libraries/LibWeb/Bindings/RustBindingsServices.cppindex 07be502a2d5..d1ad267bf41 100644--- a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp+++ b/Libraries/LibWeb/Bindings/RustBindingsServices.cpp@@ -131,6 +131,8 @@ bool web_bindings_object_implements_interface(JSObject* object, u16 interface_naJSObject* web_bindings_create_dom_exception(void* realm, ReadonlyBytes name, FlatPtr message);bool web_bindings_extract_an_origin(JSObject* object, void* ctx, void (*on_origin)(void*, URL::FFI::FfiOrigin const*));JSCompletion web_bindings_serialize_value(RustSerializationWriter*, JSValue);+void web_bindings_serialize_u8(RustSerializationWriter*, u8);+void web_bindings_serialize_i32(RustSerializationWriter*, i32);void web_bindings_serialize_u32(RustSerializationWriter*, u32);void web_bindings_serialize_u64(RustSerializationWriter*, u64);void web_bindings_serialize_f64(RustSerializationWriter*, double);@@ -140,6 +142,9 @@ void web_bindings_serialize_optional_u64(RustSerializationWriter*, bool has_valuvoid web_bindings_serialize_utf16_string(RustSerializationWriter*, FlatPtr string);void web_bindings_serialize_bytes(RustSerializationWriter*, ReadonlyBytes);JSCompletion web_bindings_deserialize_value(RustSerializationReader*);+bool web_bindings_deserialize_is_for_storage(RustSerializationReader*);+JSCompletion web_bindings_deserialize_u8(RustSerializationReader*, u8* out_value);+JSCompletion web_bindings_deserialize_i32(RustSerializationReader*, i32* out_value);JSCompletion web_bindings_deserialize_u32(RustSerializationReader*, u32* out_value);JSCompletion web_bindings_deserialize_u64(RustSerializationReader*, u64* out_value);JSCompletion web_bindings_deserialize_f64(RustSerializationReader*, double* out_value);@@ -246,6 +251,16 @@ JSCompletion web_bindings_serialize_value(RustSerializationWriter* writer, JSValreturn completion_to_abi(writer->realm, JS::js_undefined());}+void web_bindings_serialize_u8(RustSerializationWriter* writer, u8 value)+{+ writer->serialized.encode(value);+}++void web_bindings_serialize_i32(RustSerializationWriter* writer, i32 value)+{+ writer->serialized.encode(value);+}+void web_bindings_serialize_u32(RustSerializationWriter* writer, u32 value){writer->serialized.encode(value);@@ -292,6 +307,21 @@ JSCompletion web_bindings_deserialize_value(RustSerializationReader* reader)return completion_to_abi(reader->realm, HTML::structured_deserialize_internal(reader->realm->vm(), reader->serialized, reader->realm, reader->memory));}+bool web_bindings_deserialize_is_for_storage(RustSerializationReader* reader)+{+ return reader->serialized.type() == HTML::SerializationType::Storage;+}++JSCompletion web_bindings_deserialize_u8(RustSerializationReader* reader, u8* out_value)+{+ return deserialize_plain_value(reader, out_value);+}++JSCompletion web_bindings_deserialize_i32(RustSerializationReader* reader, i32* out_value)+{+ return deserialize_plain_value(reader, out_value);+}+JSCompletion web_bindings_deserialize_u32(RustSerializationReader* reader, u32* out_value){return deserialize_plain_value(reader, out_value);diff --git a/Libraries/LibWeb/HTML/ImageBitmap.cpp b/Libraries/LibWeb/HTML/ImageBitmap.cppindex ffe0ce5f9bc..f6f8760e552 100644--- a/Libraries/LibWeb/HTML/ImageBitmap.cpp+++ b/Libraries/LibWeb/HTML/ImageBitmap.cpp@@ -48,15 +48,11 @@ static constexpr size_t shared_pixels_alignment = 64;return TRY_OR_THROW_OOM(vm, Gfx::Bitmap::create_wrapper(format, alpha_type, Gfx::IntSize(width, height), pitch, pixels, [bitmap_data = move(bitmap_data)] { }));}-template<typename T, typename Encoder>-static WebIDL::ExceptionOr<void> encode_bitmap_value(Encoder& encoder, T const& value)+template<typename T>+static WebIDL::ExceptionOr<void> encode_bitmap_value(HTML::TransferDataEncoder& encoder, T const& value){- if constexpr (IsSame<Encoder, HTML::StructuredSerializeWriter>) {- encoder.encode(value);- } else {- if (encoder.encode(value).is_error())- return WebIDL::DataCloneError::create("Unable to transfer ImageBitmap"_utf16);- }+ if (encoder.encode(value).is_error())+ return WebIDL::DataCloneError::create("Unable to transfer ImageBitmap"_utf16);return {};}@@ -66,8 +62,7 @@ enum class SerializedColorSpaceKind : u8 {ICCProfile,};-template<typename Encoder>-static WebIDL::ExceptionOr<void> serialize_color_space(Encoder& encoder, Gfx::ColorSpace const& color_space)+static WebIDL::ExceptionOr<void> serialize_color_space(HTML::TransferDataEncoder& encoder, Gfx::ColorSpace const& color_space){return color_space.data().visit([&](Empty) -> WebIDL::ExceptionOr<void> {@@ -86,20 +81,19 @@ static WebIDL::ExceptionOr<void> serialize_color_space(Encoder& encoder, Gfx::Co});}-template<typename Decoder>-[[nodiscard]] static ErrorOr<Gfx::ColorSpace> deserialize_color_space(Decoder& decoder)+[[nodiscard]] static ErrorOr<Gfx::ColorSpace> deserialize_color_space(HTML::TransferDataDecoder& decoder){- auto kind = TRY(decoder.template decode<u8>());+ auto kind = TRY(decoder.decode<u8>());switch (static_cast<SerializedColorSpaceKind>(kind)) {case SerializedColorSpaceKind::SRGB:return Gfx::ColorSpace {};case SerializedColorSpaceKind::CICP: {- auto color_primaries = static_cast<Media::ColorPrimaries>(TRY(decoder.template decode<u8>()));- auto transfer_characteristics = static_cast<Media::TransferCharacteristics>(TRY(decoder.template decode<u8>()));+ auto color_primaries = static_cast<Media::ColorPrimaries>(TRY(decoder.decode<u8>()));+ auto transfer_characteristics = static_cast<Media::TransferCharacteristics>(TRY(decoder.decode<u8>()));return Gfx::ColorSpace::from_cicp({ color_primaries, transfer_characteristics, Media::MatrixCoefficients::Identity, Media::VideoFullRangeFlag::Full });}case SerializedColorSpaceKind::ICCProfile: {- auto icc_bytes = TRY(decoder.template decode<ByteBuffer>());+ auto icc_bytes = TRY(decoder.decode<ByteBuffer>());return Gfx::ColorSpace::from_icc_bytes(icc_bytes);}}@@ -114,8 +108,7 @@ enum class SerializedBitmapKind : u8 {WithColorSpace,};-template<typename Encoder>-static WebIDL::ExceptionOr<void> serialize_bitmap(Encoder& encoder, Gfx::DecodedImageFrame const* frame)+static WebIDL::ExceptionOr<void> serialize_bitmap(HTML::TransferDataEncoder& encoder, Gfx::DecodedImageFrame const* frame){if (!frame)return encode_bitmap_value(encoder, to_underlying(SerializedBitmapKind::None));@@ -134,8 +127,7 @@ static WebIDL::ExceptionOr<void> serialize_bitmap(Encoder& encoder, Gfx::Decodedreturn {};}-template<typename Decoder>-[[nodiscard]] static WebIDL::ExceptionOr<Optional<Gfx::DecodedImageFrame>> deserialize_bitmap(JS::Realm& realm, Decoder& decoder)+[[nodiscard]] static WebIDL::ExceptionOr<Optional<Gfx::DecodedImageFrame>> deserialize_bitmap(JS::Realm& realm, HTML::TransferDataDecoder& decoder){auto const kind = TRY(decode_or_throw_data_clone_error<u8>(realm, decoder));if (kind == to_underlying(SerializedBitmapKind::None))@@ -292,11 +284,28 @@ bool web_image_bitmap_origin_clean(void const* image_bitmap);void web_image_bitmap_set_origin_clean(void* image_bitmap, bool origin_clean);Gfx::DecodedImageFrame const* web_image_bitmap_frame(void const* image_bitmap);-// What Bindings/Rust/src/html/image_bitmap.rs asks of C++, which owns the encoding of a Gfx::Bitmap: a bitmap that it-// is handed over is a Gfx::DecodedImageFrame allocated with new, or null for none.+// The bitmap data of a frame, which the serialization steps of Bindings/Rust/src/html/image_bitmap.rs write and their+// deserialization steps read. The bytes of the pixels that C++ hands over borrow from the frame.+struct FramePixels {+ i32 width { 0 };+ i32 height { 0 };+ u64 pitch { 0 };+ i32 format { 0 };+ i32 alpha_type { 0 };+ u8 const* data { nullptr };+ size_t data_size { 0 };+ u8 color_space_kind { 0 };+ u8 color_primaries { 0 };+ u8 transfer_characteristics { 0 };+ u8 const* icc_profile { nullptr };+ size_t icc_profile_size { 0 };+};++// What Bindings/Rust/src/html/image_bitmap.rs asks of C++, which owns the encoding of the Gfx::Bitmap of a transferred+// frame: a frame that it is handed over is a Gfx::DecodedImageFrame allocated with new, or null for none.size_t web_image_bitmap_frame_size_in_bytes(Gfx::DecodedImageFrame const*);-void web_image_bitmap_serialize_bitmap(Bindings::RustSerializationWriter*, Gfx::DecodedImageFrame const*);-JSCompletion web_image_bitmap_deserialize_bitmap(Bindings::RustSerializationReader*, Gfx::DecodedImageFrame** out_frame);+void web_image_bitmap_frame_pixels(Gfx::DecodedImageFrame const*, FramePixels*);+JSCompletion web_image_bitmap_create_frame(void* realm, FramePixels const*, Gfx::DecodedImageFrame** out_frame);JSCompletion web_image_bitmap_transfer_bitmap(Bindings::RustTransferDataWriter*, Gfx::DecodedImageFrame const*);JSCompletion web_image_bitmap_receive_bitmap(Bindings::RustTransferDataReader*, Gfx::DecodedImageFrame** out_frame);@@ -305,18 +314,76 @@ size_t web_image_bitmap_frame_size_in_bytes(Gfx::DecodedImageFrame const* frame)return frame->bitmap().data_size();}-void web_image_bitmap_serialize_bitmap(Bindings::RustSerializationWriter* writer, Gfx::DecodedImageFrame const* frame)+// NB: The Rust side names these values by their underlying values.+static_assert(to_underlying(Gfx::BitmapFormat::BGRx8888) == 1);+static_assert(to_underlying(Gfx::BitmapFormat::BGRA8888) == 2);+static_assert(to_underlying(Gfx::BitmapFormat::RGBx8888) == 3);+static_assert(to_underlying(Gfx::BitmapFormat::RGBA8888) == 4);+static_assert(to_underlying(Gfx::AlphaType::Premultiplied) == 0);+static_assert(to_underlying(Gfx::AlphaType::Unpremultiplied) == 1);+static_assert(to_underlying(SerializedColorSpaceKind::SRGB) == 0);+static_assert(to_underlying(SerializedColorSpaceKind::CICP) == 1);+static_assert(to_underlying(SerializedColorSpaceKind::ICCProfile) == 2);++void web_image_bitmap_frame_pixels(Gfx::DecodedImageFrame const* frame, FramePixels* pixels)+{+ auto const& bitmap = frame->bitmap();+ pixels->width = bitmap.width();+ pixels->height = bitmap.height();+ pixels->pitch = bitmap.pitch();+ pixels->format = to_underlying(bitmap.format());+ pixels->alpha_type = to_underlying(bitmap.alpha_type());+ pixels->data = bitmap.scanline_u8(0);+ pixels->data_size = bitmap.data_size();+ frame->color_space().data().visit(+ [&](Empty) {+ pixels->color_space_kind = to_underlying(SerializedColorSpaceKind::SRGB);+ },+ [&](Gfx::ColorSpace::CICP const& cicp) {+ pixels->color_space_kind = to_underlying(SerializedColorSpaceKind::CICP);+ pixels->color_primaries = to_underlying(cicp.color_primaries);+ pixels->transfer_characteristics = to_underlying(cicp.transfer_characteristics);+ },+ [&](NonnullRefPtr<Gfx::ColorSpace::ICCProfile const> const& icc_profile) {+ pixels->color_space_kind = to_underlying(SerializedColorSpaceKind::ICCProfile);+ pixels->icc_profile = icc_profile->bytes().data();+ pixels->icc_profile_size = icc_profile->bytes().size();+ });+}++[[nodiscard]] static ErrorOr<Gfx::ColorSpace> color_space_from_frame_pixels(FramePixels const& pixels){- MUST(serialize_bitmap(writer->serialized, frame));+ switch (static_cast<SerializedColorSpaceKind>(pixels.color_space_kind)) {+ case SerializedColorSpaceKind::SRGB:+ return Gfx::ColorSpace {};+ case SerializedColorSpaceKind::CICP: {+ auto color_primaries = static_cast<Media::ColorPrimaries>(pixels.color_primaries);+ auto transfer_characteristics = static_cast<Media::TransferCharacteristics>(pixels.transfer_characteristics);+ return Gfx::ColorSpace::from_cicp({ color_primaries, transfer_characteristics, Media::MatrixCoefficients::Identity, Media::VideoFullRangeFlag::Full });+ }+ case SerializedColorSpaceKind::ICCProfile: {+ auto icc_bytes = TRY(ByteBuffer::copy(pixels.icc_profile, pixels.icc_profile_size));+ return Gfx::ColorSpace::from_icc_bytes(icc_bytes);+ }+ }+ return Error::from_string_literal("Invalid ImageBitmap color space");}-JSCompletion web_image_bitmap_deserialize_bitmap(Bindings::RustSerializationReader* reader, Gfx::DecodedImageFrame** out_frame)+JSCompletion web_image_bitmap_create_frame(void* realm, FramePixels const* pixels, Gfx::DecodedImageFrame** out_frame){- auto frame = deserialize_bitmap(reader->realm, reader->serialized);+ auto& js_realm = *static_cast<JS::Realm*>(realm);+ auto frame = [&]() -> WebIDL::ExceptionOr<Gfx::DecodedImageFrame> {+ auto data = TRY_OR_THROW_OOM(js_realm.vm(), ByteBuffer::copy(pixels->data, pixels->data_size));+ auto bitmap = TRY(create_bitmap_from_bitmap_data(js_realm.vm(), static_cast<Gfx::BitmapFormat>(pixels->format), static_cast<Gfx::AlphaType>(pixels->alpha_type), pixels->width, pixels->height, pixels->pitch, move(data)));+ auto color_space = color_space_from_frame_pixels(*pixels);+ if (color_space.is_error())+ return data_clone_error_from_serialization_error(js_realm, color_space.release_error());+ return Gfx::DecodedImageFrame { *bitmap, color_space.release_value() };+ }();if (frame.is_exception())- return Bindings::completion_to_abi(reader->realm, frame.release_error());+ return Bindings::completion_to_abi(js_realm, frame.release_error());*out_frame = frame_to_hand_over(frame.release_value());- return Bindings::completion_to_abi(reader->realm, JS::js_undefined());+ return Bindings::completion_to_abi(js_realm, JS::js_undefined());}JSCompletion web_image_bitmap_transfer_bitmap(Bindings::RustTransferDataWriter* writer, Gfx::DecodedImageFrame const* frame)diff --git a/Libraries/LibWeb/HTML/ImageData.cpp b/Libraries/LibWeb/HTML/ImageData.cppindex a9b03a1a39f..151a59403fe 100644--- a/Libraries/LibWeb/HTML/ImageData.cpp+++ b/Libraries/LibWeb/HTML/ImageData.cpp@@ -8,9 +8,7 @@#include <LibGfx/Bitmap.h>#include <LibJS/HostClassBuilder.h>#include <LibJS/Runtime/VM.h>-#include <LibWeb/Bindings/RustSerialization.h>#include <LibWeb/HTML/ImageData.h>-#include <LibWeb/HTML/StructuredSerialize.h>#include <LibWebCommon/Bindings/PredefinedColorSpace.h>namespace Web::HTML {@@ -29,25 +27,6 @@ u32 web_image_data_height(void const* image_data);bool web_image_data_is_detached(void const* image_data);u8* web_image_data_pixels(void const* image_data);u8 web_image_data_color_space(void const* image_data);--// What the serialization steps of Bindings/Rust/src/html/image_data.rs ask of C++: the color space, encoded as for-// any other Bindings::PredefinedColorSpace.-void web_image_data_serialize_color_space(Bindings::RustSerializationWriter*, Bindings::PredefinedColorSpace);-JSCompletion web_image_data_deserialize_color_space(Bindings::RustSerializationReader*, Bindings::PredefinedColorSpace* out_color_space);--void web_image_data_serialize_color_space(Bindings::RustSerializationWriter* writer, Bindings::PredefinedColorSpace color_space)-{- writer->serialized.encode(color_space);-}--JSCompletion web_image_data_deserialize_color_space(Bindings::RustSerializationReader* reader, Bindings::PredefinedColorSpace* out_color_space)-{- auto color_space = decode_or_throw_data_clone_error<Bindings::PredefinedColorSpace>(reader->realm, reader->serialized);- if (color_space.is_exception())- return Bindings::completion_to_abi(reader->realm, color_space.release_error());- *out_color_space = color_space.release_value();- return Bindings::completion_to_abi(reader->realm, JS::js_undefined());-}}WebIDL::ExceptionOr<GC::Ref<ImageData>> ImageData::create(JS::Realm& realm, u32 width, u32 height)diff --git a/Meta/Linters/check_libweb_realm_mentions.py b/Meta/Linters/check_libweb_realm_mentions.pyindex e0bf2d8878d..a73f1752913 100755--- a/Meta/Linters/check_libweb_realm_mentions.py+++ b/Meta/Linters/check_libweb_realm_mentions.py@@ -52,7 +52,7 @@ ALLOWED_REALM_MENTIONS = {"FileAPI": (2, 9, "Blob glue still creates streams and buffers in selected realms"),"HTML": (65,- 196,+ 197,"HTML algorithms still contain structured serialization, including posted-message preparation, canvas, navigation transfer/reconstruction, worker/worklet, and event realm use, and cross-origin Window/Location property functions are created in the current realm; RemoteWindow mirrors Window's postMessage; ""the C++ glue of the Rust structured serialization reads records and creates platform objects in a given realm",),