Skip to content

Commit 73aef06

Browse files
authored
fix(🍏): tag the CAMetalLayer colorspace on the main thread, from mount-only Canvas props (#626)
configure() tagged the layer from the JS or worklet thread and then called [CATransaction flush], which commits the whole layer tree off the main thread and can lay out UIKit views there (same crash as react-native-skia #4474). The Canvas now takes colorSpace and toneMapping props, read when it mounts on iOS and macOS: the layer is tagged on the main thread before it is attached, and configure() no longer touches it. A change of the props on a mounted canvas, or a configure() that asks for something else, is reported in development.
1 parent 8ae9035 commit 73aef06

17 files changed

Lines changed: 281 additions & 104 deletions

‎apps/docs/content/api/canvas.mdx‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ description: Rendering pixels on-screen
1010
| Prop | Type | Description |
1111
| ---- | ---- | ----------- |
1212
| `android` | `AndroidCanvasProps` | Android-only rendering options: the native view behind the canvas (`backingView`) and its options (`opaque`, `zOrderOnTop`, `zOrderMediaOverlay`), see [Android rendering options](#android-rendering-options). Ignored on iOS and web |
13+
| `colorSpace` | `PredefinedColorSpace` | `"srgb"` (the default) or `"display-p3"`, as in `configure()`. Read when the canvas mounts on iOS and macOS, see [Color space](#color-space). Ignored on Android and web |
14+
| `toneMapping` | `GPUCanvasToneMapping` | `{ mode: "standard" }` (the default) or `{ mode: "extended" }`, as in `configure()`. Read when the canvas mounts on iOS and macOS, see [HDR](#hdr-extended-dynamic-range). Ignored on Android and web |
1315
| `...ViewProps` | `ViewProps` | All standard React Native View props (`style`, `onLayout`, etc.) |
1416

1517
## Usage
@@ -137,11 +139,13 @@ To show the views behind the canvas, configure the context with `alphaMode: "pre
137139

138140
## Color space
139141

140-
`context.configure({ colorSpace })` says which primaries the canvas's values are in: `"srgb"` (the default) or `"display-p3"`. Both use the sRGB transfer function, as on the Web. On iOS the layer is tagged Display P3 (extended Display P3 for an `rgba16float` canvas), so a shader's output reaches a wide-gamut display unconverted and matches other Display P3 content, such as a Skia canvas. Android currently ignores `colorSpace`.
142+
`context.configure({ colorSpace })` says which primaries the canvas's values are in: `"srgb"` (the default) or `"display-p3"`. Both use the sRGB transfer function, as on the Web. On iOS and macOS the color space is set when the canvas mounts, from the `colorSpace` prop of the `Canvas`: pass the same value to both. With `"display-p3"`, a shader's output reaches a wide-gamut display unconverted and matches other Display P3 content, such as a Skia canvas. Android currently ignores `colorSpace`.
143+
144+
The prop is read once: a change on a mounted canvas is ignored, with a warning in development, and so is a `configure()` that asks for another color space than the canvas was mounted with. To change it, remount the canvas with a new `key`.
141145

142146
## HDR (extended dynamic range)
143147

144-
`context.configure({ toneMapping: { mode } })` says what happens to values above 1.0 on an `rgba16float` canvas: `"standard"` (the default) clamps them to the display's SDR range, `"extended"` lets them use the display's headroom, as in a browser. On iOS 16 and later the `CAMetalLayer` opts into extended dynamic range content for `"extended"`; the mode is accepted and has no effect on an 8-bit canvas, which cannot hold values above 1.0. tvOS has no extended dynamic range for this layer, so `"extended"` behaves like `"standard"` there. Android currently ignores `toneMapping`.
148+
`context.configure({ toneMapping: { mode } })` says what happens to values above 1.0 on an `rgba16float` canvas: `"standard"` (the default) clamps them to the display's SDR range, `"extended"` lets them use the display's headroom, as in a browser. On iOS 16 and later and on macOS, the `toneMapping` prop of the `Canvas` sets it when the canvas mounts, like `colorSpace`: pass the same value to both. The mode has no effect on an 8-bit canvas, which cannot hold values above 1.0. tvOS has no extended dynamic range for this layer, so `"extended"` behaves like `"standard"` there. Android currently ignores `toneMapping`.
145149

146150
### Android rendering options
147151

‎apps/docs/content/docs/getting-started/canvas.mdx‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -99,17 +99,23 @@ On iOS `alphaMode` alone controls it. On Android the `alphaMode` passed to `conf
9999

100100
## Color space
101101

102-
By default the canvas's values are sRGB. Pass `colorSpace: "display-p3"` to `configure()` to write Display P3 values instead, as you would in a browser. iOS tags the layer accordingly, so colors outside sRGB show on a wide-gamut display. Android ignores it for now.
102+
By default the canvas's values are sRGB. Pass `colorSpace: "display-p3"` to `configure()` to write Display P3 values instead, as you would in a browser. On iOS and macOS, also pass it to the `Canvas`: the color space is set when the canvas mounts, so colors outside sRGB show on a wide-gamut display. Android ignores it for now.
103103

104104
```tsx
105+
<Canvas ref={ref} colorSpace="display-p3" style={{ flex: 1 }} />;
106+
105107
context.configure({ device, format, colorSpace: "display-p3" });
106108
```
107109

110+
The `Canvas` props are read once, when it mounts: a change on a mounted canvas is ignored, with a warning in development. To change them, remount the canvas with a new `key`. If `configure()` asks for something else than the canvas was mounted with, a warning says so in development.
111+
108112
## HDR
109113

110-
On an `rgba16float` canvas, values above 1.0 are clamped to the display's SDR range by default. Pass `toneMapping: { mode: "extended" }` to `configure()` to let them use the display's extended range (HDR) instead, as in a browser. iOS 16 and later opts the layer into extended dynamic range content. Android ignores it for now.
114+
On an `rgba16float` canvas, values above 1.0 are clamped to the display's SDR range by default. Pass `toneMapping: { mode: "extended" }` to `configure()` to let them use the display's extended range (HDR) instead, as in a browser. On iOS 16 and later and on macOS, also pass it to the `Canvas`, which reads it when it mounts, like `colorSpace`. Android ignores it for now.
111115

112116
```tsx
117+
<Canvas ref={ref} toneMapping={{ mode: "extended" }} style={{ flex: 1 }} />;
118+
113119
context.configure({
114120
device,
115121
format: "rgba16float",

‎apps/docs/content/docs/getting-started/native-api.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,7 @@ This only works with a library that links the same Dawn build as react-native-we
148148

149149
## Rendering to a native window
150150

151-
`RNWebGPU.MakeWebGPUCanvasContextFromNativeWindow()` makes a canvas context that presents to a native window other than a `Canvas`, for instance the input `Surface` of a `MediaCodec` encoder on Android. The window is an `ANativeWindow*` on Android or a `CAMetalLayer*` on Apple platforms, passed as a `BigInt`; `width` and `height` size the drawing buffer, like `canvas.width` and `canvas.height`. The context retains the window for as long as it lives, so the pointer stays valid; whatever the window belongs to (the encoder, the layer's view) is yours to keep alive while you present to it. Unlike a `Canvas`, nothing drives the context for you: call it from one thread at a time.
151+
`RNWebGPU.MakeWebGPUCanvasContextFromNativeWindow()` makes a canvas context that presents to a native window other than a `Canvas`, for instance the input `Surface` of a `MediaCodec` encoder on Android. The window is an `ANativeWindow*` on Android or a `CAMetalLayer*` on Apple platforms, passed as a `BigInt`; `width` and `height` size the drawing buffer, like `canvas.width` and `canvas.height`. The context retains the window for as long as it lives, so the pointer stays valid; whatever the window belongs to (the encoder, the layer's view) is yours to keep alive while you present to it. Unlike a `Canvas`, nothing drives the context for you: call it from one thread at a time. On Apple platforms, `configure()` leaves the layer's `colorspace` as it is: set it yourself, on the main thread, to match the `colorSpace` and format you configure.
152152

153153
```tsx
154154
const context = RNWebGPU.MakeWebGPUCanvasContextFromNativeWindow(

‎packages/webgpu/android/src/main/java/com/webgpu/WebGPUViewManager.java‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,16 @@ public void setAndroidZOrderMediaOverlay(WebGPUView view, boolean value) {
5454
view.setZOrderMediaOverlay(value);
5555
}
5656

57+
// The colorspace props of the canvas, read on Apple platforms only: Android
58+
// renders in sRGB.
59+
@Override
60+
@ReactProp(name = "appleDisplayP3")
61+
public void setAppleDisplayP3(WebGPUView view, boolean value) {}
62+
63+
@Override
64+
@ReactProp(name = "appleExtendedDynamicRange")
65+
public void setAppleExtendedDynamicRange(WebGPUView view, boolean value) {}
66+
5767
@Override
5868
protected void onAfterUpdateTransaction(@NonNull WebGPUView view) {
5969
super.onAfterUpdateTransaction(view);
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
#pragma once
2+
3+
#import <QuartzCore/CAMetalLayer.h>
4+
5+
#include "CanvasColorSpace.h"
6+
7+
namespace rnwgpu {
8+
9+
// Tags a new CAMetalLayer with the colorspace of the canvas, and opts it into
10+
// the display's extended dynamic range for an "extended" toneMapping mode.
11+
// Main thread only, where the platform view calls it as the canvas mounts (see
12+
// -[MetalView configure]): the threads that configure and present the surface
13+
// (JS, worklet runtimes) never touch a CATransaction.
14+
void applyCAMetalLayerColorSpace(CAMetalLayer *layer,
15+
CanvasLayerColorSpace colorSpace);
16+
17+
} // namespace rnwgpu
Lines changed: 36 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -1,79 +1,58 @@
11
#import <CoreGraphics/CoreGraphics.h>
22
#import <Foundation/Foundation.h>
33
#import <QuartzCore/CAMetalLayer.h>
4-
#import <QuartzCore/CATransaction.h>
54

6-
#include "CanvasColorSpace.h"
7-
#include "webgpu/webgpu_cpp.h"
5+
#include "MetalLayerColorSpace.h"
86

97
namespace rnwgpu {
108

119
// WebGPU canvas values are encoded with the sRGB transfer function regardless
12-
// of the texture format, and GPUCanvasConfiguration.colorSpace says which
13-
// primaries they are in: "srgb" (the default) or "display-p3". The same shader
14-
// output must display identically on bgra8unorm and rgba16float surfaces.
15-
// Core Animation interprets a float-format layer with a nil colorspace as
16-
// extended *linear* sRGB, which displays the same values noticeably brighter.
17-
// Tagging the layer as (gamma-encoded) extended sRGB matches the browser
18-
// behavior: identical colors, with the extra precision of float16. For
19-
// "display-p3" the layer is tagged Display P3 instead, or its extended range
20-
// variant on a float format, so the values reach a wide-gamut display without
21-
// being converted from sRGB first.
10+
// of the texture format, and the canvas's colorSpace says which primaries they
11+
// are in: "srgb" (the default) or "display-p3". The same shader output must
12+
// display identically on bgra8unorm and rgba16float surfaces. Core Animation
13+
// interprets a float-format layer with a nil colorspace as extended *linear*
14+
// sRGB, which displays the same values noticeably brighter. The layer is
15+
// tagged before the format is known (configure() comes later, from JS), so it
16+
// gets the gamma-encoded extended variant of its gamut: on an 8-bit format it
17+
// reads the same values as the plain colorspace, and on a float format it
18+
// gives identical colors with the extra precision of float16, as in a browser.
19+
// For "display-p3" the values reach a wide-gamut display without being
20+
// converted from sRGB first.
2221
//
23-
// GPUCanvasConfiguration.toneMapping.mode says what happens to values above
24-
// 1.0 on a float canvas. Core Animation keeps an extended colorspace inside
25-
// the display's SDR range unless the layer asks for extended dynamic range
26-
// content, so without it the values clip at white: that is "standard". For
27-
// "extended" the layer opts in, and the values use the display's headroom
28-
// (EDR) as they do in a browser. An 8-bit canvas cannot hold values above 1.0,
29-
// so the flag only applies to a float format.
30-
void applyCAMetalLayerColorSpace(void *nativeSurface,
31-
wgpu::TextureFormat format,
32-
CanvasColorSpace canvasColorSpace,
33-
CanvasToneMappingMode toneMappingMode) {
34-
CALayer *layer = (__bridge CALayer *)nativeSurface;
35-
if (![layer isKindOfClass:[CAMetalLayer class]]) {
36-
return;
37-
}
38-
auto metalLayer = static_cast<CAMetalLayer *>(layer);
39-
const bool isFloat = format == wgpu::TextureFormat::RGBA16Float;
40-
CFStringRef name = nullptr;
41-
if (canvasColorSpace == CanvasColorSpace::DisplayP3) {
42-
name = isFloat ? kCGColorSpaceExtendedDisplayP3 : kCGColorSpaceDisplayP3;
43-
} else if (isFloat) {
44-
name = kCGColorSpaceExtendedSRGB;
45-
}
46-
if (name != nullptr) {
47-
CGColorSpaceRef colorSpace = CGColorSpaceCreateWithName(name);
48-
metalLayer.colorspace = colorSpace;
49-
CGColorSpaceRelease(colorSpace);
50-
} else if (metalLayer.colorspace != nil) {
51-
// Restore the default (no color matching) when reconfiguring back to an
52-
// 8-bit sRGB canvas.
53-
metalLayer.colorspace = nil;
54-
}
22+
// The toneMapping mode says what happens to values above 1.0 on a float
23+
// canvas. Core Animation keeps an extended colorspace inside the display's
24+
// SDR range unless the layer asks for extended dynamic range content, so
25+
// without it the values clip at white: that is "standard". For "extended" the
26+
// layer opts in, and the values use the display's headroom (EDR) as they do in
27+
// a browser. An 8-bit canvas cannot hold values above 1.0, so the flag has no
28+
// visible effect there.
29+
void applyCAMetalLayerColorSpace(CAMetalLayer *layer,
30+
CanvasLayerColorSpace colorSpace) {
31+
// Main thread only: the properties land in the calling thread's implicit
32+
// CATransaction, which the main run loop commits. Committing it from any
33+
// other thread ([CATransaction flush]) commits the whole layer tree there,
34+
// and lays out whatever UIKit view has a layout pending, off the main
35+
// thread (react-native-skia #4474).
36+
NSCAssert(NSThread.isMainThread,
37+
@"applyCAMetalLayerColorSpace must be called on the main thread");
38+
CGColorSpaceRef cgColorSpace = CGColorSpaceCreateWithName(
39+
colorSpace.colorSpace == CanvasColorSpace::DisplayP3
40+
? kCGColorSpaceExtendedDisplayP3
41+
: kCGColorSpaceExtendedSRGB);
42+
layer.colorspace = cgColorSpace;
43+
CGColorSpaceRelease(cgColorSpace);
5544
const bool extendedRange =
56-
isFloat && toneMappingMode == CanvasToneMappingMode::Extended;
45+
colorSpace.toneMappingMode == CanvasToneMappingMode::Extended;
5746
// The property does not exist on tvOS (the SDK marks it unavailable, which
5847
// @available cannot work around), so it is compiled only where it exists.
5948
// On tvOS "extended" behaves like "standard".
6049
#if TARGET_OS_IOS || TARGET_OS_OSX || TARGET_OS_VISION
6150
if (@available(iOS 16.0, macOS 10.11, visionOS 1.0, *)) {
62-
if (metalLayer.wantsExtendedDynamicRangeContent != extendedRange) {
63-
metalLayer.wantsExtendedDynamicRangeContent = extendedRange;
64-
}
51+
layer.wantsExtendedDynamicRangeContent = extendedRange;
6552
}
6653
#else
6754
(void)extendedRange;
6855
#endif
69-
// The change must be set synchronously so the first present already sees
70-
// it, and it must reach the render server. On a non-main thread (RN JS or
71-
// worklet runtime) the property lands in that thread's implicit
72-
// CATransaction, which may never commit on threads without a spinning
73-
// runloop, so flush it now. On the main thread the runloop commits it.
74-
if (!NSThread.isMainThread) {
75-
[CATransaction flush];
76-
}
7756
}
7857

7958
} // namespace rnwgpu

‎packages/webgpu/apple/MetalView.h‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,10 @@
66
@interface MetalView : RNWGPlatformView
77

88
@property NSNumber *contextId;
9+
// The colorSpace and toneMapping props of the Canvas, as they are when it
10+
// mounts: set before configure, which tags the layer with them.
11+
@property BOOL displayP3;
12+
@property BOOL extendedDynamicRange;
913

1014
- (void)configure;
1115
- (void)update;

‎packages/webgpu/apple/MetalView.mm‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
#import "MetalView.h"
2+
#include "MetalLayerColorSpace.h"
23
#import "WebGPURuntime.h"
34
#import "webgpu/webgpu_cpp.h"
45

@@ -27,6 +28,18 @@ - (void)configure {
2728
if (manager == nullptr) {
2829
return;
2930
}
31+
// The layer is tagged with its colorspace here, on the main thread, before
32+
// it is attached: the threads that configure and present the surface (JS,
33+
// worklet runtimes) then never change the layer in a CATransaction of
34+
// theirs. The tag comes from the Canvas props when it mounts and is kept
35+
// (see -[WebGPUView updateProps:oldProps:]).
36+
const rnwgpu::CanvasLayerColorSpace layerColorSpace{
37+
_displayP3 ? rnwgpu::CanvasColorSpace::DisplayP3
38+
: rnwgpu::CanvasColorSpace::SRGB,
39+
_extendedDynamicRange ? rnwgpu::CanvasToneMappingMode::Extended
40+
: rnwgpu::CanvasToneMappingMode::Standard};
41+
rnwgpu::applyCAMetalLayerColorSpace((CAMetalLayer *)self.layer,
42+
layerColorSpace);
3043
// Retain the layer for as long as SurfaceInfo holds the pointer: the
3144
// latched attach (and the flush lambda that adopts it) can outlive this
3245
// view, e.g. across a dev reload where the registry is cleared before
@@ -47,6 +60,7 @@ - (void)configure {
4760
CFBridgingRelease(layer);
4861
});
4962
});
63+
info->setLayerColorSpace(layerColorSpace);
5064
// The attach is adopted at the next frame boundary by the rendering thread;
5165
// schedule a flush so contexts that are not currently rendering still pick
5266
// it up (and present their last offscreen frame).

‎packages/webgpu/apple/WebGPUView.mm‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,10 +66,16 @@ - (void)updateProps:(const Props::Shared &)props
6666
/*
6767
The context is set only once during mounting the component
6868
and never changes because it isn't available for users to modify.
69+
The colorspace props are read here too, and only here: the layer is
70+
tagged with them as it is attached, on the main thread, and a change on
71+
a mounted canvas is ignored (with a warning in development from JS, see
72+
Canvas.tsx).
6973
*/
7074
MetalView *metalView = [MetalView new];
7175
self.contentView = metalView;
7276
[metalView setContextId:@(newViewProps.contextId)];
77+
metalView.displayP3 = newViewProps.appleDisplayP3;
78+
metalView.extendedDynamicRange = newViewProps.appleExtendedDynamicRange;
7379
[metalView configure];
7480
}
7581

‎packages/webgpu/cpp/jsi/NativeObject.h‎

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -839,11 +839,18 @@ class NativeObject : public NativeObjectBase,
839839
ReturnType (Derived::*method)(jsi::Runtime &, Args...),
840840
jsi::Runtime &runtime, const jsi::Value *args,
841841
std::index_sequence<Is...>, size_t count) {
842-
ReturnType result = (obj->*method)(
843-
runtime, rnwgpu::JSIConverter<std::decay_t<Args>>::fromJSI(
844-
runtime, args[Is], Is >= count)...);
845-
return rnwgpu::JSIConverter<std::decay_t<ReturnType>>::toJSI(
846-
runtime, std::move(result));
842+
if constexpr (std::is_same_v<ReturnType, void>) {
843+
(obj->*method)(runtime,
844+
rnwgpu::JSIConverter<std::decay_t<Args>>::fromJSI(
845+
runtime, args[Is], Is >= count)...);
846+
return jsi::Value::undefined();
847+
} else {
848+
ReturnType result = (obj->*method)(
849+
runtime, rnwgpu::JSIConverter<std::decay_t<Args>>::fromJSI(
850+
runtime, args[Is], Is >= count)...);
851+
return rnwgpu::JSIConverter<std::decay_t<ReturnType>>::toJSI(
852+
runtime, std::move(result));
853+
}
847854
}
848855

849856
// Helper to call a method with JSI argument conversion

0 commit comments

Comments
 (0)