Skip to content

Truly independent web browser

LibWeb: Implement createImageBitmap() for video elements

Andreas Kling3e3415aba629
diff --git a/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/exports.rs
index fbbe410f5c3..8a12231518a 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/exports.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/exports.rs
@@ -16,8 +16,10 @@ use libgfx_rust::{IntRect, IntSize};
use super::canvas::Canvas;
use super::context::{ContextParameters, ContextState, Offscreen, OnScreen, RenderingContext2D};
+use crate::bindings::conversions::CppInterface;
use crate::bindings::interface::{Interface, allocate, cell_from_abi, cell_into_abi};
use crate::html::canvas_draw_image::CanvasImageSource;
+use crate::html::canvas_pattern::read_back_current_video_frame;
use crate::html::canvas_rendering_context2d_settings::{CanvasColorType, CanvasRenderingContext2DSettings};
use crate::html::image_bitmap::ImageBitmap;
use crate::html::predefined_color_space::PredefinedColorSpace;
@@ -216,3 +218,29 @@ pub unsafe extern "C" fn web_canvas_2d_context_draw_image_bitmap(
.is_ok()
})
}
+
+unsafe extern "C" {
+ /// Sets the Optional<Gfx::DecodedImageFrame> to a copy of the frame, which is lent for the call.
+ fn web_canvas_2d_set_video_frame_copy(out_frame: *mut c_void, frame: *const c_void);
+}
+
+/// Sets the Optional<Gfx::DecodedImageFrame> to a copy of the frame of the video at its current playback position, and
+/// returns whether the video has one.
+///
+/// # Safety
+///
+/// `video` must be a live wrapper of an HTMLVideoElement, and `out_frame` an Optional<Gfx::DecodedImageFrame>.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_canvas_2d_read_back_video_frame(video: *mut c_void, out_frame: *mut c_void) -> bool {
+ let video = NonNull::new(video.cast::<libjs_rust::api::Object>()).expect("C++ passes the video");
+ // SAFETY: The caller passes a live wrapper of an HTMLVideoElement.
+ let video = unsafe { CppInterface::from_wrapper(libjs_rust::api::Gc::from_non_null(video)) };
+ // NB: The colors of a video can be outside the gamut of sRGB, so the frame is read back in the widest color space of
+ // a canvas.
+ let Some(frame) = read_back_current_video_frame(video, ColorSpace::DisplayP3) else {
+ return false;
+ };
+ // SAFETY: The handle keeps the frame alive for the call, and the caller passes the optional.
+ unsafe { web_canvas_2d_set_video_frame_copy(out_frame, frame.as_raw()) };
+ true
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/host.rs b/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/host.rs
index d61fd3e65b3..94786b00af8 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/host.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/host.rs
@@ -46,7 +46,7 @@ unsafe extern "C" {
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) -> *mut c_void;
+ 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,
@@ -85,9 +85,9 @@ impl Bitmap {
bitmap
}
- /// A frame of the bitmap, which the frame keeps alive.
- pub(crate) fn into_image_frame(self) -> ImageFrameHandle {
- let frame = unsafe { web_canvas_2d_image_frame_from_bitmap(self.into_raw()) };
+ /// A frame of the bitmap, whose pixels are in the color space, which the frame keeps alive.
+ pub(crate) fn into_image_frame(self, color_space: ColorSpace) -> ImageFrameHandle {
+ let frame = unsafe { web_canvas_2d_image_frame_from_bitmap(self.into_raw(), color_space) };
// SAFETY: LibWeb hands over a frame that it allocated with new, which took over the reference to the bitmap.
unsafe { ImageFrameHandle::adopt(frame) }
}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/canvas_fill_stroke_styles.rs b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_fill_stroke_styles.rs
index 98f68d2d412..28971d9b258 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/canvas_fill_stroke_styles.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_fill_stroke_styles.rs
@@ -179,6 +179,6 @@ impl<K: CanvasKind> RenderingContext2D<K> {
image: CanvasImageSource,
repetition: Utf16String,
) -> WebIdlResult<Option<Ref<CanvasPattern>>> {
- CanvasPattern::create_for_image(cx.vm(), &image, &repetition)
+ CanvasPattern::create_for_image(cx.vm(), &image, &repetition, self.context_attributes.color_space.into())
}
}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/canvas_pattern.rs b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_pattern.rs
index b078df2a1a8..6189d86fe82 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/canvas_pattern.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_pattern.rs
@@ -37,8 +37,9 @@ fn parse_repetition(repetition: &Utf16String) -> Option<Canvas2DPatternRepetitio
.map(|(_, repetition)| repetition)
}
-/// A pattern outlives any one video frame, so it reads the frame back instead of holding it.
-fn read_back_current_video_frame(video: CppInterface) -> Option<ImageFrameHandle> {
+/// A copy of the frame of the video at its current playback position, in the color space, which it keeps. A pattern or
+/// an ImageBitmap outlives any one video frame, so it reads the frame back instead of holding it.
+pub(crate) fn read_back_current_video_frame(video: CppInterface, color_space: ColorSpace) -> Option<ImageFrameHandle> {
let captured_frame = capture_video_frame(video)?;
let transport = video_transport(video)?;
let mut recorder = Recorder::new(transport);
@@ -54,7 +55,7 @@ fn read_back_current_video_frame(video: CppInterface) -> Option<ImageFrameHandle
let will_read_frequently = true;
if width <= 0
|| height <= 0
- || !recorder.create_context(IntSize { width, height }, true, will_read_frequently, ColorSpace::Srgb)
+ || !recorder.create_context(IntSize { width, height }, true, will_read_frequently, color_space)
{
return None;
}
@@ -77,9 +78,9 @@ fn read_back_current_video_frame(video: CppInterface) -> Option<ImageFrameHandle
},
);
recorder.flush();
- let bitmap = recorder.read_back_pixels(frame_rect, AlphaType::Premultiplied, ColorSpace::Srgb);
+ let bitmap = recorder.read_back_pixels(frame_rect, AlphaType::Premultiplied, color_space);
recorder.destroy_context();
- Some(bitmap?.into_image_frame())
+ Some(bitmap?.into_image_frame(color_space))
}
#[derive(Trace)]
@@ -119,6 +120,7 @@ impl CanvasPattern {
vm: &Vm,
image: &CanvasImageSource,
repetition: &Utf16String,
+ color_space: ColorSpace,
) -> WebIdlResult<Option<Ref<Self>>> {
// 1. Let usability be the result of checking the usability of image.
// 2. If usability is bad, then return null.
@@ -144,7 +146,9 @@ impl CanvasPattern {
// 6. Let pattern be a new CanvasPattern object with the image image and the repetition behavior given by
// repetition.
let frame = match *image {
- CanvasImageSource::HTMLVideoElement(video) => read_back_current_video_frame(video),
+ // NB: The frame of a video is read back in the color space of the context, which a draw with the pattern
+ // converts it to anyway.
+ CanvasImageSource::HTMLVideoElement(video) => read_back_current_video_frame(video, color_space),
_ => image.frame(),
};
let pattern = Self::create(vm, frame, repetition);
diff --git a/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cpp b/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cpp
index be30617959b..2eab424fdfd 100644
--- a/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cpp
+++ b/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cpp
@@ -168,6 +168,7 @@ Gfx::DecodedImageFrame* web_canvas_2d_image_source_frame(void* source_wrapper, C
bool web_canvas_2d_capture_video_frame(void* source_wrapper, CapturedVideoFrame* out_frame);
void* web_canvas_2d_video_transport(void* source_wrapper);
void web_canvas_2d_video_frame_hold_unref(Compositing::VideoFrameHold*);
+void web_canvas_2d_set_video_frame_copy(Optional<Gfx::DecodedImageFrame>* out_frame, Gfx::DecodedImageFrame const* frame);
// What Bindings/Rust/src/html/canvas_gradient.rs asks of LibWeb.
bool web_canvas_gradient_parse_color(FlatPtr color, Gfx::Color* out_colors);
@@ -817,6 +818,11 @@ void web_canvas_2d_video_frame_hold_unref(Compositing::VideoFrameHold* hold)
hold->unref();
}
+void web_canvas_2d_set_video_frame_copy(Optional<Gfx::DecodedImageFrame>* out_frame, Gfx::DecodedImageFrame const* frame)
+{
+ *out_frame = *frame;
+}
+
// https://drafts.csswg.org/css-color/#parse-a-css-color-value
// NB: The color is written in each predefined color space, in the order of Bindings::PredefinedColorSpace.
bool web_canvas_gradient_parse_color(FlatPtr color, Gfx::Color* out_colors)
diff --git a/Libraries/LibWeb/HTML/Canvas/RemoteCanvas2DTransportFFI.cpp b/Libraries/LibWeb/HTML/Canvas/RemoteCanvas2DTransportFFI.cpp
index b5ced3ad660..e26b7b0163f 100644
--- a/Libraries/LibWeb/HTML/Canvas/RemoteCanvas2DTransportFFI.cpp
+++ b/Libraries/LibWeb/HTML/Canvas/RemoteCanvas2DTransportFFI.cpp
@@ -50,7 +50,7 @@ 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);
+void* web_canvas_2d_image_frame_from_bitmap(void* bitmap, u8 color_space);
}
static RemoteCanvas2DTransport& transport_from(void* transport)
@@ -154,11 +154,12 @@ bool web_canvas_2d_bitmap_unpremultiplied_rgba_pixels(void* bitmap, u8 const** o
return true;
}
-// A Gfx::DecodedImageFrame of the bitmap, allocated with new, which takes over the reference to the bitmap.
-void* web_canvas_2d_image_frame_from_bitmap(void* bitmap)
+// A Gfx::DecodedImageFrame of the bitmap, whose pixels are in the color space, allocated with new, which takes over the
+// reference to the bitmap.
+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));
- return new Gfx::DecodedImageFrame { move(adopted_bitmap) };
+ return new Gfx::DecodedImageFrame { move(adopted_bitmap), gfx_color_space_for(predefined_color_space_from_underlying(color_space)) };
}
}
diff --git a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp
index 5ed4cbc211a..adbb98fa180 100644
--- a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp
+++ b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp
@@ -258,6 +258,11 @@ WebIDL::ExceptionOr<JS::Value> WindowOrWorkerGlobalScopeMixin::structured_clone(
return deserialized.deserialized;
}
+extern "C" {
+// Defined in Bindings/Rust/src/canvas_2d/exports.rs.
+bool web_canvas_2d_read_back_video_frame(void* video_wrapper, Optional<Gfx::DecodedImageFrame>* out_frame);
+}
+
static Compositor::CompositorHost* compositor_host_for(JS::Object& global_object)
{
Page* page = nullptr;
@@ -649,11 +654,43 @@ void WindowOrWorkerGlobalScopeMixin::create_image_bitmap_impl(JS::Realm& realm,
}));
},
// -> video
- [&](GC::Ref<HTMLVideoElement>) {
- dbgln("(STUBBED) createImageBitmap() for HTMLVideoElement");
- auto const error = JS::Error::create(realm, "Not Implemented: createImageBitmap() for HTMLVideoElement"sv);
- TemporaryExecutionContext const context { WebIDL::promise_realm(*p), TemporaryExecutionContext::CallbacksEnabled::Yes };
- WebIDL::reject_promise(*p, error);
+ [&](GC::Ref<HTMLVideoElement> video) {
+ // 1. If image's networkState attribute is NETWORK_EMPTY, then return a promise rejected with an
+ // "InvalidStateError" DOMException.
+ if (video->network_state() == HTMLMediaElement::NetworkState::Empty) {
+ WebIDL::reject_promise(*p, WebIDL::InvalidStateError::create("Video has no media resource"_utf16));
+ return;
+ }
+
+ // 2. Set imageBitmap's bitmap data to a copy of the frame at the current playback position, at the
+ // media resource's natural width and natural height (i.e., after any aspect-ratio correction has
+ // been applied), cropped to the source rectangle with formatting.
+ Optional<Gfx::DecodedImageFrame> video_frame;
+ auto wrapper = Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, video);
+ // AD-HOC: Reject promise with an "InvalidStateError" DOMException if the video has no frame to copy.
+ if (!web_canvas_2d_read_back_video_frame(wrapper.ptr(), &video_frame)) {
+ WebIDL::reject_promise(*p, WebIDL::InvalidStateError::create("Video has no frame"_utf16));
+ return;
+ }
+ auto cropped_bitmap_or_error = crop_to_the_source_rectangle_with_formatting(compositor_host_for(realm.global_object()), *video_frame, sx, sy, sw, sh, options);
+ // AD-HOC: Reject promise with an "InvalidStateError" DOMException on allocation failure
+ // Spec issue: https://github.com/whatwg/html/issues/3323
+ if (cropped_bitmap_or_error.is_error()) {
+ WebIDL::reject_promise(*p, WebIDL::InvalidStateError::create("Image size is invalid"_utf16));
+ return;
+ }
+ auto image_bitmap = ImageBitmap::create(cropped_bitmap_or_error.release_value());
+
+ // 3. If image is not origin-clean, then set the origin-clean flag of imageBitmap's bitmap to false.
+ if (image_is_not_origin_clean(video))
+ image_bitmap->set_origin_clean(false);
+
+ // 4. Queue a global task, using the bitmap task source, to resolve promise with imageBitmap.
+ queue_global_task(Task::Source::BitmapTask, realm.global_object(), GC::create_function(GC::Heap::the(), [p, image_bitmap] {
+ auto& realm = WebIDL::promise_realm(*p);
+ TemporaryExecutionContext const context { realm, TemporaryExecutionContext::CallbacksEnabled::Yes };
+ Bindings::resolve_image_bitmap_promise(realm, *p, image_bitmap);
+ }));
},
// -> img
// -> SVG image
diff --git a/Tests/LibWeb/Text/expected/HTML/createImageBitmap-video.txt b/Tests/LibWeb/Text/expected/HTML/createImageBitmap-video.txt
new file mode 100644
index 00000000000..9bcdbae25a5
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/HTML/createImageBitmap-video.txt
@@ -0,0 +1,5 @@
+ImageBitmap size: 300x200
+Cropped ImageBitmap size: 30x40
+Pixel in a srgb canvas is the color of the video: true
+Pixel in a display-p3 canvas is the color of the video: true
+A video without a media resource: InvalidStateError
diff --git a/Tests/LibWeb/Text/expected/wpt-import/html/canvas/element/manual/imagebitmap/createImageBitmap-invalid-args.txt b/Tests/LibWeb/Text/expected/wpt-import/html/canvas/element/manual/imagebitmap/createImageBitmap-invalid-args.txt
index b93052dd610..98be07e8087 100644
--- a/Tests/LibWeb/Text/expected/wpt-import/html/canvas/element/manual/imagebitmap/createImageBitmap-invalid-args.txt
+++ b/Tests/LibWeb/Text/expected/wpt-import/html/canvas/element/manual/imagebitmap/createImageBitmap-invalid-args.txt
@@ -2,8 +2,8 @@ Harness status: OK
Found 93 tests
-90 Pass
-3 Fail
+92 Pass
+1 Fail
Pass createImageBitmap with an HTMLCanvasElement source and sw set to 0
Pass createImageBitmap with an HTMLCanvasElement source and sh set to 0
Pass createImageBitmap with an HTMLCanvasElement source and oversized (unallocatable) crop region
@@ -13,14 +13,14 @@ Pass createImageBitmap with an HTMLCanvasElement source and a value between 0 an
Pass createImageBitmap with an HTMLCanvasElement source and a value between 0 and 1 in resizeHeight
Pass createImageBitmap with an HTMLVideoElement source and sw set to 0
Pass createImageBitmap with an HTMLVideoElement source and sh set to 0
-Fail createImageBitmap with an HTMLVideoElement source and oversized (unallocatable) crop region
+Pass createImageBitmap with an HTMLVideoElement source and oversized (unallocatable) crop region
Pass createImageBitmap with an HTMLVideoElement source and a value of 0 int resizeWidth
Pass createImageBitmap with an HTMLVideoElement source and a value of 0 in resizeHeight
Pass createImageBitmap with an HTMLVideoElement source and a value between 0 and 1 in resizeWidth
Pass createImageBitmap with an HTMLVideoElement source and a value between 0 and 1 in resizeHeight
Pass createImageBitmap with an HTMLVideoElement from a data URL source and sw set to 0
Pass createImageBitmap with an HTMLVideoElement from a data URL source and sh set to 0
-Fail createImageBitmap with an HTMLVideoElement from a data URL source and oversized (unallocatable) crop region
+Pass createImageBitmap with an HTMLVideoElement from a data URL source and oversized (unallocatable) crop region
Pass createImageBitmap with an HTMLVideoElement from a data URL source and a value of 0 int resizeWidth
Pass createImageBitmap with an HTMLVideoElement from a data URL source and a value of 0 in resizeHeight
Pass createImageBitmap with an HTMLVideoElement from a data URL source and a value between 0 and 1 in resizeWidth
diff --git a/Tests/LibWeb/Text/input/HTML/createImageBitmap-video.html b/Tests/LibWeb/Text/input/HTML/createImageBitmap-video.html
new file mode 100644
index 00000000000..0e9ebcfe7a7
--- /dev/null
+++ b/Tests/LibWeb/Text/input/HTML/createImageBitmap-video.html
@@ -0,0 +1,41 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ asyncTest(async done => {
+ const video = document.createElement("video");
+ video.preload = "auto";
+ await new Promise((resolve, reject) => {
+ video.oncanplaythrough = resolve;
+ video.onerror = reject;
+ video.src = "../wpt-import/html/canvas/element/manual/wide-gamut-canvas/resources/sRGB-BB0000.webm";
+ });
+
+ const bitmap = await createImageBitmap(video);
+ println(`ImageBitmap size: ${bitmap.width}x${bitmap.height}`);
+
+ const cropped = await createImageBitmap(video, 10, 20, 30, 40);
+ println(`Cropped ImageBitmap size: ${cropped.width}x${cropped.height}`);
+
+ for (const colorSpace of ["srgb", "display-p3"]) {
+ const canvas = document.createElement("canvas");
+ canvas.width = 4;
+ canvas.height = 4;
+ const context = canvas.getContext("2d", { colorSpace });
+ context.drawImage(bitmap, 0, 0);
+ const [red, green, blue, alpha] = context.getImageData(1, 1, 1, 1).data;
+ const expected = colorSpace === "srgb" ? [187, 0, 0] : [171, 35, 23];
+ const matches = Math.abs(red - expected[0]) <= 3 && Math.abs(green - expected[1]) <= 3 && Math.abs(blue - expected[2]) <= 3 && alpha === 255;
+ println(`Pixel in a ${colorSpace} canvas is the color of the video: ${matches}`);
+ }
+
+ video.removeAttribute("src");
+ video.load();
+ try {
+ await createImageBitmap(video);
+ println("FAIL: a video without a media resource made an ImageBitmap");
+ } catch (error) {
+ println(`A video without a media resource: ${error.name}`);
+ }
+ done();
+ });
+</script>