[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
This commit is contained in:
gaaclarke
2023-02-10 16:08:20 -08:00
committed by GitHub
parent 93ef23fca0
commit f51ea3b01f
32 changed files with 474 additions and 40 deletions

View File

@@ -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;

View File

@@ -30,4 +30,8 @@ impeller::AiksContext* Surface::GetAiksContext() const {
return nullptr;
}
Surface::SurfaceData Surface::GetSurfaceData() const {
return {};
}
} // namespace flutter

View File

@@ -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<SkData> 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);
};

View File

@@ -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<GLenum> ToRenderBufferFormat(PixelFormat format) {
case PixelFormat::kR8G8UNormInt:
case PixelFormat::kR8G8B8A8UNormIntSRGB:
case PixelFormat::kB8G8R8A8UNormIntSRGB:
case PixelFormat::kB10G10R10XRSRGB:
case PixelFormat::kB10G10R10XR:
return std::nullopt;
}
FML_UNREACHABLE();

View File

@@ -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;
};

View File

@@ -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

View File

@@ -32,7 +32,7 @@ class SurfaceMTL final : public Surface {
///
/// @return A pointer to the wrapped surface or null.
///
static std::unique_ptr<Surface> WrapCurrentMetalLayerDrawable(
static std::unique_ptr<SurfaceMTL> WrapCurrentMetalLayerDrawable(
const std::shared_ptr<Context>& context,
CAMetalLayer* layer);
#pragma GCC diagnostic pop
@@ -40,6 +40,8 @@ class SurfaceMTL final : public Surface {
// |Surface|
~SurfaceMTL() override;
id<MTLDrawable> drawable() const { return drawable_; }
private:
id<MTLDrawable> drawable_ = nil;

View File

@@ -15,7 +15,7 @@ namespace impeller {
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunguarded-availability-new"
std::unique_ptr<Surface> SurfaceMTL::WrapCurrentMetalLayerDrawable(
std::unique_ptr<SurfaceMTL> SurfaceMTL::WrapCurrentMetalLayerDrawable(
const std::shared_ptr<Context>& context,
CAMetalLayer* layer) {
TRACE_EVENT0("impeller", "SurfaceMTL::WrapCurrentMetalLayerDrawable");

View File

@@ -137,6 +137,8 @@ constexpr std::optional<vk::ShaderStageFlagBits> 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;

View File

@@ -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;

View File

@@ -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",

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

View File

@@ -22,8 +22,8 @@ std::unique_ptr<ImageDecoder> ImageDecoder::Make(
return std::make_unique<ImageDecoderImpeller>(
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<ImageDecoderSkia>(

View File

@@ -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<fml::ConcurrentTaskRunner> concurrent_task_runner,
const fml::WeakPtr<IOManager>& io_manager)
: ImageDecoder(runners, std::move(concurrent_task_runner), io_manager) {
const fml::WeakPtr<IOManager>& io_manager,
bool supports_wide_gamut)
: ImageDecoder(runners, std::move(concurrent_task_runner), io_manager),
supports_wide_gamut_(supports_wide_gamut) {
std::promise<std::shared_ptr<impeller::Context>> context_promise;
context_ = context_promise.get_future();
runners_.GetIOTaskRunner()->PostTask(fml::MakeCopyable(
@@ -51,6 +92,8 @@ static std::optional<impeller::PixelFormat> 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<impeller::PixelFormat> ToPixelFormat(SkColorType type) {
std::shared_ptr<SkBitmap> 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<SkBitmap> 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<ImageDescriptor> 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<ImageDescriptor> 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;

View File

@@ -22,7 +22,8 @@ class ImageDecoderImpeller final : public ImageDecoder {
ImageDecoderImpeller(
const TaskRunners& runners,
std::shared_ptr<fml::ConcurrentTaskRunner> concurrent_task_runner,
const fml::WeakPtr<IOManager>& io_manager);
const fml::WeakPtr<IOManager>& io_manager,
bool supports_wide_gamut);
~ImageDecoderImpeller() override;
@@ -35,7 +36,8 @@ class ImageDecoderImpeller final : public ImageDecoder {
static std::shared_ptr<SkBitmap> DecompressTexture(
ImageDescriptor* descriptor,
SkISize target_size,
impeller::ISize max_texture_size);
impeller::ISize max_texture_size,
bool supports_wide_gamut);
static sk_sp<DlImage> UploadTexture(
const std::shared_ptr<impeller::Context>& context,
@@ -44,6 +46,7 @@ class ImageDecoderImpeller final : public ImageDecoder {
private:
using FutureContext = std::shared_future<std::shared_ptr<impeller::Context>>;
FutureContext context_;
const bool supports_wide_gamut_;
FML_DISALLOW_COPY_AND_ASSIGN(ImageDecoderImpeller);
};

View File

@@ -272,6 +272,67 @@ TEST_F(ImageDecoderFixtureTest, ValidImageResultsInSuccess) {
latch.Wait();
}
namespace {
float HalfToFloat(uint16_t half) {
switch (half) {
case 0x7c00:
return std::numeric_limits<float>::infinity();
case 0xfc00:
return -std::numeric_limits<float>::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<float>(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<ImageGenerator> generator =
registry.CreateCompatibleGenerator(data);
ASSERT_TRUE(generator);
auto descriptor = fml::MakeRefCounted<ImageDescriptor>(std::move(data),
std::move(generator));
#if IMPELLER_SUPPORTS_RENDERING
std::shared_ptr<SkBitmap> 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<const uint16_t*>(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<SkBitmap> 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

View File

@@ -711,22 +711,32 @@ Rasterizer::Screenshot Rasterizer::ScreenshotLastLayerTree(
}
sk_sp<SkData> 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<size_t> Rasterizer::GetResourceCacheMaxBytes() const {
Rasterizer::Screenshot::Screenshot() {}
Rasterizer::Screenshot::Screenshot(sk_sp<SkData> p_data, SkISize p_size)
: data(std::move(p_data)), frame_size(p_size) {}
Rasterizer::Screenshot::Screenshot(sk_sp<SkData> 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;

View File

@@ -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<SkData> p_data, SkISize p_size);
Screenshot(sk_sp<SkData> p_data,
SkISize p_size,
const std::string& p_format);
//--------------------------------------------------------------------------
/// @brief The copy constructor for a screenshot.

View File

@@ -5,8 +5,11 @@
#ifndef FLUTTER_SHELL_GPU_GPU_SURFACE_METAL_IMPELLER_H_
#define FLUTTER_SHELL_GPU_GPU_SURFACE_METAL_IMPELLER_H_
#include <QuartzCore/CAMetalLayer.h>
#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> impeller_renderer_;
std::shared_ptr<impeller::AiksContext> aiks_context_;
fml::scoped_nsprotocol<id<MTLDrawable>> last_drawable_;
// |Surface|
std::unique_ptr<SurfaceFrame> AcquireFrame(const SkISize& size) override;

View File

@@ -7,6 +7,7 @@
#import <Metal/Metal.h>
#import <QuartzCore/QuartzCore.h>
#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<SurfaceFrame> 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<CAMetalDrawable> metal_drawable = static_cast<id<CAMetalDrawable>>(last_drawable_);
id<MTLTexture> 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<SkData> 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

View File

@@ -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);
}

View File

@@ -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

View File

@@ -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.
*/

View File

@@ -134,6 +134,7 @@ static constexpr int kNumProfilerSamplesPerSec = 5;
fml::scoped_nsobject<FlutterBasicMessageChannel> _systemChannel;
fml::scoped_nsobject<FlutterBasicMessageChannel> _settingsChannel;
fml::scoped_nsobject<FlutterBasicMessageChannel> _keyEventChannel;
fml::scoped_nsobject<FlutterMethodChannel> _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 {

View File

@@ -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_

View File

@@ -41,7 +41,8 @@
- (instancetype)initWithCoder:(NSCoder*)aDecoder NS_UNAVAILABLE;
- (instancetype)initWithDelegate:(id<FlutterViewEngineDelegate>)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;

View File

@@ -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<FlutterViewEngineDelegate> _delegate;
BOOL _isWideGamutEnabled;
}
- (instancetype)init {
@@ -35,7 +43,9 @@
return nil;
}
- (instancetype)initWithDelegate:(id<FlutterViewEngineDelegate>)delegate opaque:(BOOL)opaque {
- (instancetype)initWithDelegate:(id<FlutterViewEngineDelegate>)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];

View File

@@ -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<fml::WeakPtrFactory<FlutterViewController>>(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]);

View File

@@ -91,6 +91,7 @@ extern NSNotificationName const FlutterViewControllerWillDealloc;
///
/// Used for testing deallocation.
@interface MockEngine : NSObject
@property(nonatomic, strong) FlutterDartProject* project;
@end
@implementation MockEngine

View File

@@ -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);
}

View File

@@ -374,7 +374,9 @@ fml::RefPtr<fml::TaskRunner> 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<flutter::AccessibilityBridge>(
@@ -464,7 +466,9 @@ fml::RefPtr<fml::TaskRunner> 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<fml::TaskRunner> 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 {

View File

@@ -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>& 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<Allocator> GetResourceAllocator() const override {
return context_->GetResourceAllocator();
}
std::shared_ptr<ShaderLibrary> GetShaderLibrary() const override {
return context_->GetShaderLibrary();
}
std::shared_ptr<SamplerLibrary> GetSamplerLibrary() const override {
return context_->GetSamplerLibrary();
}
std::shared_ptr<PipelineLibrary> GetPipelineLibrary() const override {
return context_->GetPipelineLibrary();
}
std::shared_ptr<CommandBuffer> CreateCommandBuffer() const override {
return context_->CreateCommandBuffer();
}
std::shared_ptr<WorkQueue> GetWorkQueue() const override { return context_->GetWorkQueue(); }
std::shared_ptr<GPUTracer> 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> context_;
PixelFormat color_attachment_pixel_format_;
};
} // namespace
} // namespace impeller
namespace flutter {
using impeller::CustomColorAttachmentPixelFormatContext;
using impeller::FromMTLPixelFormat;
IOSSurfaceMetalImpeller::IOSSurfaceMetalImpeller(const fml::scoped_nsobject<CAMetalLayer>& layer,
const std::shared_ptr<IOSContext>& context)
: IOSSurface(context),
@@ -35,9 +99,10 @@ void IOSSurfaceMetalImpeller::UpdateStorageSizeIfNecessary() {
// |IOSSurface|
std::unique_ptr<Surface> IOSSurfaceMetalImpeller::CreateGPUSurface(GrDirectContext*) {
return std::make_unique<GPUSurfaceMetalImpeller>(this, //
impeller_context_ //
auto context = std::make_shared<CustomColorAttachmentPixelFormatContext>(
impeller_context_, FromMTLPixelFormat(layer_.get().pixelFormat));
return std::make_unique<GPUSurfaceMetalImpeller>(this, //
context //
);
}