Truly independent web browser
LibGfx+LibWeb: Describe the canvas color space in serialized PNGs
Andreas Kling521765481ebd
diff --git a/Libraries/LibGfx/ImageFormats/PNGWriter.cpp b/Libraries/LibGfx/ImageFormats/PNGWriter.cppindex 1933b47a464..c43e9f75ea5 100644--- a/Libraries/LibGfx/ImageFormats/PNGWriter.cpp+++ b/Libraries/LibGfx/ImageFormats/PNGWriter.cpp@@ -47,6 +47,11 @@ ErrorOr<ByteBuffer> PNGWriter::encode(Gfx::Bitmap const& bitmap, Options optionspng_set_iCCP(png_ptr, info_ptr, "embedded profile", 0, options.icc_data->data(), options.icc_data->size());}+ if (options.cicp.has_value()) {+ auto const& cicp = *options.cicp;+ png_set_cICP(png_ptr, info_ptr, to_underlying(cicp.color_primaries()), to_underlying(cicp.transfer_characteristics()), to_underlying(cicp.matrix_coefficients()), to_underlying(cicp.video_full_range_flag()));+ }+if (bitmap.format() == BitmapFormat::BGRA8888 || bitmap.format() == BitmapFormat::BGRx8888) {png_set_bgr(png_ptr);}diff --git a/Libraries/LibGfx/ImageFormats/PNGWriter.h b/Libraries/LibGfx/ImageFormats/PNGWriter.hindex 7ce1f3aeb3e..1576f57d3d9 100644--- a/Libraries/LibGfx/ImageFormats/PNGWriter.h+++ b/Libraries/LibGfx/ImageFormats/PNGWriter.h@@ -10,6 +10,7 @@#include <AK/Optional.h>#include <AK/Span.h>#include <LibGfx/Forward.h>+#include <LibMediaCodecs/Color/CodingIndependentCodePoints.h>namespace Gfx {@@ -22,8 +23,10 @@ enum class PNGCompression : u8 {// This is not a nested struct to work around https://llvm.org/PR36684struct PNGWriterOptions {// Data for the iCCP chunk.- // FIXME: Allow writing cICP, sRGB, or gAMA instead too.+ // FIXME: Allow writing sRGB or gAMA instead too.Optional<ReadonlyBytes> icc_data;+ // Data for the cICP chunk, which describes the color space in place of an ICC profile.+ Optional<Media::CodingIndependentCodePoints> cicp {};PNGCompression compression { PNGCompression::Default };};diff --git a/Libraries/LibWeb/HTML/Canvas/CanvasHost.cpp b/Libraries/LibWeb/HTML/Canvas/CanvasHost.cppindex 5ae916dd389..1bc3caa3092 100644--- a/Libraries/LibWeb/HTML/Canvas/CanvasHost.cpp+++ b/Libraries/LibWeb/HTML/Canvas/CanvasHost.cpp@@ -11,6 +11,7 @@#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/WebGL/WebGLRenderingContextBase.h>namespace Web::HTML {@@ -82,6 +83,16 @@ Optional<Gfx::DecodedImageFrame> CanvasHost::get_frame_from_surface()return Gfx::DecodedImageFrame { *bitmap };}+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 Gfx::DecodedImageFrame { *bitmap };+}+// https://html.spec.whatwg.org/multipage/canvas.html#concept-canvas-origin-cleanbool CanvasHost::is_origin_clean() const{diff --git a/Libraries/LibWeb/HTML/Canvas/CanvasHost.h b/Libraries/LibWeb/HTML/Canvas/CanvasHost.hindex 7a6e2ff14f1..01ea474446b 100644--- a/Libraries/LibWeb/HTML/Canvas/CanvasHost.h+++ b/Libraries/LibWeb/HTML/Canvas/CanvasHost.h@@ -7,6 +7,7 @@#pragma once#include <AK/Optional.h>+#include <AK/Utf16View.h>#include <LibGfx/DecodedImageFrame.h>#include <LibGfx/Forward.h>#include <LibGfx/Size.h>@@ -43,6 +44,9 @@ public:virtual RefPtr<Gfx::Bitmap> get_bitmap_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 its+ // context if the file can include a color profile, and converted to sRGB otherwise.+ Optional<Gfx::DecodedImageFrame> get_frame_for_serialization(Utf16View type);virtual bool is_origin_clean() const;protected:diff --git a/Libraries/LibWeb/HTML/Canvas/SerializeBitmap.cpp b/Libraries/LibWeb/HTML/Canvas/SerializeBitmap.cppindex 9629ced9369..8c42abbefd8 100644--- a/Libraries/LibWeb/HTML/Canvas/SerializeBitmap.cpp+++ b/Libraries/LibWeb/HTML/Canvas/SerializeBitmap.cpp@@ -7,6 +7,7 @@#include <AK/Assertions.h>#include <AK/MemoryStream.h>#include <LibGfx/Bitmap.h>+#include <LibGfx/DecodedImageFrame.h>#include <LibGfx/ImageFormats/JPEGWriter.h>#include <LibGfx/ImageFormats/PNGWriter.h>#include <LibWeb/HTML/Canvas/SerializeBitmap.h>@@ -35,17 +36,46 @@ Utf16View serialized_bitmap_mime_type_to_utf16_view(SerializedBitmapMimeType mimVERIFY_NOT_REACHED();}+static bool type_is_jpeg(Utf16View type)+{+ return type.equals_ignoring_ascii_case(u"image/jpeg"sv);+}++bool serialization_of_the_bitmap_supports_color_profiles(Utf16View type)+{+ // NB: The color space of a canvas is described by coding-independent code points, which PNG can carry and JPEG+ // cannot. Every type that is not JPEG is serialized as PNG.+ return !type_is_jpeg(type);+}+// https://html.spec.whatwg.org/multipage/canvas.html#a-serialisation-of-the-bitmap-as-a-file-ErrorOr<SerializeBitmapResult> serialize_bitmap(Gfx::Bitmap const& bitmap, Utf16View type, Optional<double> quality)+ErrorOr<SerializeBitmapResult> serialize_bitmap(Gfx::DecodedImageFrame const& frame, Utf16View type, Optional<double> quality){+ auto const& bitmap = frame.bitmap();+ Optional<ReadonlyBytes> icc_data;+ Optional<Media::CodingIndependentCodePoints> cicp;+ frame.color_space().data().visit(+ [](Empty) { },+ [&](Gfx::ColorSpace::CICP const& color_space_cicp) {+ cicp = Media::CodingIndependentCodePoints { color_space_cicp.color_primaries, color_space_cicp.transfer_characteristics, Media::MatrixCoefficients::Identity, Media::VideoFullRangeFlag::Full };+ },+ [&](NonnullRefPtr<Gfx::ColorSpace::ICCProfile const> const& icc_profile) {+ icc_data = icc_profile->bytes();+ });+// If type is an image format that supports variable quality (such as "image/jpeg"), quality is given, and type is not "image/png", then,// if quality is a Number in the range 0.0 to 1.0 inclusive, the user agent must treat quality as the desired quality level.// Otherwise, the user agent must use its default quality value, as if the quality argument had not been given.bool valid_quality = quality.has_value() and quality.value() >= 0.0 && quality.value() <= 1.0;- if (type.equals_ignoring_ascii_case(u"image/jpeg"sv)) {+ // For image types that support color profiles, the serialized image must include a color profile indicating the+ // color space of the underlying bitmap. For image types that do not support color profiles, the serialized image+ // must be converted to the 'srgb' color space using 'relative-colorimetric' rendering intent.+ if (type_is_jpeg(type)) {+ VERIFY(!cicp.has_value());AllocatingMemoryStream file;Gfx::JPEGWriter::Options jpeg_options;+ jpeg_options.icc_data = icc_data;if (valid_quality)jpeg_options.quality = static_cast<int>(quality.value() * 100);TRY(Gfx::JPEGWriter::encode(file, bitmap, jpeg_options));@@ -54,7 +84,7 @@ ErrorOr<SerializeBitmapResult> serialize_bitmap(Gfx::Bitmap const& bitmap, Utf16// User agents must support PNG ("image/png"). User agents may support other types.// If the user agent does not support the requested type, then it must create the file using the PNG format. [PNG]- return SerializeBitmapResult { TRY(Gfx::PNGWriter::encode(bitmap)), SerializedBitmapMimeType::PNG };+ return SerializeBitmapResult { TRY(Gfx::PNGWriter::encode(bitmap, { .icc_data = icc_data, .cicp = cicp })), SerializedBitmapMimeType::PNG };}}diff --git a/Libraries/LibWeb/HTML/Canvas/SerializeBitmap.h b/Libraries/LibWeb/HTML/Canvas/SerializeBitmap.hindex 07a4b2b4a6f..d8e19a18594 100644--- a/Libraries/LibWeb/HTML/Canvas/SerializeBitmap.h+++ b/Libraries/LibWeb/HTML/Canvas/SerializeBitmap.h@@ -26,7 +26,13 @@ struct SerializeBitmapResult {StringView serialized_bitmap_mime_type_to_byte_string(SerializedBitmapMimeType);Utf16View serialized_bitmap_mime_type_to_utf16_view(SerializedBitmapMimeType);+// Whether a serialization of the bitmap as a file of the type includes a color profile that indicates the color space+// of the bitmap. The bitmap of any other file is converted to sRGB.+bool serialization_of_the_bitmap_supports_color_profiles(Utf16View type);+// https://html.spec.whatwg.org/multipage/canvas.html#a-serialisation-of-the-bitmap-as-a-file-ErrorOr<SerializeBitmapResult> serialize_bitmap(Gfx::Bitmap const& bitmap, Utf16View type, Optional<double> quality);+// NB: The bitmap of the frame is in the color space of the frame, which has to be sRGB unless the type supports color+// profiles.+ErrorOr<SerializeBitmapResult> serialize_bitmap(Gfx::DecodedImageFrame const&, Utf16View type, Optional<double> quality);}diff --git a/Libraries/LibWeb/HTML/HTMLCanvasElement.cpp b/Libraries/LibWeb/HTML/HTMLCanvasElement.cppindex dd09bf6e054..9a753a1056b 100644--- a/Libraries/LibWeb/HTML/HTMLCanvasElement.cpp+++ b/Libraries/LibWeb/HTML/HTMLCanvasElement.cpp@@ -406,10 +406,10 @@ WebIDL::ExceptionOr<Utf16String> HTMLCanvasElement::to_data_url(Utf16View type,// 2. If this canvas element's bitmap has no pixels (i.e. either its horizontal dimension or its vertical dimension is zero),// then return the string "data:,". (This is the shortest data: URL; it represents the empty string in a text/plain resource.)- auto bitmap = get_bitmap_from_surface();+ auto bitmap = get_frame_for_serialization(type);if (!is_origin_clean())return WebIDL::SecurityError::create(HTML::relevant_realm(*this), "Canvas is not origin-clean"_utf16);- if (!bitmap)+ if (!bitmap.has_value())return "data:,"_utf16;// 3. Let file be a serialization of this canvas element's bitmap as a file, passing type and quality if given.@@ -441,7 +441,7 @@ WebIDL::ExceptionOr<void> HTMLCanvasElement::to_blob(GC::Ref<WebIDL::CallbackTyp// 2. Let result be null.// 3. If this canvas element's bitmap has pixels (i.e., neither its horizontal dimension nor its vertical dimension is zero),// then set result to a copy of this canvas element's bitmap.- auto bitmap_result = get_bitmap_from_surface();+ auto bitmap_result = get_frame_for_serialization(type);if (!is_origin_clean())return WebIDL::SecurityError::create(HTML::relevant_realm(*this), "Canvas is not origin-clean"_utf16);@@ -451,7 +451,7 @@ WebIDL::ExceptionOr<void> HTMLCanvasElement::to_blob(GC::Ref<WebIDL::CallbackTypPlatform::EventLoopPlugin::the().deferred_invoke(GC::create_function(heap(), [this, callback, bitmap_result, type = move(type_string), quality] {// 1. If result is non-null, then set result to a serialization of result as a file with type and quality if given.Optional<SerializeBitmapResult> file_result;- if (bitmap_result) {+ if (bitmap_result.has_value()) {if (auto result = serialize_bitmap(*bitmap_result, type, quality); !result.is_error())file_result = result.release_value();}diff --git a/Libraries/LibWeb/HTML/OffscreenCanvas.cpp b/Libraries/LibWeb/HTML/OffscreenCanvas.cppindex 58cdc2693d2..28affec7dd5 100644--- a/Libraries/LibWeb/HTML/OffscreenCanvas.cpp+++ b/Libraries/LibWeb/HTML/OffscreenCanvas.cpp@@ -424,8 +424,10 @@ GC::Ref<WebIDL::Promise> convert_to_blob(JS::Realm& realm, HTML::OffscreenCanvasreturn WebIDL::create_rejected_promise_for(offscreen_canvas.relevant_global_object(), error);}+ auto image_encode_options = options.value_or({});+// 4. Let bitmap be a copy of this's bitmap.- auto bitmap = offscreen_canvas.get_bitmap_from_surface();+ auto bitmap = offscreen_canvas.get_frame_for_serialization(image_encode_options.type);// 5. Let result be a new promise object.auto result_promise = WebIDL::create_promise_for(offscreen_canvas.relevant_global_object());@@ -433,14 +435,12 @@ GC::Ref<WebIDL::Promise> convert_to_blob(JS::Realm& realm, HTML::OffscreenCanvas// 6. Let global be this's relevant global object.auto& global = offscreen_canvas.relevant_global_object();- auto image_encode_options = options.value_or({});-// 7. Run these steps in parallel:Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [realm = GC::Ref(realm), &global, result_promise, bitmap, image_encode_options] {// 1. Let file be a serialization of bitmap as a file, with options's type and quality if present.Optional<HTML::SerializeBitmapResult> file_result {};- if (bitmap) {+ if (bitmap.has_value()) {if (auto result = HTML::serialize_bitmap(*bitmap, image_encode_options.type, image_encode_options.quality); !result.is_error())file_result = result.release_value();}diff --git a/Tests/LibWeb/Text/expected/wpt-import/html/canvas/element/wide-gamut-canvas/2d.color.space.toBlob.convert.txt b/Tests/LibWeb/Text/expected/wpt-import/html/canvas/element/wide-gamut-canvas/2d.color.space.toBlob.convert.txtindex 2d912e24262..d41836c08f3 100644--- a/Tests/LibWeb/Text/expected/wpt-import/html/canvas/element/wide-gamut-canvas/2d.color.space.toBlob.convert.txt+++ b/Tests/LibWeb/Text/expected/wpt-import/html/canvas/element/wide-gamut-canvas/2d.color.space.toBlob.convert.txt@@ -2,9 +2,8 @@ Harness status: OKFound 4 tests-2 Pass-2 Fail+4 PassPass Test toBlob color space preservation and conversion from a srgb canvasPass Test toBlob color space preservation and conversion from a srgb-linear canvas-Fail Test toBlob color space preservation and conversion from a display-p3 canvas-Fail Test toBlob color space preservation and conversion from a display-p3-linear canvas\ No newline at end of file+Pass Test toBlob color space preservation and conversion from a display-p3 canvas+Pass Test toBlob color space preservation and conversion from a display-p3-linear canvas\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/html/canvas/element/wide-gamut-canvas/2d.color.space.toDataURL.convert.txt b/Tests/LibWeb/Text/expected/wpt-import/html/canvas/element/wide-gamut-canvas/2d.color.space.toDataURL.convert.txtindex e75edf14fe6..1ae4fceadbf 100644--- a/Tests/LibWeb/Text/expected/wpt-import/html/canvas/element/wide-gamut-canvas/2d.color.space.toDataURL.convert.txt+++ b/Tests/LibWeb/Text/expected/wpt-import/html/canvas/element/wide-gamut-canvas/2d.color.space.toDataURL.convert.txt@@ -2,9 +2,8 @@ Harness status: OKFound 4 tests-2 Pass-2 Fail+4 PassPass Test toDataURL color space preservation and conversion from a srgb canvasPass Test toDataURL color space preservation and conversion from a srgb-linear canvas-Fail Test toDataURL color space preservation and conversion from a display-p3 canvas-Fail Test toDataURL color space preservation and conversion from a display-p3-linear canvas\ No newline at end of file+Pass Test toDataURL color space preservation and conversion from a display-p3 canvas+Pass Test toDataURL color space preservation and conversion from a display-p3-linear canvas\ No newline at end of file