From f51ea3b01f15a2a01a7bb68c70e1b98ce755a464 Mon Sep 17 00:00:00 2001 From: gaaclarke <30870216+gaaclarke@users.noreply.github.com> Date: Fri, 10 Feb 2023 16:08:20 -0800 Subject: [PATCH] [Impeller] Adds wide gamut support for iOS. (flutter/engine#39111) * Implemented wide gamut images for iOS Moved the surface to an extended range color format. * wrong gamma but default pixel format set to bgra10_xr * BGR10_XR add * format * updated todos * updated todo with information about pixel formats * switched logic for determining if we have a wide gamut image * cleaned up gamut math to match style and linked source * made the color attachment pixel format match the surface * updated vulkan format switch * removed comment * added enable disable switch * moved default to bgr10 for now since there is a bug where someone is still reading this, msaa? * fixed the decoder settings to make sure we don't lose wide gamut colors * fixed stored srgb gamut variable * fixed false lint * updated test * added ability to grab the surface data for tests * made the screenshot utility return the format * added width and height to the platform channel payload * fixed a couple of broken targets * moved back the default pixel buffer format * cleanup and add docstrings * made the surfacedata feature only available in debug builds * added decoding unit test * fixed objc tests * turned off by default * bdero feedback1 * bdero2 * bdero3 * fixed merge issue * removed using std::shared_ptr --- engine/src/flutter/common/settings.h | 12 +++ engine/src/flutter/flow/surface.cc | 4 + engine/src/flutter/flow/surface.h | 12 +++ .../renderer/backend/gles/texture_gles.cc | 6 ++ .../renderer/backend/metal/formats_mtl.h | 17 ++++ .../renderer/backend/metal/formats_mtl.mm | 16 ++++ .../renderer/backend/metal/surface_mtl.h | 4 +- .../renderer/backend/metal/surface_mtl.mm | 2 +- .../renderer/backend/vulkan/formats_vk.h | 2 + .../src/flutter/impeller/renderer/formats.h | 5 +- engine/src/flutter/lib/ui/BUILD.gn | 1 + .../flutter/lib/ui/fixtures/DisplayP3Logo.png | Bin 0 -> 3025 bytes .../flutter/lib/ui/painting/image_decoder.cc | 4 +- .../lib/ui/painting/image_decoder_impeller.cc | 84 +++++++++++++++--- .../lib/ui/painting/image_decoder_impeller.h | 7 +- .../ui/painting/image_decoder_unittests.cc | 67 +++++++++++++- engine/src/flutter/shell/common/rasterizer.cc | 20 ++++- engine/src/flutter/shell/common/rasterizer.h | 16 +++- .../shell/gpu/gpu_surface_metal_impeller.h | 6 ++ .../shell/gpu/gpu_surface_metal_impeller.mm | 43 +++++++++ .../platform/android/android_shell_holder.cc | 2 +- .../framework/Source/FlutterDartProject.mm | 10 +++ .../Source/FlutterDartProject_Internal.h | 2 + .../ios/framework/Source/FlutterEngine.mm | 35 ++++++++ .../framework/Source/FlutterEngine_Internal.h | 2 + .../darwin/ios/framework/Source/FlutterView.h | 3 +- .../ios/framework/Source/FlutterView.mm | 36 +++++++- .../framework/Source/FlutterViewController.mm | 8 +- .../Source/FlutterViewControllerTest.mm | 1 + .../ios/framework/Source/FlutterViewTest.mm | 4 +- .../Source/accessibility_bridge_test.mm | 12 ++- .../darwin/ios/ios_surface_metal_impeller.mm | 71 ++++++++++++++- 32 files changed, 474 insertions(+), 40 deletions(-) create mode 100644 engine/src/flutter/lib/ui/fixtures/DisplayP3Logo.png diff --git a/engine/src/flutter/common/settings.h b/engine/src/flutter/common/settings.h index 75f1e262fb..755621c0f6 100644 --- a/engine/src/flutter/common/settings.h +++ b/engine/src/flutter/common/settings.h @@ -96,6 +96,15 @@ struct Settings { ~Settings(); + /// Determines if attempts at grabbing the Surface's SurfaceData can be + /// attempted. + static constexpr bool kSurfaceDataAccessible = +#ifdef _NDEBUG + false; +#else + true; +#endif + // VM settings std::string vm_snapshot_data_path; // deprecated MappingCallback vm_snapshot_data; @@ -199,6 +208,9 @@ struct Settings { // Selects the SkParagraph implementation of the text layout engine. bool enable_skparagraph = false; + // Enable the rendering of colors outside of the sRGB gamut. + bool enable_wide_gamut = false; + // Enable the Impeller renderer on supported platforms. Ignored if Impeller is // not supported on the platform. bool enable_impeller = false; diff --git a/engine/src/flutter/flow/surface.cc b/engine/src/flutter/flow/surface.cc index 61d1fc87d1..fbd3d427c2 100644 --- a/engine/src/flutter/flow/surface.cc +++ b/engine/src/flutter/flow/surface.cc @@ -30,4 +30,8 @@ impeller::AiksContext* Surface::GetAiksContext() const { return nullptr; } +Surface::SurfaceData Surface::GetSurfaceData() const { + return {}; +} + } // namespace flutter diff --git a/engine/src/flutter/flow/surface.h b/engine/src/flutter/flow/surface.h index 8db5d1f90b..432987b50f 100644 --- a/engine/src/flutter/flow/surface.h +++ b/engine/src/flutter/flow/surface.h @@ -21,6 +21,12 @@ namespace flutter { /// Abstract Base Class that represents where we will be rendering content. class Surface { public: + /// A screenshot of the surface's raw data. + struct SurfaceData { + std::string pixel_format; + sk_sp data; + }; + Surface(); virtual ~Surface(); @@ -43,6 +49,12 @@ class Surface { virtual impeller::AiksContext* GetAiksContext() const; + /// Capture the `SurfaceData` currently present in the surface. + /// + /// Not guaranteed to work on all setups and not intended to be used in + /// production. The data field will be null if it was unable to work. + virtual SurfaceData GetSurfaceData() const; + private: FML_DISALLOW_COPY_AND_ASSIGN(Surface); }; diff --git a/engine/src/flutter/impeller/renderer/backend/gles/texture_gles.cc b/engine/src/flutter/impeller/renderer/backend/gles/texture_gles.cc index 191e6c9d65..14933adbdb 100644 --- a/engine/src/flutter/impeller/renderer/backend/gles/texture_gles.cc +++ b/engine/src/flutter/impeller/renderer/backend/gles/texture_gles.cc @@ -122,6 +122,8 @@ struct TexImage2DData { case PixelFormat::kD32FloatS8UInt: case PixelFormat::kR8UNormInt: case PixelFormat::kR8G8UNormInt: + case PixelFormat::kB10G10R10XRSRGB: + case PixelFormat::kB10G10R10XR: return; } is_valid_ = true; @@ -167,6 +169,8 @@ struct TexImage2DData { case PixelFormat::kD32FloatS8UInt: case PixelFormat::kR8UNormInt: case PixelFormat::kR8G8UNormInt: + case PixelFormat::kB10G10R10XRSRGB: + case PixelFormat::kB10G10R10XR: return; } is_valid_ = true; @@ -312,6 +316,8 @@ static std::optional ToRenderBufferFormat(PixelFormat format) { case PixelFormat::kR8G8UNormInt: case PixelFormat::kR8G8B8A8UNormIntSRGB: case PixelFormat::kB8G8R8A8UNormIntSRGB: + case PixelFormat::kB10G10R10XRSRGB: + case PixelFormat::kB10G10R10XR: return std::nullopt; } FML_UNREACHABLE(); diff --git a/engine/src/flutter/impeller/renderer/backend/metal/formats_mtl.h b/engine/src/flutter/impeller/renderer/backend/metal/formats_mtl.h index 056c9a7314..f03c3aeb9b 100644 --- a/engine/src/flutter/impeller/renderer/backend/metal/formats_mtl.h +++ b/engine/src/flutter/impeller/renderer/backend/metal/formats_mtl.h @@ -37,12 +37,25 @@ constexpr PixelFormat FromMTLPixelFormat(MTLPixelFormat format) { return PixelFormat::kS8UInt; case MTLPixelFormatDepth32Float_Stencil8: return PixelFormat::kD32FloatS8UInt; + case MTLPixelFormatBGR10_XR_sRGB: + return PixelFormat::kB10G10R10XRSRGB; + case MTLPixelFormatBGR10_XR: + return PixelFormat::kB10G10R10XR; default: return PixelFormat::kUnknown; } return PixelFormat::kUnknown; } +/// Safe accessor for MTLPixelFormatBGR10_XR_sRGB. +/// Returns PixelFormat::kUnknown if MTLPixelFormatBGR10_XR_sRGB isn't +/// supported. +MTLPixelFormat SafeMTLPixelFormatBGR10_XR_sRGB(); + +/// Safe accessor for MTLPixelFormatBGR10_XR. +/// Returns PixelFormat::kUnknown if MTLPixelFormatBGR10_XR isn't supported. +MTLPixelFormat SafeMTLPixelFormatBGR10_XR(); + constexpr MTLPixelFormat ToMTLPixelFormat(PixelFormat format) { switch (format) { case PixelFormat::kUnknown: @@ -69,6 +82,10 @@ constexpr MTLPixelFormat ToMTLPixelFormat(PixelFormat format) { return MTLPixelFormatStencil8; case PixelFormat::kD32FloatS8UInt: return MTLPixelFormatDepth32Float_Stencil8; + case PixelFormat::kB10G10R10XRSRGB: + return SafeMTLPixelFormatBGR10_XR_sRGB(); + case PixelFormat::kB10G10R10XR: + return SafeMTLPixelFormatBGR10_XR(); } return MTLPixelFormatInvalid; }; diff --git a/engine/src/flutter/impeller/renderer/backend/metal/formats_mtl.mm b/engine/src/flutter/impeller/renderer/backend/metal/formats_mtl.mm index 3d88d59c52..48d86a279c 100644 --- a/engine/src/flutter/impeller/renderer/backend/metal/formats_mtl.mm +++ b/engine/src/flutter/impeller/renderer/backend/metal/formats_mtl.mm @@ -104,4 +104,20 @@ MTLTextureDescriptor* ToMTLTextureDescriptor(const TextureDescriptor& desc) { return mtl_desc; } +MTLPixelFormat SafeMTLPixelFormatBGR10_XR_sRGB() { + if (@available(iOS 11, macOS 11.0, *)) { + return MTLPixelFormatBGR10_XR_sRGB; + } else { + return MTLPixelFormatInvalid; + } +} + +MTLPixelFormat SafeMTLPixelFormatBGR10_XR() { + if (@available(iOS 10, macOS 11.0, *)) { + return MTLPixelFormatBGR10_XR; + } else { + return MTLPixelFormatInvalid; + } +} + } // namespace impeller diff --git a/engine/src/flutter/impeller/renderer/backend/metal/surface_mtl.h b/engine/src/flutter/impeller/renderer/backend/metal/surface_mtl.h index e922b8ac46..e641dd6c23 100644 --- a/engine/src/flutter/impeller/renderer/backend/metal/surface_mtl.h +++ b/engine/src/flutter/impeller/renderer/backend/metal/surface_mtl.h @@ -32,7 +32,7 @@ class SurfaceMTL final : public Surface { /// /// @return A pointer to the wrapped surface or null. /// - static std::unique_ptr WrapCurrentMetalLayerDrawable( + static std::unique_ptr WrapCurrentMetalLayerDrawable( const std::shared_ptr& context, CAMetalLayer* layer); #pragma GCC diagnostic pop @@ -40,6 +40,8 @@ class SurfaceMTL final : public Surface { // |Surface| ~SurfaceMTL() override; + id drawable() const { return drawable_; } + private: id drawable_ = nil; diff --git a/engine/src/flutter/impeller/renderer/backend/metal/surface_mtl.mm b/engine/src/flutter/impeller/renderer/backend/metal/surface_mtl.mm index 1a2d06b09c..09302c26dc 100644 --- a/engine/src/flutter/impeller/renderer/backend/metal/surface_mtl.mm +++ b/engine/src/flutter/impeller/renderer/backend/metal/surface_mtl.mm @@ -15,7 +15,7 @@ namespace impeller { #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunguarded-availability-new" -std::unique_ptr SurfaceMTL::WrapCurrentMetalLayerDrawable( +std::unique_ptr SurfaceMTL::WrapCurrentMetalLayerDrawable( const std::shared_ptr& context, CAMetalLayer* layer) { TRACE_EVENT0("impeller", "SurfaceMTL::WrapCurrentMetalLayerDrawable"); diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/formats_vk.h b/engine/src/flutter/impeller/renderer/backend/vulkan/formats_vk.h index 10441c3624..a9074f661e 100644 --- a/engine/src/flutter/impeller/renderer/backend/vulkan/formats_vk.h +++ b/engine/src/flutter/impeller/renderer/backend/vulkan/formats_vk.h @@ -137,6 +137,8 @@ constexpr std::optional ToVKShaderStageFlagBits( constexpr vk::Format ToVKImageFormat(PixelFormat format) { switch (format) { case PixelFormat::kUnknown: + case PixelFormat::kB10G10R10XR: + case PixelFormat::kB10G10R10XRSRGB: return vk::Format::eUndefined; case PixelFormat::kA8UNormInt: return vk::Format::eR8Unorm; diff --git a/engine/src/flutter/impeller/renderer/formats.h b/engine/src/flutter/impeller/renderer/formats.h index 12015586c9..065d38a9fa 100644 --- a/engine/src/flutter/impeller/renderer/formats.h +++ b/engine/src/flutter/impeller/renderer/formats.h @@ -89,7 +89,8 @@ enum class PixelFormat { kB8G8R8A8UNormIntSRGB, kR32G32B32A32Float, kR16G16B16A16Float, - + kB10G10R10XR, + kB10G10R10XRSRGB, // Depth and stencil formats. kS8UInt, kD32FloatS8UInt, @@ -289,6 +290,8 @@ constexpr size_t BytesPerPixelForPixelFormat(PixelFormat format) { case PixelFormat::kR8G8B8A8UNormIntSRGB: case PixelFormat::kB8G8R8A8UNormInt: case PixelFormat::kB8G8R8A8UNormIntSRGB: + case PixelFormat::kB10G10R10XRSRGB: + case PixelFormat::kB10G10R10XR: return 4u; case PixelFormat::kD32FloatS8UInt: return 5u; diff --git a/engine/src/flutter/lib/ui/BUILD.gn b/engine/src/flutter/lib/ui/BUILD.gn index 1556126b2d..b0c3ce3dfd 100644 --- a/engine/src/flutter/lib/ui/BUILD.gn +++ b/engine/src/flutter/lib/ui/BUILD.gn @@ -212,6 +212,7 @@ if (enable_unittests) { fixtures = [ "fixtures/DashInNooglerHat.jpg", "fixtures/DashInNooglerHat%20WithSpace.jpg", + "fixtures/DisplayP3Logo.png", "fixtures/Horizontal.jpg", "fixtures/Horizontal.png", "fixtures/hello_loop_2.gif", diff --git a/engine/src/flutter/lib/ui/fixtures/DisplayP3Logo.png b/engine/src/flutter/lib/ui/fixtures/DisplayP3Logo.png new file mode 100644 index 0000000000000000000000000000000000000000..32f032bae3de42c8c7ba9529d2d18ad41e81bede GIT binary patch literal 3025 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 literal 0 HcmV?d00001 diff --git a/engine/src/flutter/lib/ui/painting/image_decoder.cc b/engine/src/flutter/lib/ui/painting/image_decoder.cc index dabdb2b751..905ffe4b9d 100644 --- a/engine/src/flutter/lib/ui/painting/image_decoder.cc +++ b/engine/src/flutter/lib/ui/painting/image_decoder.cc @@ -22,8 +22,8 @@ std::unique_ptr ImageDecoder::Make( return std::make_unique( runners, // std::move(concurrent_task_runner), // - std::move(io_manager) // - ); + std::move(io_manager), // + settings.enable_wide_gamut); } #endif // IMPELLER_SUPPORTS_RENDERING return std::make_unique( diff --git a/engine/src/flutter/lib/ui/painting/image_decoder_impeller.cc b/engine/src/flutter/lib/ui/painting/image_decoder_impeller.cc index 6e13772f62..7558b4fd80 100644 --- a/engine/src/flutter/lib/ui/painting/image_decoder_impeller.cc +++ b/engine/src/flutter/lib/ui/painting/image_decoder_impeller.cc @@ -23,11 +23,52 @@ namespace flutter { +namespace { +/** + * Loads the gamut as a set of three points (triangle). + */ +void LoadGamut(SkPoint abc[3], const skcms_Matrix3x3& xyz) { + // rx = rX / (rX + rY + rZ) + // ry = rY / (rX + rY + rZ) + // gx, gy, bx, and gy are calculated similarly. + for (int index = 0; index < 3; index++) { + float sum = xyz.vals[index][0] + xyz.vals[index][1] + xyz.vals[index][2]; + abc[index].fX = xyz.vals[index][0] / sum; + abc[index].fY = xyz.vals[index][1] / sum; + } +} + +/** + * Calculates the area of the triangular gamut. + */ +float CalculateArea(SkPoint abc[3]) { + const SkPoint& a = abc[0]; + const SkPoint& b = abc[1]; + const SkPoint& c = abc[2]; + return 0.5f * fabsf(a.fX * b.fY + b.fX * c.fY - a.fX * c.fY - c.fX * b.fY - + b.fX * a.fY); +} + +static constexpr float kSrgbD50GamutArea = 0.084f; + +// Source: +// https://source.chromium.org/chromium/_/skia/skia.git/+/393fb1ec80f41d8ad7d104921b6920e69749fda1:src/codec/SkAndroidCodec.cpp;l=67;drc=46572b4d445f41943059d0e377afc6d6748cd5ca;bpv=1;bpt=0 +bool IsWideGamut(const SkColorSpace& color_space) { + skcms_Matrix3x3 xyzd50; + color_space.toXYZD50(&xyzd50); + SkPoint rgb[3]; + LoadGamut(rgb, xyzd50); + return CalculateArea(rgb) > kSrgbD50GamutArea; +} +} // namespace + ImageDecoderImpeller::ImageDecoderImpeller( const TaskRunners& runners, std::shared_ptr concurrent_task_runner, - const fml::WeakPtr& io_manager) - : ImageDecoder(runners, std::move(concurrent_task_runner), io_manager) { + const fml::WeakPtr& io_manager, + bool supports_wide_gamut) + : ImageDecoder(runners, std::move(concurrent_task_runner), io_manager), + supports_wide_gamut_(supports_wide_gamut) { std::promise> context_promise; context_ = context_promise.get_future(); runners_.GetIOTaskRunner()->PostTask(fml::MakeCopyable( @@ -51,6 +92,8 @@ static std::optional ToPixelFormat(SkColorType type) { switch (type) { case kRGBA_8888_SkColorType: return impeller::PixelFormat::kR8G8B8A8UNormInt; + case kRGBA_F16_SkColorType: + return impeller::PixelFormat::kR16G16B16A16Float; default: return std::nullopt; } @@ -60,7 +103,8 @@ static std::optional ToPixelFormat(SkColorType type) { std::shared_ptr ImageDecoderImpeller::DecompressTexture( ImageDescriptor* descriptor, SkISize target_size, - impeller::ISize max_texture_size) { + impeller::ISize max_texture_size, + bool supports_wide_gamut) { TRACE_EVENT0("impeller", __FUNCTION__); if (!descriptor) { FML_DLOG(ERROR) << "Invalid descriptor."; @@ -85,11 +129,29 @@ std::shared_ptr ImageDecoderImpeller::DecompressTexture( /// const auto base_image_info = descriptor->image_info(); - const auto image_info = - base_image_info.makeWH(decode_size.width(), decode_size.height()) - .makeColorType(ChooseCompatibleColorType(base_image_info.colorType())) - .makeAlphaType( - ChooseCompatibleAlphaType(base_image_info.alphaType())); + const bool is_wide_gamut = + supports_wide_gamut ? IsWideGamut(*base_image_info.colorSpace()) : false; + SkAlphaType alpha_type = + ChooseCompatibleAlphaType(base_image_info.alphaType()); + SkImageInfo image_info; + if (is_wide_gamut) { + // TODO(gaaclarke): Branch on alpha_type so it's 32bpp for opaque images. + // I tried using kBGRA_1010102_SkColorType and + // kBGR_101010x_SkColorType but Skia fails to decode the + // image that way. + SkColorType color_type = kRGBA_F16_SkColorType; + image_info = + base_image_info.makeWH(decode_size.width(), decode_size.height()) + .makeColorType(color_type) + .makeAlphaType(alpha_type) + .makeColorSpace(SkColorSpace::MakeSRGB()); + } else { + image_info = + base_image_info.makeWH(decode_size.width(), decode_size.height()) + .makeColorType( + ChooseCompatibleColorType(base_image_info.colorType())) + .makeAlphaType(alpha_type); + } const auto pixel_format = ToPixelFormat(image_info.colorType()); if (!pixel_format.has_value()) { @@ -237,7 +299,8 @@ void ImageDecoderImpeller::Decode(fml::RefPtr descriptor, context = context_.get(), // target_size = SkISize::Make(target_width, target_height), // io_runner = runners_.GetIOTaskRunner(), // - result // + result, + supports_wide_gamut = supports_wide_gamut_ // ]() { FML_CHECK(context) << "No valid impeller context"; auto max_size_supported = @@ -245,7 +308,8 @@ void ImageDecoderImpeller::Decode(fml::RefPtr descriptor, // Always decompress on the concurrent runner. auto bitmap = - DecompressTexture(raw_descriptor, target_size, max_size_supported); + DecompressTexture(raw_descriptor, target_size, max_size_supported, + supports_wide_gamut); if (!bitmap) { result(nullptr); return; diff --git a/engine/src/flutter/lib/ui/painting/image_decoder_impeller.h b/engine/src/flutter/lib/ui/painting/image_decoder_impeller.h index fdaa0a600f..5764410ab5 100644 --- a/engine/src/flutter/lib/ui/painting/image_decoder_impeller.h +++ b/engine/src/flutter/lib/ui/painting/image_decoder_impeller.h @@ -22,7 +22,8 @@ class ImageDecoderImpeller final : public ImageDecoder { ImageDecoderImpeller( const TaskRunners& runners, std::shared_ptr concurrent_task_runner, - const fml::WeakPtr& io_manager); + const fml::WeakPtr& io_manager, + bool supports_wide_gamut); ~ImageDecoderImpeller() override; @@ -35,7 +36,8 @@ class ImageDecoderImpeller final : public ImageDecoder { static std::shared_ptr DecompressTexture( ImageDescriptor* descriptor, SkISize target_size, - impeller::ISize max_texture_size); + impeller::ISize max_texture_size, + bool supports_wide_gamut); static sk_sp UploadTexture( const std::shared_ptr& context, @@ -44,6 +46,7 @@ class ImageDecoderImpeller final : public ImageDecoder { private: using FutureContext = std::shared_future>; FutureContext context_; + const bool supports_wide_gamut_; FML_DISALLOW_COPY_AND_ASSIGN(ImageDecoderImpeller); }; diff --git a/engine/src/flutter/lib/ui/painting/image_decoder_unittests.cc b/engine/src/flutter/lib/ui/painting/image_decoder_unittests.cc index 4f91282281..a9b09c559a 100644 --- a/engine/src/flutter/lib/ui/painting/image_decoder_unittests.cc +++ b/engine/src/flutter/lib/ui/painting/image_decoder_unittests.cc @@ -272,6 +272,67 @@ TEST_F(ImageDecoderFixtureTest, ValidImageResultsInSuccess) { latch.Wait(); } +namespace { +float HalfToFloat(uint16_t half) { + switch (half) { + case 0x7c00: + return std::numeric_limits::infinity(); + case 0xfc00: + return -std::numeric_limits::infinity(); + } + bool negative = half >> 15; + uint16_t exponent = (half >> 10) & 0x1f; + uint16_t fraction = half & 0x3ff; + float fExponent = exponent - 15.0f; + float fFraction = static_cast(fraction) / 1024.f; + float pow_value = powf(2.0f, fExponent); + return (negative ? -1.f : 1.f) * pow_value * (1.0f + fFraction); +} +} // namespace + +TEST_F(ImageDecoderFixtureTest, ImpellerWideGamutDisplayP3) { + auto data = OpenFixtureAsSkData("DisplayP3Logo.png"); + auto image = SkImage::MakeFromEncoded(data); + ASSERT_TRUE(image != nullptr); + ASSERT_EQ(SkISize::Make(100, 100), image->dimensions()); + + ImageGeneratorRegistry registry; + std::shared_ptr generator = + registry.CreateCompatibleGenerator(data); + ASSERT_TRUE(generator); + + auto descriptor = fml::MakeRefCounted(std::move(data), + std::move(generator)); + +#if IMPELLER_SUPPORTS_RENDERING + std::shared_ptr wide_bitmap = + ImageDecoderImpeller::DecompressTexture( + descriptor.get(), SkISize::Make(100, 100), {100, 100}, + /*supports_wide_gamut=*/true); + ASSERT_EQ(wide_bitmap->colorType(), kRGBA_F16_SkColorType); + ASSERT_TRUE(wide_bitmap->colorSpace()->isSRGB()); + const SkPixmap& wide_pixmap = wide_bitmap->pixmap(); + const uint16_t* half_ptr = static_cast(wide_pixmap.addr()); + bool found_deep_red = false; + for (int i = 0; i < wide_pixmap.width() * wide_pixmap.height(); ++i) { + float red = HalfToFloat(*half_ptr++); + float green = HalfToFloat(*half_ptr++); + float blue = HalfToFloat(*half_ptr++); + half_ptr++; // alpha + if (fabsf(red - 1.0931f) < 0.01f && fabsf(green - -0.2268f) < 0.01f && + fabsf(blue - -0.1501f) < 0.01f) { + found_deep_red = true; + break; + } + } + ASSERT_TRUE(found_deep_red); + std::shared_ptr bitmap = ImageDecoderImpeller::DecompressTexture( + descriptor.get(), SkISize::Make(100, 100), {100, 100}, + /*supports_wide_gamut=*/false); + ASSERT_EQ(bitmap->colorType(), kRGBA_8888_SkColorType); +#endif // IMPELLER_SUPPORTS_RENDERING +} + TEST_F(ImageDecoderFixtureTest, ExifDataIsRespectedOnDecode) { auto loop = fml::ConcurrentMessageLoop::Create(); TaskRunners runners(GetCurrentTestName(), // label @@ -508,11 +569,13 @@ TEST(ImageDecoderTest, VerifySimpleDecoding) { #if IMPELLER_SUPPORTS_RENDERING ASSERT_EQ(ImageDecoderImpeller::DecompressTexture( - descriptor.get(), SkISize::Make(6, 2), {100, 100}) + descriptor.get(), SkISize::Make(6, 2), {100, 100}, + /*supports_wide_gamut=*/false) ->dimensions(), SkISize::Make(6, 2)); ASSERT_EQ(ImageDecoderImpeller::DecompressTexture( - descriptor.get(), SkISize::Make(60, 20), {10, 10}) + descriptor.get(), SkISize::Make(60, 20), {10, 10}, + /*supports_wide_gamut=*/false) ->dimensions(), SkISize::Make(10, 10)); #endif // IMPELLER_SUPPORTS_RENDERING diff --git a/engine/src/flutter/shell/common/rasterizer.cc b/engine/src/flutter/shell/common/rasterizer.cc index a9397aacaf..f301e43947 100644 --- a/engine/src/flutter/shell/common/rasterizer.cc +++ b/engine/src/flutter/shell/common/rasterizer.cc @@ -711,22 +711,32 @@ Rasterizer::Screenshot Rasterizer::ScreenshotLastLayerTree( } sk_sp data = nullptr; + std::string format; GrDirectContext* surface_context = surface_ ? surface_->GetContext() : nullptr; switch (type) { case ScreenshotType::SkiaPicture: + format = "ScreenshotType::SkiaPicture"; data = ScreenshotLayerTreeAsPicture(layer_tree, *compositor_context_); break; case ScreenshotType::UncompressedImage: + format = "ScreenshotType::UncompressedImage"; data = ScreenshotLayerTreeAsImage(layer_tree, *compositor_context_, surface_context, false); break; case ScreenshotType::CompressedImage: + format = "ScreenshotType::CompressedImage"; data = ScreenshotLayerTreeAsImage(layer_tree, *compositor_context_, surface_context, true); break; + case ScreenshotType::SurfaceData: { + Surface::SurfaceData surface_data = surface_->GetSurfaceData(); + format = surface_data.pixel_format; + data = surface_data.data; + break; + } } if (data == nullptr) { @@ -738,10 +748,10 @@ Rasterizer::Screenshot Rasterizer::ScreenshotLastLayerTree( size_t b64_size = SkBase64::Encode(data->data(), data->size(), nullptr); auto b64_data = SkData::MakeUninitialized(b64_size); SkBase64::Encode(data->data(), data->size(), b64_data->writable_data()); - return Rasterizer::Screenshot{b64_data, layer_tree->frame_size()}; + return Rasterizer::Screenshot{b64_data, layer_tree->frame_size(), format}; } - return Rasterizer::Screenshot{data, layer_tree->frame_size()}; + return Rasterizer::Screenshot{data, layer_tree->frame_size(), format}; } void Rasterizer::SetNextFrameCallback(const fml::closure& callback) { @@ -810,8 +820,10 @@ std::optional Rasterizer::GetResourceCacheMaxBytes() const { Rasterizer::Screenshot::Screenshot() {} -Rasterizer::Screenshot::Screenshot(sk_sp p_data, SkISize p_size) - : data(std::move(p_data)), frame_size(p_size) {} +Rasterizer::Screenshot::Screenshot(sk_sp p_data, + SkISize p_size, + const std::string& p_format) + : data(std::move(p_data)), frame_size(p_size), format(p_format) {} Rasterizer::Screenshot::Screenshot(const Screenshot& other) = default; diff --git a/engine/src/flutter/shell/common/rasterizer.h b/engine/src/flutter/shell/common/rasterizer.h index 32ff4de421..c529ea987d 100644 --- a/engine/src/flutter/shell/common/rasterizer.h +++ b/engine/src/flutter/shell/common/rasterizer.h @@ -287,6 +287,12 @@ class Rasterizer final : public SnapshotDelegate, /// container is used. /// CompressedImage, + + //-------------------------------------------------------------------------- + /// Reads the data directly from the Rasterizer's surface. The pixel format + /// is determined from the surface. This is the only way to read wide gamut + /// color data, but isn't supported everywhere. + SurfaceData, }; //---------------------------------------------------------------------------- @@ -307,6 +313,11 @@ class Rasterizer final : public SnapshotDelegate, /// SkISize frame_size = SkISize::MakeEmpty(); + //-------------------------------------------------------------------------- + /// Characterization of the format of the data in `data`. + /// + std::string format; + //-------------------------------------------------------------------------- /// @brief Creates an empty screenshot /// @@ -317,8 +328,11 @@ class Rasterizer final : public SnapshotDelegate, /// /// @param[in] p_data The screenshot data /// @param[in] p_size The screenshot size. + /// @param[in] p_format The screenshot format. /// - Screenshot(sk_sp p_data, SkISize p_size); + Screenshot(sk_sp p_data, + SkISize p_size, + const std::string& p_format); //-------------------------------------------------------------------------- /// @brief The copy constructor for a screenshot. diff --git a/engine/src/flutter/shell/gpu/gpu_surface_metal_impeller.h b/engine/src/flutter/shell/gpu/gpu_surface_metal_impeller.h index 3fda202a63..6254d851a5 100644 --- a/engine/src/flutter/shell/gpu/gpu_surface_metal_impeller.h +++ b/engine/src/flutter/shell/gpu/gpu_surface_metal_impeller.h @@ -5,8 +5,11 @@ #ifndef FLUTTER_SHELL_GPU_GPU_SURFACE_METAL_IMPELLER_H_ #define FLUTTER_SHELL_GPU_GPU_SURFACE_METAL_IMPELLER_H_ +#include + #include "flutter/flow/surface.h" #include "flutter/fml/macros.h" +#include "flutter/fml/platform/darwin/scoped_nsobject.h" #include "flutter/impeller/aiks/aiks_context.h" #include "flutter/impeller/renderer/renderer.h" #include "flutter/shell/gpu/gpu_surface_metal_delegate.h" @@ -24,10 +27,13 @@ class SK_API_AVAILABLE_CA_METAL_LAYER GPUSurfaceMetalImpeller : public Surface { // |Surface| bool IsValid() override; + virtual Surface::SurfaceData GetSurfaceData() const override; + private: const GPUSurfaceMetalDelegate* delegate_; std::shared_ptr impeller_renderer_; std::shared_ptr aiks_context_; + fml::scoped_nsprotocol> last_drawable_; // |Surface| std::unique_ptr AcquireFrame(const SkISize& size) override; diff --git a/engine/src/flutter/shell/gpu/gpu_surface_metal_impeller.mm b/engine/src/flutter/shell/gpu/gpu_surface_metal_impeller.mm index 686c3c5a92..b98c2be0ab 100644 --- a/engine/src/flutter/shell/gpu/gpu_surface_metal_impeller.mm +++ b/engine/src/flutter/shell/gpu/gpu_surface_metal_impeller.mm @@ -7,6 +7,7 @@ #import #import +#include "flutter/common/settings.h" #include "flutter/fml/make_copyable.h" #include "flutter/fml/mapping.h" #include "flutter/fml/trace_event.h" @@ -60,6 +61,9 @@ std::unique_ptr GPUSurfaceMetalImpeller::AcquireFrame(const SkISiz auto surface = impeller::SurfaceMTL::WrapCurrentMetalLayerDrawable( impeller_renderer_->GetContext(), mtl_layer); + if (Settings::kSurfaceDataAccessible) { + last_drawable_.reset([surface->drawable() retain]); + } SurfaceFrame::SubmitCallback submit_callback = fml::MakeCopyable([renderer = impeller_renderer_, // @@ -129,4 +133,43 @@ impeller::AiksContext* GPUSurfaceMetalImpeller::GetAiksContext() const { return aiks_context_.get(); } +Surface::SurfaceData GPUSurfaceMetalImpeller::GetSurfaceData() const { + if (!(last_drawable_ && [last_drawable_ conformsToProtocol:@protocol(CAMetalDrawable)])) { + return {}; + } + id metal_drawable = static_cast>(last_drawable_); + id texture = metal_drawable.texture; + int bytesPerPixel = 0; + std::string pixel_format; + switch (texture.pixelFormat) { + case MTLPixelFormatBGR10_XR: + bytesPerPixel = 4; + pixel_format = "MTLPixelFormatBGR10_XR"; + break; + case MTLPixelFormatBGRA10_XR: + bytesPerPixel = 8; + pixel_format = "MTLPixelFormatBGRA10_XR"; + break; + case MTLPixelFormatBGRA8Unorm: + bytesPerPixel = 4; + pixel_format = "MTLPixelFormatBGRA8Unorm"; + break; + default: + return {}; + } + + // Zero initialized so that errors are easier to find at the cost of + // performance. + sk_sp result = + SkData::MakeZeroInitialized(texture.width * texture.height * bytesPerPixel); + [texture getBytes:result->writable_data() + bytesPerRow:texture.width * bytesPerPixel + fromRegion:MTLRegionMake2D(0, 0, texture.width, texture.height) + mipmapLevel:0]; + return { + .pixel_format = pixel_format, + .data = result, + }; +} + } // namespace flutter diff --git a/engine/src/flutter/shell/platform/android/android_shell_holder.cc b/engine/src/flutter/shell/platform/android/android_shell_holder.cc index 79605a5743..dd2c34c468 100644 --- a/engine/src/flutter/shell/platform/android/android_shell_holder.cc +++ b/engine/src/flutter/shell/platform/android/android_shell_holder.cc @@ -296,7 +296,7 @@ Rasterizer::Screenshot AndroidShellHolder::Screenshot( Rasterizer::ScreenshotType type, bool base64_encode) { if (!IsValid()) { - return {nullptr, SkISize::MakeEmpty()}; + return {nullptr, SkISize::MakeEmpty(), ""}; } return shell_->Screenshot(type, base64_encode); } diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterDartProject.mm b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterDartProject.mm index d57393db6b..9ad9c1d89b 100644 --- a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterDartProject.mm +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterDartProject.mm @@ -160,6 +160,12 @@ flutter::Settings FLTDefaultSettingsForBundle(NSBundle* bundle) { NSNumber* enableSkParagraph = [mainBundle objectForInfoDictionaryKey:@"FLTEnableSkParagraph"]; settings.enable_skparagraph = (enableSkParagraph != nil) ? enableSkParagraph.boolValue : true; + // Whether to enable Impeller. + NSNumber* nsEnableWideGamut = [mainBundle objectForInfoDictionaryKey:@"FLTEnableWideGamut"]; + // TODO(gaaclarke): Make this value `on` by default (pending memory audit). + BOOL enableWideGamut = nsEnableWideGamut ? nsEnableWideGamut.boolValue : NO; + settings.enable_wide_gamut = enableWideGamut; + // Whether to enable Impeller. NSNumber* enableImpeller = [mainBundle objectForInfoDictionaryKey:@"FLTEnableImpeller"]; // Change the default only if the option is present. @@ -371,4 +377,8 @@ flutter::Settings FLTDefaultSettingsForBundle(NSBundle* bundle) { return @"io.flutter.flutter.app"; } +- (BOOL)isWideGamutEnabled { + return _settings.enable_wide_gamut; +} + @end diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterDartProject_Internal.h b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterDartProject_Internal.h index 0cd2cc95f2..c741a53478 100644 --- a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterDartProject_Internal.h +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterDartProject_Internal.h @@ -16,6 +16,8 @@ flutter::Settings FLTDefaultSettingsForBundle(NSBundle* bundle = nil); @interface FlutterDartProject () +@property(nonatomic, readonly) BOOL isWideGamutEnabled; + /** * This is currently used for *only for tests* to override settings. */ diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine.mm b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine.mm index 5113c963a0..9a94326c99 100644 --- a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine.mm +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine.mm @@ -134,6 +134,7 @@ static constexpr int kNumProfilerSamplesPerSec = 5; fml::scoped_nsobject _systemChannel; fml::scoped_nsobject _settingsChannel; fml::scoped_nsobject _keyEventChannel; + fml::scoped_nsobject _screenshotChannel; int64_t _nextTextureId; @@ -633,6 +634,36 @@ static constexpr int kNumProfilerSamplesPerSec = 5; initWithChannel:_restorationChannel.get() restorationEnabled:_restorationEnabled]); _spellCheckPlugin.reset([[FlutterSpellCheckPlugin alloc] init]); + + _screenshotChannel.reset([[FlutterMethodChannel alloc] + initWithName:@"flutter/screenshot" + binaryMessenger:self.binaryMessenger + codec:[FlutterStandardMethodCodec sharedInstance]]); + + [_screenshotChannel.get() + setMethodCallHandler:^(FlutterMethodCall* _Nonnull call, FlutterResult _Nonnull result) { + if (!(weakSelf.get() && weakSelf.get()->_shell && weakSelf.get()->_shell->IsSetup())) { + return result([FlutterError + errorWithCode:@"invalid_state" + message:@"Requesting screenshot while engine is not running." + details:nil]); + } + flutter::Rasterizer::Screenshot screenshot = + [weakSelf.get() screenshot:flutter::Rasterizer::ScreenshotType::SurfaceData + base64Encode:NO]; + if (!screenshot.data) { + return result([FlutterError errorWithCode:@"failure" + message:@"Unable to get screenshot." + details:nil]); + } + // TODO(gaaclarke): Find way to eliminate this data copy. + NSData* data = [NSData dataWithBytes:screenshot.data->writable_data() + length:screenshot.data->size()]; + NSString* format = [NSString stringWithCString:screenshot.format.c_str()]; + NSNumber* width = @(screenshot.frame_size.fWidth); + NSNumber* height = @(screenshot.frame_size.fHeight); + return result(@[ width, height, format, data ]); + }]; } - (void)maybeSetupPlatformViewChannels { @@ -1347,6 +1378,10 @@ static void SetEntryPoint(flutter::Settings* settings, NSString* entrypoint, NSS return *_threadHost; } +- (FlutterDartProject*)project { + return _dartProject.get(); +} + @end @implementation FlutterEngineRegistrar { diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine_Internal.h b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine_Internal.h index 15eaa54854..8a957ee709 100644 --- a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine_Internal.h +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine_Internal.h @@ -81,6 +81,8 @@ extern NSString* _Nonnull const kFlutterEngineWillDealloc; - (void)sendKeyEvent:(const FlutterKeyEvent&)event callback:(nullable FlutterKeyEventCallback)callback userData:(nullable void*)userData; + +@property(nonatomic, readonly, nonnull) FlutterDartProject* project; @end #endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTER_ENGINE_INTERNAL_H_ diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterView.h b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterView.h index a795953c82..2f5e26d7d4 100644 --- a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterView.h +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterView.h @@ -41,7 +41,8 @@ - (instancetype)initWithCoder:(NSCoder*)aDecoder NS_UNAVAILABLE; - (instancetype)initWithDelegate:(id)delegate - opaque:(BOOL)opaque NS_DESIGNATED_INITIALIZER; + opaque:(BOOL)opaque + enableWideGamut:(BOOL)isWideGamutEnabled NS_DESIGNATED_INITIALIZER; // Set by FlutterEngine or FlutterViewController to override software rendering. @property(class, nonatomic) BOOL forceSoftwareRendering; diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterView.mm b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterView.mm index dcab55d404..d0377d0033 100644 --- a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterView.mm +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterView.mm @@ -16,8 +16,16 @@ #import "flutter/shell/platform/darwin/ios/ios_surface_software.h" #include "third_party/skia/include/utils/mac/SkCGUtils.h" +static BOOL IsWideGamutSupported() { + // This predicates the decision on the capabilities of the iOS device's + // display. This means external displays will not support wide gamut if the + // device's display doesn't support it. It practice that should be never. + return UIScreen.mainScreen.traitCollection.displayGamut != UIDisplayGamutSRGB; +} + @implementation FlutterView { id _delegate; + BOOL _isWideGamutEnabled; } - (instancetype)init { @@ -35,7 +43,9 @@ return nil; } -- (instancetype)initWithDelegate:(id)delegate opaque:(BOOL)opaque { +- (instancetype)initWithDelegate:(id)delegate + opaque:(BOOL)opaque + enableWideGamut:(BOOL)isWideGamutEnabled { if (delegate == nil) { NSLog(@"FlutterView delegate was nil."); [self release]; @@ -46,6 +56,7 @@ if (self) { _delegate = delegate; + _isWideGamutEnabled = isWideGamutEnabled; self.layer.opaque = opaque; // This line is necessary. CoreAnimation(or UIKit) may take this to do @@ -60,10 +71,27 @@ - (void)layoutSubviews { if ([self.layer isKindOfClass:NSClassFromString(@"CAMetalLayer")]) { +// It is a known Apple bug that CAMetalLayer incorrectly reports its supported +// SDKs. It is, in fact, available since iOS 8. +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunguarded-availability-new" + CAMetalLayer* layer = (CAMetalLayer*)self.layer; +#pragma clang diagnostic pop CGFloat screenScale = [UIScreen mainScreen].scale; - self.layer.allowsGroupOpacity = YES; - self.layer.contentsScale = screenScale; - self.layer.rasterizationScale = screenScale; + layer.allowsGroupOpacity = YES; + layer.contentsScale = screenScale; + layer.rasterizationScale = screenScale; + layer.framebufferOnly = flutter::Settings::kSurfaceDataAccessible ? NO : YES; + if (_isWideGamutEnabled && IsWideGamutSupported()) { + CGColorSpaceRef srgb = CGColorSpaceCreateWithName(kCGColorSpaceExtendedSRGB); + layer.colorspace = srgb; + CFRelease(srgb); + if (self.opaque) { + layer.pixelFormat = MTLPixelFormatBGR10_XR; + } else { + layer.pixelFormat = MTLPixelFormatBGRA10_XR; + } + } } [super layoutSubviews]; diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController.mm b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController.mm index ced158a9ed..ecf2c70538 100644 --- a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController.mm +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController.mm @@ -161,7 +161,9 @@ typedef struct MouseState { } _engine.reset([engine retain]); _engineNeedsLaunch = NO; - _flutterView.reset([[FlutterView alloc] initWithDelegate:_engine opaque:self.isViewOpaque]); + _flutterView.reset([[FlutterView alloc] initWithDelegate:_engine + opaque:self.isViewOpaque + enableWideGamut:engine.project.isWideGamutEnabled]); _weakFactory = std::make_unique>(self); _ongoingTouches.reset([[NSMutableSet alloc] init]); @@ -236,7 +238,9 @@ typedef struct MouseState { _viewOpaque = YES; _engine = engine; - _flutterView.reset([[FlutterView alloc] initWithDelegate:_engine opaque:self.isViewOpaque]); + _flutterView.reset([[FlutterView alloc] initWithDelegate:_engine + opaque:self.isViewOpaque + enableWideGamut:project.isWideGamutEnabled]); [_engine.get() createShell:nil libraryURI:nil initialRoute:initialRoute]; _engineNeedsLaunch = YES; _ongoingTouches.reset([[NSMutableSet alloc] init]); diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewControllerTest.mm b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewControllerTest.mm index 1461ca0640..defa7fd537 100644 --- a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewControllerTest.mm +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewControllerTest.mm @@ -91,6 +91,7 @@ extern NSNotificationName const FlutterViewControllerWillDealloc; /// /// Used for testing deallocation. @interface MockEngine : NSObject +@property(nonatomic, strong) FlutterDartProject* project; @end @implementation MockEngine diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewTest.mm b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewTest.mm index d264933b0b..ed694afe85 100644 --- a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewTest.mm +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewTest.mm @@ -43,7 +43,7 @@ - (void)testFlutterViewEnableSemanticsWhenIsAccessibilityElementIsCalled { FakeDelegate* delegate = [[FakeDelegate alloc] init]; - FlutterView* view = [[FlutterView alloc] initWithDelegate:delegate opaque:NO]; + FlutterView* view = [[FlutterView alloc] initWithDelegate:delegate opaque:NO enableWideGamut:NO]; delegate.callbackCalled = NO; XCTAssertFalse(view.isAccessibilityElement); XCTAssertTrue(delegate.callbackCalled); @@ -51,7 +51,7 @@ - (void)testFlutterViewBackgroundColorIsNotNil { FakeDelegate* delegate = [[FakeDelegate alloc] init]; - FlutterView* view = [[FlutterView alloc] initWithDelegate:delegate opaque:NO]; + FlutterView* view = [[FlutterView alloc] initWithDelegate:delegate opaque:NO enableWideGamut:NO]; XCTAssertNotNil(view.backgroundColor); } diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/accessibility_bridge_test.mm b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/accessibility_bridge_test.mm index 9b978150e0..67dc27901f 100644 --- a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/accessibility_bridge_test.mm +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/accessibility_bridge_test.mm @@ -374,7 +374,9 @@ fml::RefPtr CreateNewThread(std::string name) { /*task_runners=*/runners); id engine = OCMClassMock([FlutterEngine class]); id mockFlutterViewController = OCMClassMock([FlutterViewController class]); - FlutterView* flutterView = [[FlutterView alloc] initWithDelegate:engine opaque:YES]; + FlutterView* flutterView = [[FlutterView alloc] initWithDelegate:engine + opaque:YES + enableWideGamut:NO]; OCMStub([mockFlutterViewController view]).andReturn(flutterView); std::string label = "some label"; auto bridge = std::make_unique( @@ -464,7 +466,9 @@ fml::RefPtr CreateNewThread(std::string name) { /*task_runners=*/runners); id engine = OCMClassMock([FlutterEngine class]); id mockFlutterViewController = OCMClassMock([FlutterViewController class]); - FlutterView* flutterView = [[FlutterView alloc] initWithDelegate:engine opaque:YES]; + FlutterView* flutterView = [[FlutterView alloc] initWithDelegate:engine + opaque:YES + enableWideGamut:NO]; OCMStub([mockFlutterViewController view]).andReturn(flutterView); std::string label = "some label"; @autoreleasepool { @@ -532,7 +536,9 @@ fml::RefPtr CreateNewThread(std::string name) { /*task_runners=*/runners); id engine = OCMClassMock([FlutterEngine class]); id mockFlutterViewController = OCMClassMock([FlutterViewController class]); - FlutterView* flutterView = [[FlutterView alloc] initWithDelegate:engine opaque:YES]; + FlutterView* flutterView = [[FlutterView alloc] initWithDelegate:engine + opaque:YES + enableWideGamut:NO]; OCMStub([mockFlutterViewController view]).andReturn(flutterView); std::string label = "some label"; @autoreleasepool { diff --git a/engine/src/flutter/shell/platform/darwin/ios/ios_surface_metal_impeller.mm b/engine/src/flutter/shell/platform/darwin/ios/ios_surface_metal_impeller.mm index 31dcd7a5e9..caf382d905 100644 --- a/engine/src/flutter/shell/platform/darwin/ios/ios_surface_metal_impeller.mm +++ b/engine/src/flutter/shell/platform/darwin/ios/ios_surface_metal_impeller.mm @@ -4,10 +4,74 @@ #import "flutter/shell/platform/darwin/ios/ios_surface_metal_impeller.h" +#include "flutter/impeller/renderer/backend/metal/formats_mtl.h" +#include "flutter/impeller/renderer/context.h" #include "flutter/shell/gpu/gpu_surface_metal_impeller.h" +namespace impeller { +namespace { + +// This appears to be the only safe way to override the +// GetColorAttachmentPixelFormat method. It is assumed in the Context that +// there will be one pixel format for the whole app which is not true. So, it +// is unsafe to mutate the Context and you cannot clone the Context at this +// level since the Context does not safely manage the MTLDevice. +class CustomColorAttachmentPixelFormatContext final : public Context { + public: + CustomColorAttachmentPixelFormatContext(const std::shared_ptr& context, + PixelFormat color_attachment_pixel_format) + : context_(context), color_attachment_pixel_format_(color_attachment_pixel_format) {} + + bool IsValid() const override { return context_->IsValid(); } + + std::shared_ptr GetResourceAllocator() const override { + return context_->GetResourceAllocator(); + } + + std::shared_ptr GetShaderLibrary() const override { + return context_->GetShaderLibrary(); + } + + std::shared_ptr GetSamplerLibrary() const override { + return context_->GetSamplerLibrary(); + } + + std::shared_ptr GetPipelineLibrary() const override { + return context_->GetPipelineLibrary(); + } + + std::shared_ptr CreateCommandBuffer() const override { + return context_->CreateCommandBuffer(); + } + + std::shared_ptr GetWorkQueue() const override { return context_->GetWorkQueue(); } + + std::shared_ptr GetGPUTracer() const override { return context_->GetGPUTracer(); } + + PixelFormat GetColorAttachmentPixelFormat() const override { + return color_attachment_pixel_format_; + } + + bool HasThreadingRestrictions() const override { return context_->HasThreadingRestrictions(); } + + bool SupportsOffscreenMSAA() const override { return context_->SupportsOffscreenMSAA(); } + + const BackendFeatures& GetBackendFeatures() const override { + return context_->GetBackendFeatures(); + } + + private: + std::shared_ptr context_; + PixelFormat color_attachment_pixel_format_; +}; +} // namespace +} // namespace impeller + namespace flutter { +using impeller::CustomColorAttachmentPixelFormatContext; +using impeller::FromMTLPixelFormat; + IOSSurfaceMetalImpeller::IOSSurfaceMetalImpeller(const fml::scoped_nsobject& layer, const std::shared_ptr& context) : IOSSurface(context), @@ -35,9 +99,10 @@ void IOSSurfaceMetalImpeller::UpdateStorageSizeIfNecessary() { // |IOSSurface| std::unique_ptr IOSSurfaceMetalImpeller::CreateGPUSurface(GrDirectContext*) { - return std::make_unique(this, // - impeller_context_ // - + auto context = std::make_shared( + impeller_context_, FromMTLPixelFormat(layer_.get().pixelFormat)); + return std::make_unique(this, // + context // ); }