react-native-webgpu 0.21.4 → 0.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (170) hide show
  1. package/README.md +15 -2
  2. package/android/CMakeLists.txt +10 -8
  3. package/android/build.gradle +111 -20
  4. package/android/cpp/AndroidAnimationFrameSource.h +136 -0
  5. package/android/cpp/AndroidPlatformContext.h +55 -0
  6. package/android/cpp/cpp-adapter.cpp +148 -2
  7. package/android/src/main/java/com/webgpu/WebGPUModule.java +21 -4
  8. package/android/src/main/java/com/webgpu/WebGPUNativeBufferView.java +370 -0
  9. package/android/src/main/java/com/webgpu/WebGPUNativeBufferViewManager.java +56 -0
  10. package/android/src/main/java/com/webgpu/WebGPUTextureView.java +21 -0
  11. package/android/src/main/java/com/webgpu/WebGPUVideoPlayer.java +1 -1
  12. package/android/src/main/java/com/webgpu/WebGPUView.java +19 -3
  13. package/android/src/main/java/com/webgpu/WebGPUViewManager.java +10 -0
  14. package/android/src/main/java/com/webgpu/WebGPUViewPackage.java +2 -2
  15. package/android/src/newarch/com/webgpu/WebGPUNativeBufferViewManagerSpec.java +24 -0
  16. package/apple/AppleAnimationFrameSource.mm +208 -0
  17. package/apple/ApplePlatformContext.h +6 -0
  18. package/apple/ApplePlatformContext.mm +73 -0
  19. package/apple/MetalLayerColorSpace.h +17 -0
  20. package/apple/MetalLayerColorSpace.mm +36 -57
  21. package/apple/MetalView.h +4 -0
  22. package/apple/MetalView.mm +14 -0
  23. package/apple/NativeBufferFenceWait.mm +88 -0
  24. package/apple/RNWGUIKit.h +4 -1
  25. package/apple/WebGPUModule.mm +26 -1
  26. package/apple/WebGPUNativeBufferView.h +15 -0
  27. package/apple/WebGPUNativeBufferView.mm +200 -0
  28. package/apple/WebGPUView.h +2 -1
  29. package/apple/WebGPUView.mm +6 -0
  30. package/binaries.json +156 -0
  31. package/cpp/jsi/NativeObject.h +12 -5
  32. package/cpp/rnwgpu/AnimationFrames.cpp +576 -0
  33. package/cpp/rnwgpu/AnimationFrames.h +233 -0
  34. package/cpp/rnwgpu/CanvasColorSpace.h +16 -0
  35. package/cpp/rnwgpu/NativeBufferViewRegistry.cpp +396 -0
  36. package/cpp/rnwgpu/NativeBufferViewRegistry.h +163 -0
  37. package/cpp/rnwgpu/PlatformContext.h +20 -0
  38. package/cpp/rnwgpu/RNWebGPUManager.cpp +17 -4
  39. package/cpp/rnwgpu/SurfaceRegistry.h +26 -30
  40. package/cpp/rnwgpu/api/GPUAdapter.cpp +1 -1
  41. package/cpp/rnwgpu/api/GPUCanvasContext.cpp +41 -3
  42. package/cpp/rnwgpu/api/GPUCanvasContext.h +7 -3
  43. package/cpp/rnwgpu/api/GPUDevice.cpp +16 -131
  44. package/cpp/rnwgpu/api/GPUDevice.h +0 -18
  45. package/cpp/rnwgpu/api/GPUExternalTexture.cpp +35 -3
  46. package/cpp/rnwgpu/api/GPUExternalTexture.h +4 -4
  47. package/cpp/rnwgpu/api/GPUQueue.cpp +1 -1
  48. package/cpp/rnwgpu/api/GPUQueue.h +1 -1
  49. package/cpp/rnwgpu/api/GPUSharedFence.h +1 -0
  50. package/cpp/rnwgpu/api/GPUSharedTextureMemory.cpp +11 -5
  51. package/cpp/rnwgpu/api/GPUSharedTextureMemory.h +21 -2
  52. package/cpp/rnwgpu/api/GPUTexture.h +18 -0
  53. package/cpp/rnwgpu/api/NativeFrameFeatures.h +1 -1
  54. package/cpp/rnwgpu/api/NativeFrameImport.cpp +20 -17
  55. package/cpp/rnwgpu/api/NativeFrameImport.h +31 -20
  56. package/cpp/rnwgpu/api/RNWebGPU.h +201 -3
  57. package/cpp/rnwgpu/api/VideoFrame.h +5 -4
  58. package/cpp/rnwgpu/api/VideoFrameBlit.h +2 -2
  59. package/cpp/rnwgpu/api/descriptors/GPUExternalTextureDescriptor.h +21 -14
  60. package/cpp/rnwgpu/api/descriptors/GPUImageCopyExternalImage.h +1 -1
  61. package/cpp/rnwgpu/api/descriptors/GPUSharedTextureMemoryDescriptor.h +17 -9
  62. package/cpp/rnwgpu/async/RuntimeContext.cpp +21 -4
  63. package/cpp/rnwgpu/async/RuntimeContext.h +8 -0
  64. package/lib/commonjs/Canvas.js +33 -1
  65. package/lib/commonjs/Canvas.js.map +1 -1
  66. package/lib/commonjs/NativeBufferView.js +131 -0
  67. package/lib/commonjs/NativeBufferView.js.map +1 -0
  68. package/lib/commonjs/NativeBufferViewNativeComponent.js +10 -0
  69. package/lib/commonjs/NativeBufferViewNativeComponent.js.map +1 -0
  70. package/lib/commonjs/WebGPUViewNativeComponent.js.map +1 -1
  71. package/lib/commonjs/WebGPUViewNativeComponent.web.js +2 -0
  72. package/lib/commonjs/WebGPUViewNativeComponent.web.js.map +1 -1
  73. package/lib/commonjs/animationFrame.js +91 -0
  74. package/lib/commonjs/animationFrame.js.map +1 -0
  75. package/lib/commonjs/index.js +16 -1
  76. package/lib/commonjs/index.js.map +1 -1
  77. package/lib/commonjs/main/index.js +12 -0
  78. package/lib/commonjs/main/index.js.map +1 -1
  79. package/lib/commonjs/mock.js +30 -1
  80. package/lib/commonjs/mock.js.map +1 -1
  81. package/lib/commonjs/video.js +14 -4
  82. package/lib/commonjs/video.js.map +1 -1
  83. package/lib/module/Canvas.js +33 -1
  84. package/lib/module/Canvas.js.map +1 -1
  85. package/lib/module/NativeBufferView.js +122 -0
  86. package/lib/module/NativeBufferView.js.map +1 -0
  87. package/lib/module/NativeBufferViewNativeComponent.js +4 -0
  88. package/lib/module/NativeBufferViewNativeComponent.js.map +1 -0
  89. package/lib/module/WebGPUViewNativeComponent.js.map +1 -1
  90. package/lib/module/WebGPUViewNativeComponent.web.js +2 -0
  91. package/lib/module/WebGPUViewNativeComponent.web.js.map +1 -1
  92. package/lib/module/animationFrame.js +83 -0
  93. package/lib/module/animationFrame.js.map +1 -0
  94. package/lib/module/index.js +1 -0
  95. package/lib/module/index.js.map +1 -1
  96. package/lib/module/main/index.js +1 -0
  97. package/lib/module/main/index.js.map +1 -1
  98. package/lib/module/mock.js +21 -0
  99. package/lib/module/mock.js.map +1 -1
  100. package/lib/module/video.js +11 -2
  101. package/lib/module/video.js.map +1 -1
  102. package/lib/typescript/lib/commonjs/Canvas.d.ts +3 -1
  103. package/lib/typescript/lib/commonjs/Canvas.d.ts.map +1 -1
  104. package/lib/typescript/lib/commonjs/NativeBufferView.d.ts +48 -0
  105. package/lib/typescript/lib/commonjs/NativeBufferView.d.ts.map +1 -0
  106. package/lib/typescript/lib/commonjs/NativeBufferViewNativeComponent.d.ts +5 -0
  107. package/lib/typescript/lib/commonjs/NativeBufferViewNativeComponent.d.ts.map +1 -0
  108. package/lib/typescript/lib/commonjs/WebGPUViewNativeComponent.web.d.ts.map +1 -1
  109. package/lib/typescript/lib/commonjs/animationFrame.d.ts +54 -0
  110. package/lib/typescript/lib/commonjs/animationFrame.d.ts.map +1 -0
  111. package/lib/typescript/lib/commonjs/index.d.ts +2 -0
  112. package/lib/typescript/lib/commonjs/mock.d.ts +12 -0
  113. package/lib/typescript/lib/commonjs/mock.d.ts.map +1 -1
  114. package/lib/typescript/lib/commonjs/video.d.ts +3 -2
  115. package/lib/typescript/lib/commonjs/video.d.ts.map +1 -1
  116. package/lib/typescript/lib/module/Canvas.d.ts +3 -1
  117. package/lib/typescript/lib/module/Canvas.d.ts.map +1 -1
  118. package/lib/typescript/lib/module/NativeBufferView.d.ts +14 -0
  119. package/lib/typescript/lib/module/NativeBufferView.d.ts.map +1 -0
  120. package/lib/typescript/lib/module/NativeBufferViewNativeComponent.d.ts +3 -0
  121. package/lib/typescript/lib/module/NativeBufferViewNativeComponent.d.ts.map +1 -0
  122. package/lib/typescript/lib/module/WebGPUViewNativeComponent.web.d.ts.map +1 -1
  123. package/lib/typescript/lib/module/animationFrame.d.ts +3 -0
  124. package/lib/typescript/lib/module/animationFrame.d.ts.map +1 -0
  125. package/lib/typescript/lib/module/index.d.ts +1 -0
  126. package/lib/typescript/lib/module/main/index.d.ts +1 -0
  127. package/lib/typescript/lib/module/mock.d.ts +14 -0
  128. package/lib/typescript/lib/module/mock.d.ts.map +1 -1
  129. package/lib/typescript/lib/module/video.d.ts +3 -2
  130. package/lib/typescript/lib/module/video.d.ts.map +1 -1
  131. package/lib/typescript/src/Canvas.d.ts +17 -1
  132. package/lib/typescript/src/Canvas.d.ts.map +1 -1
  133. package/lib/typescript/src/NativeBufferView.d.ts +99 -0
  134. package/lib/typescript/src/NativeBufferView.d.ts.map +1 -0
  135. package/lib/typescript/src/NativeBufferViewNativeComponent.d.ts +13 -0
  136. package/lib/typescript/src/NativeBufferViewNativeComponent.d.ts.map +1 -0
  137. package/lib/typescript/src/WebGPUViewNativeComponent.d.ts +2 -0
  138. package/lib/typescript/src/WebGPUViewNativeComponent.d.ts.map +1 -1
  139. package/lib/typescript/src/WebGPUViewNativeComponent.web.d.ts +2 -0
  140. package/lib/typescript/src/WebGPUViewNativeComponent.web.d.ts.map +1 -1
  141. package/lib/typescript/src/animationFrame.d.ts +59 -0
  142. package/lib/typescript/src/animationFrame.d.ts.map +1 -0
  143. package/lib/typescript/src/index.d.ts +18 -8
  144. package/lib/typescript/src/index.d.ts.map +1 -1
  145. package/lib/typescript/src/main/index.d.ts +1 -0
  146. package/lib/typescript/src/main/index.d.ts.map +1 -1
  147. package/lib/typescript/src/mock.d.ts +11 -0
  148. package/lib/typescript/src/mock.d.ts.map +1 -1
  149. package/lib/typescript/src/types.d.ts +32 -31
  150. package/lib/typescript/src/types.d.ts.map +1 -1
  151. package/lib/typescript/src/video.d.ts +12 -4
  152. package/lib/typescript/src/video.d.ts.map +1 -1
  153. package/package.json +8 -2
  154. package/react-native-webgpu.podspec +1 -1
  155. package/src/Canvas.tsx +67 -1
  156. package/src/NativeBufferView.tsx +199 -0
  157. package/src/NativeBufferViewNativeComponent.ts +20 -0
  158. package/src/WebGPUViewNativeComponent.ts +4 -0
  159. package/src/WebGPUViewNativeComponent.web.ts +6 -0
  160. package/src/animationFrame.ts +82 -0
  161. package/src/index.tsx +45 -39
  162. package/src/main/index.tsx +1 -0
  163. package/src/mock.ts +35 -0
  164. package/src/types.ts +61 -87
  165. package/src/video.ts +20 -7
  166. package/cpp/rnwgpu/api/GPUNativeBufferExternalTexture.h +0 -60
  167. package/cpp/rnwgpu/api/GPUNativeBufferTexture.h +0 -52
  168. package/cpp/rnwgpu/api/GPUNativeBufferWrapper.cpp +0 -144
  169. package/cpp/rnwgpu/api/GPUNativeBufferWrapper.h +0 -143
  170. package/cpp/rnwgpu/api/descriptors/GPUNativeBufferTextureDescriptor.h +0 -55
@@ -0,0 +1,208 @@
1
+ #include "AnimationFrames.h"
2
+
3
+ #import "RNWGUIKit.h"
4
+ #import <QuartzCore/QuartzCore.h>
5
+ #import <React/RCTUtils.h>
6
+
7
+ #include <atomic>
8
+ #include <memory>
9
+
10
+ namespace rnwgpu {
11
+ class AppleAnimationFrameSource;
12
+ std::shared_ptr<AnimationFrameSource> makeAppleAnimationFrameSource();
13
+ } // namespace rnwgpu
14
+
15
+ // The display link's target. A CADisplayLink retains its target, and the
16
+ // source outlives it anyway: the target borrows the source.
17
+ @interface RNWGAnimationFrameTarget : NSObject
18
+ - (instancetype)initWithSource:(rnwgpu::AppleAnimationFrameSource *)source;
19
+ - (void)onFrame:(CADisplayLink *)link;
20
+ @end
21
+
22
+ namespace rnwgpu {
23
+
24
+ #if !TARGET_OS_OSX
25
+
26
+ /**
27
+ * The display's frames on iOS: a CADisplayLink on a run loop thread of its
28
+ * own, so that a busy main thread never delays them, asking for the highest
29
+ * rate the display has. React Native's own display link sets no frame rate
30
+ * range, which keeps it at 60 Hz on a ProMotion iPhone. (The app must still
31
+ * opt in to more than 60 Hz on iPhone with CADisableMinimumFrameDurationOnPhone
32
+ * in its Info.plist.)
33
+ *
34
+ * A request is delivered at the next frame of the link. The link keeps running
35
+ * between requests, and only pauses after kIdleFramesBeforePause frames
36
+ * without one: pausing it at every frame and unpausing it at the next request
37
+ * reads to the system as a link that keeps stopping, which it does not run at
38
+ * 120 Hz. The frame time is the link's timestamp, moved from its clock to
39
+ * std::chrono::steady_clock. The thread lives as long as the process.
40
+ */
41
+ class AppleAnimationFrameSource : public AnimationFrameSource {
42
+ public:
43
+ static std::shared_ptr<AppleAnimationFrameSource> shared() {
44
+ static std::shared_ptr<AppleAnimationFrameSource> source = create();
45
+ return source;
46
+ }
47
+
48
+ void requestFrame() override {
49
+ _wanted.store(true);
50
+ // Paired with onFrame(), which stores _paused before it reads _wanted:
51
+ // either it sees this request, or this sees the link paused.
52
+ if (_paused.load()) {
53
+ unpause();
54
+ }
55
+ }
56
+
57
+ // The link's thread.
58
+ void onFrame(CADisplayLink *link) {
59
+ if (!_wanted.exchange(false)) {
60
+ if (++_idleFrames >= kIdleFramesBeforePause) {
61
+ link.paused = YES;
62
+ _paused.store(true);
63
+ if (_wanted.load()) {
64
+ unpause();
65
+ }
66
+ }
67
+ return;
68
+ }
69
+ _idleFrames = 0;
70
+ const CFTimeInterval age = CACurrentMediaTime() - link.timestamp;
71
+ const int64_t ageNanos = age > 0 ? static_cast<int64_t>(age * 1e9) : 0;
72
+ deliverFrame(AnimationFrameDispatcher::nowNanos() - ageNanos);
73
+ }
74
+
75
+ private:
76
+ AppleAnimationFrameSource() = default;
77
+
78
+ static std::shared_ptr<AppleAnimationFrameSource> create() {
79
+ auto source = std::shared_ptr<AppleAnimationFrameSource>(
80
+ new AppleAnimationFrameSource());
81
+ auto *raw = source.get();
82
+ dispatch_semaphore_t ready = dispatch_semaphore_create(0);
83
+ NSThread *thread = [[NSThread alloc] initWithBlock:^{
84
+ RNWGAnimationFrameTarget *target =
85
+ [[RNWGAnimationFrameTarget alloc] initWithSource:raw];
86
+ CADisplayLink *link =
87
+ [CADisplayLink displayLinkWithTarget:target
88
+ selector:@selector(onFrame:)];
89
+ if (@available(iOS 15.0, tvOS 15.0, *)) {
90
+ // Up to what the display can do: the system lowers it as it sees fit
91
+ // (Low Power Mode, a display that has no more).
92
+ link.preferredFrameRateRange = CAFrameRateRangeMake(60, 120, 120);
93
+ }
94
+ link.paused = YES;
95
+ [link addToRunLoop:[NSRunLoop currentRunLoop]
96
+ forMode:NSRunLoopCommonModes];
97
+ raw->_link = link;
98
+ raw->_runLoop = CFRunLoopGetCurrent();
99
+ CFRetain(raw->_runLoop);
100
+ dispatch_semaphore_signal(ready);
101
+ // The display link is a source of the run loop: it keeps running.
102
+ for (;;) {
103
+ @autoreleasepool {
104
+ [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
105
+ beforeDate:[NSDate distantFuture]];
106
+ }
107
+ }
108
+ }];
109
+ thread.name = @"RNWebGPU Frames";
110
+ thread.qualityOfService = NSQualityOfServiceUserInteractive;
111
+ [thread start];
112
+ dispatch_semaphore_wait(ready, DISPATCH_TIME_FOREVER);
113
+ return source;
114
+ }
115
+
116
+ // Any thread: the link runs again from its next frame.
117
+ void unpause() {
118
+ CFRunLoopPerformBlock(_runLoop, kCFRunLoopCommonModes, ^{
119
+ if (_paused.exchange(false)) {
120
+ _link.paused = NO;
121
+ }
122
+ });
123
+ CFRunLoopWakeUp(_runLoop);
124
+ }
125
+
126
+ static constexpr int kIdleFramesBeforePause = 8;
127
+
128
+ CADisplayLink *_link = nil;
129
+ CFRunLoopRef _runLoop = nullptr;
130
+ std::atomic<bool> _wanted{false};
131
+ std::atomic<bool> _paused{true};
132
+ // The link's thread only.
133
+ int _idleFrames = 0;
134
+ };
135
+
136
+ // Whether the app is in the foreground and active (see
137
+ // AnimationFrameDispatcher::setForeground): false from the moment it starts to
138
+ // resign active (a lock, a swipe home, an incoming call; the inactive and
139
+ // background states of iOS) until it is active again. The display link does
140
+ // not stop on its own when the app goes to the background: it runs on until
141
+ // the system suspends the app, a second or so of frames whose GPU work iOS
142
+ // refuses.
143
+ static void observeApplicationState() {
144
+ static dispatch_once_t once;
145
+ dispatch_once(&once, ^{
146
+ NSNotificationCenter *center = NSNotificationCenter.defaultCenter;
147
+ [center addObserverForName:UIApplicationWillResignActiveNotification
148
+ object:nil
149
+ queue:nil
150
+ usingBlock:^(NSNotification *) {
151
+ AnimationFrameDispatcher::shared().setForeground(false);
152
+ }];
153
+ [center addObserverForName:UIApplicationDidBecomeActiveNotification
154
+ object:nil
155
+ queue:nil
156
+ usingBlock:^(NSNotification *) {
157
+ AnimationFrameDispatcher::shared().setForeground(true);
158
+ }];
159
+ // The state now, which is the main thread's to read. An app extension has
160
+ // no application: it stays in the foreground.
161
+ dispatch_async(dispatch_get_main_queue(), ^{
162
+ UIApplication *application = RCTSharedApplication();
163
+ if (application != nil &&
164
+ application.applicationState != UIApplicationStateActive) {
165
+ AnimationFrameDispatcher::shared().setForeground(false);
166
+ }
167
+ });
168
+ });
169
+ }
170
+
171
+ std::shared_ptr<AnimationFrameSource> makeAppleAnimationFrameSource() {
172
+ observeApplicationState();
173
+ return AppleAnimationFrameSource::shared();
174
+ }
175
+
176
+ #else
177
+
178
+ // macOS: none for now. Each runtime keeps its own requestAnimationFrame.
179
+ class AppleAnimationFrameSource : public AnimationFrameSource {
180
+ public:
181
+ void requestFrame() override {}
182
+ void onFrame(CADisplayLink *) {}
183
+ };
184
+
185
+ std::shared_ptr<AnimationFrameSource> makeAppleAnimationFrameSource() {
186
+ return nullptr;
187
+ }
188
+
189
+ #endif
190
+
191
+ } // namespace rnwgpu
192
+
193
+ @implementation RNWGAnimationFrameTarget {
194
+ rnwgpu::AppleAnimationFrameSource *_source;
195
+ }
196
+
197
+ - (instancetype)initWithSource:(rnwgpu::AppleAnimationFrameSource *)source {
198
+ if ((self = [super init])) {
199
+ _source = source;
200
+ }
201
+ return self;
202
+ }
203
+
204
+ - (void)onFrame:(CADisplayLink *)link {
205
+ _source->onFrame(link);
206
+ }
207
+
208
+ @end
@@ -45,6 +45,10 @@ public:
45
45
  VideoFrameHandle createTestVideoFrame(uint32_t width, uint32_t height,
46
46
  VideoPixelFormat format) override;
47
47
 
48
+ VideoFrameHandle createNativeBuffer(uint32_t width, uint32_t height,
49
+ wgpu::TextureFormat format,
50
+ bool displayP3) override;
51
+
48
52
  std::unique_ptr<IVideoPlayer>
49
53
  createVideoPlayer(const std::string &path, VideoPixelFormat format) override;
50
54
 
@@ -54,6 +58,8 @@ public:
54
58
 
55
59
  std::function<void(void *)> retainNativeWindow(void *window) override;
56
60
 
61
+ std::shared_ptr<AnimationFrameSource> makeAnimationFrameSource() override;
62
+
57
63
  private:
58
64
  ViewLookup _viewLookup;
59
65
  BlobManagerLookup _blobManagerLookup;
@@ -547,6 +547,14 @@ ApplePlatformContext::createVideoPlayer(const std::string &path,
547
547
  return createAppleVideoPlayer(path, format);
548
548
  }
549
549
 
550
+ // AppleAnimationFrameSource.mm
551
+ std::shared_ptr<AnimationFrameSource> makeAppleAnimationFrameSource();
552
+
553
+ std::shared_ptr<AnimationFrameSource>
554
+ ApplePlatformContext::makeAnimationFrameSource() {
555
+ return makeAppleAnimationFrameSource();
556
+ }
557
+
550
558
  std::string ApplePlatformContext::writeTestVideoFile() {
551
559
  return writeAppleTestVideoFile();
552
560
  }
@@ -685,4 +693,69 @@ ApplePlatformContext::createTestVideoFrame(uint32_t width, uint32_t height,
685
693
  return handle;
686
694
  }
687
695
 
696
+ // An IOSurface-backed pixel buffer that Dawn imports as a render target and
697
+ // Core Animation displays as layer contents (NativeBufferView). The surface is
698
+ // tagged with its color space (kIOSurfaceColorSpace), which Core Animation
699
+ // reads; untagged surfaces are taken as sRGB.
700
+ VideoFrameHandle
701
+ ApplePlatformContext::createNativeBuffer(uint32_t width, uint32_t height,
702
+ wgpu::TextureFormat format,
703
+ bool displayP3) {
704
+ OSType pixelFormat;
705
+ CFStringRef colorSpaceName;
706
+ switch (format) {
707
+ case wgpu::TextureFormat::BGRA8Unorm:
708
+ pixelFormat = kCVPixelFormatType_32BGRA;
709
+ colorSpaceName = displayP3 ? kCGColorSpaceDisplayP3 : kCGColorSpaceSRGB;
710
+ break;
711
+ case wgpu::TextureFormat::RGBA16Float:
712
+ pixelFormat = kCVPixelFormatType_64RGBAHalf;
713
+ colorSpaceName =
714
+ displayP3 ? kCGColorSpaceExtendedDisplayP3 : kCGColorSpaceExtendedSRGB;
715
+ break;
716
+ default:
717
+ throw std::runtime_error(
718
+ "createNativeBuffer: unsupported format on Apple platforms (expected "
719
+ "'bgra8unorm' or 'rgba16float')");
720
+ }
721
+ NSDictionary *attrs = @{
722
+ (NSString *)kCVPixelBufferIOSurfacePropertiesKey : @{},
723
+ (NSString *)kCVPixelBufferMetalCompatibilityKey : @YES,
724
+ };
725
+ CVPixelBufferRef pixelBuffer = NULL;
726
+ CVReturn err =
727
+ CVPixelBufferCreate(kCFAllocatorDefault, width, height, pixelFormat,
728
+ (__bridge CFDictionaryRef)attrs, &pixelBuffer);
729
+ if (err != kCVReturnSuccess || !pixelBuffer) {
730
+ throw std::runtime_error(
731
+ "createNativeBuffer: CVPixelBufferCreate failed (" +
732
+ std::to_string(err) + ")");
733
+ }
734
+ IOSurfaceRef ioSurface = CVPixelBufferGetIOSurface(pixelBuffer);
735
+ if (!ioSurface) {
736
+ CFRelease(pixelBuffer);
737
+ throw std::runtime_error(
738
+ "createNativeBuffer: pixel buffer is not IOSurface-backed");
739
+ }
740
+ CGColorSpaceRef colorSpace = CGColorSpaceCreateWithName(colorSpaceName);
741
+ if (colorSpace != NULL) {
742
+ CFPropertyListRef plist = CGColorSpaceCopyPropertyList(colorSpace);
743
+ if (plist != NULL) {
744
+ IOSurfaceSetValue(ioSurface, kIOSurfaceColorSpace, plist);
745
+ CFRelease(plist);
746
+ }
747
+ CGColorSpaceRelease(colorSpace);
748
+ }
749
+
750
+ VideoFrameHandle handle;
751
+ handle.handle = (void *)ioSurface;
752
+ handle.width = width;
753
+ handle.height = height;
754
+ handle.colorSpace.primaries = displayP3
755
+ ? wgpu::ColorSpacePrimariesDawn::DisplayP3
756
+ : wgpu::ColorSpacePrimariesDawn::SRGB;
757
+ handle.deleter = [pixelBuffer]() { CFRelease(pixelBuffer); };
758
+ return handle;
759
+ }
760
+
688
761
  } // namespace rnwgpu
@@ -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
@@ -1,79 +1,58 @@
1
1
  #import <CoreGraphics/CoreGraphics.h>
2
2
  #import <Foundation/Foundation.h>
3
3
  #import <QuartzCore/CAMetalLayer.h>
4
- #import <QuartzCore/CATransaction.h>
5
4
 
6
- #include "CanvasColorSpace.h"
7
- #include "webgpu/webgpu_cpp.h"
5
+ #include "MetalLayerColorSpace.h"
8
6
 
9
7
  namespace rnwgpu {
10
8
 
11
9
  // 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.
22
21
  //
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);
55
44
  const bool extendedRange =
56
- isFloat && toneMappingMode == CanvasToneMappingMode::Extended;
45
+ colorSpace.toneMappingMode == CanvasToneMappingMode::Extended;
57
46
  // The property does not exist on tvOS (the SDK marks it unavailable, which
58
47
  // @available cannot work around), so it is compiled only where it exists.
59
48
  // On tvOS "extended" behaves like "standard".
60
49
  #if TARGET_OS_IOS || TARGET_OS_OSX || TARGET_OS_VISION
61
50
  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;
65
52
  }
66
53
  #else
67
54
  (void)extendedRange;
68
55
  #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
- }
77
56
  }
78
57
 
79
58
  } // namespace rnwgpu
package/apple/MetalView.h CHANGED
@@ -6,6 +6,10 @@
6
6
  @interface MetalView : RNWGPlatformView
7
7
 
8
8
  @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;
9
13
 
10
14
  - (void)configure;
11
15
  - (void)update;
@@ -1,4 +1,5 @@
1
1
  #import "MetalView.h"
2
+ #include "MetalLayerColorSpace.h"
2
3
  #import "WebGPURuntime.h"
3
4
  #import "webgpu/webgpu_cpp.h"
4
5
 
@@ -27,6 +28,18 @@
27
28
  if (manager == nullptr) {
28
29
  return;
29
30
  }
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);
30
43
  // Retain the layer for as long as SurfaceInfo holds the pointer: the
31
44
  // latched attach (and the flush lambda that adopts it) can outlive this
32
45
  // view, e.g. across a dev reload where the registry is cleared before
@@ -47,6 +60,7 @@
47
60
  CFBridgingRelease(layer);
48
61
  });
49
62
  });
63
+ info->setLayerColorSpace(layerColorSpace);
50
64
  // The attach is adopted at the next frame boundary by the rendering thread;
51
65
  // schedule a flush so contexts that are not currently rendering still pick
52
66
  // it up (and present their last offscreen frame).
@@ -0,0 +1,88 @@
1
+ #import <Foundation/Foundation.h>
2
+ #import <Metal/Metal.h>
3
+
4
+ #include <atomic>
5
+ #include <memory>
6
+ #include <utility>
7
+
8
+ #include "NativeBufferViewRegistry.h"
9
+
10
+ namespace rnwgpu {
11
+
12
+ namespace {
13
+
14
+ // A fence that has not signaled after this long belongs to work that will
15
+ // never finish (a lost device): the buffer is dropped, as on Android.
16
+ constexpr int64_t kTimeoutSeconds = 10;
17
+
18
+ // One wait, finished by whichever comes first: the event's notification or
19
+ // the timeout. Metal cannot cancel a notification, so after a timeout the
20
+ // listener keeps its block (and this small object) until the event signals,
21
+ // possibly never; the fence and the buffer captured by `done` are released
22
+ // when the wait finishes. ANGLE's Metal sync (SyncMtl.mm) makes the same
23
+ // trade-off.
24
+ struct PendingFenceWait {
25
+ wgpu::SharedFence fence;
26
+ std::function<void(bool)> done;
27
+ std::atomic<bool> finished{false};
28
+
29
+ void finish(bool signaled) {
30
+ if (finished.exchange(true)) {
31
+ return;
32
+ }
33
+ auto callback = std::move(done);
34
+ fence = nullptr;
35
+ if (!signaled) {
36
+ NSLog(@"[WebGPU] presentNativeBuffer: the fence did not signal within "
37
+ @"%lld s; the buffer is dropped",
38
+ kTimeoutSeconds);
39
+ }
40
+ callback(signaled);
41
+ }
42
+ };
43
+
44
+ } // namespace
45
+
46
+ // The MTLSharedEvent behind a Dawn fence, waited on with a listener: no
47
+ // thread blocks. The notification and the timeout run on a private serial
48
+ // queue.
49
+ void waitForSharedFence(wgpu::SharedFence fence, uint64_t signaledValue,
50
+ std::function<void(bool)> done) {
51
+ wgpu::SharedFenceExportInfo info{};
52
+ wgpu::SharedFenceMTLSharedEventExportInfo mtlInfo{};
53
+ info.nextInChain = &mtlInfo;
54
+ fence.ExportInfo(&info);
55
+ id<MTLSharedEvent> event = (__bridge id<MTLSharedEvent>)mtlInfo.sharedEvent;
56
+ if (info.type != wgpu::SharedFenceType::MTLSharedEvent || event == nil) {
57
+ NSLog(@"[WebGPU] presentNativeBuffer: the fence is not an MTLSharedEvent; "
58
+ @"the buffer is dropped");
59
+ done(false);
60
+ return;
61
+ }
62
+ if (event.signaledValue >= signaledValue) {
63
+ done(true);
64
+ return;
65
+ }
66
+ static dispatch_queue_t queue = dispatch_queue_create(
67
+ "com.webgpu.NativeBufferView.fence", DISPATCH_QUEUE_SERIAL);
68
+ static MTLSharedEventListener *listener =
69
+ [[MTLSharedEventListener alloc] initWithDispatchQueue:queue];
70
+ // Holds the fence (which keeps the event, and Dawn's view of it, alive)
71
+ // until the wait finishes.
72
+ auto pending = std::make_shared<PendingFenceWait>();
73
+ pending->fence = std::move(fence);
74
+ pending->done = std::move(done);
75
+ [event
76
+ notifyListener:listener
77
+ atValue:signaledValue
78
+ block:^(id<MTLSharedEvent> /* event */, uint64_t /* value */) {
79
+ pending->finish(true);
80
+ }];
81
+ dispatch_after(
82
+ dispatch_time(DISPATCH_TIME_NOW, kTimeoutSeconds * NSEC_PER_SEC), queue,
83
+ ^{
84
+ pending->finish(false);
85
+ });
86
+ }
87
+
88
+ } // namespace rnwgpu
package/apple/RNWGUIKit.h CHANGED
@@ -1,10 +1,13 @@
1
1
  #ifndef PACKAGES_WEBGPU_APPLE_RNWGUIKIT_H_
2
2
  #define PACKAGES_WEBGPU_APPLE_RNWGUIKIT_H_
3
3
 
4
+ // Select UIKit or AppKit before importing either framework.
5
+ #import <TargetConditionals.h>
6
+
4
7
  #if !TARGET_OS_OSX
5
8
  #import <UIKit/UIKit.h>
6
9
  #else
7
- #import <Appkit/Appkit.h>
10
+ #import <AppKit/AppKit.h>
8
11
  #endif
9
12
 
10
13
  #if !TARGET_OS_OSX
@@ -46,13 +46,38 @@ static std::shared_ptr<rnwgpu::RNWebGPUManager> webgpuManager;
46
46
  return webgpuManager;
47
47
  }
48
48
 
49
- #pragma Setup and invalidation
49
+ #pragma mark - Setup and invalidation
50
50
 
51
51
  + (BOOL)requiresMainQueueSetup {
52
52
  return YES;
53
53
  }
54
54
 
55
+ #if TARGET_OS_OSX
56
+ - (instancetype)init {
57
+ if (self = [super init]) {
58
+ [[NSNotificationCenter defaultCenter]
59
+ addObserver:self
60
+ selector:@selector(applicationWillTerminate:)
61
+ name:NSApplicationWillTerminateNotification
62
+ object:nil];
63
+ }
64
+ return self;
65
+ }
66
+
67
+ - (void)applicationWillTerminate:(NSNotification *)notification {
68
+ // AppKit exits without necessarily invalidating the React instance. Release
69
+ // the manager before static teardown destroys SurfaceRegistry and its mutex.
70
+ [self invalidate];
71
+ }
72
+ #endif
73
+
55
74
  - (void)invalidate {
75
+ #if TARGET_OS_OSX
76
+ [[NSNotificationCenter defaultCenter]
77
+ removeObserver:self
78
+ name:NSApplicationWillTerminateNotification
79
+ object:nil];
80
+ #endif
56
81
  webgpuManager = nil;
57
82
  }
58
83
 
@@ -0,0 +1,15 @@
1
+ #pragma once
2
+
3
+ // RNWGUIKit selects AppKit for native macOS and UIKit for other Apple targets.
4
+ #import "RNWGUIKit.h"
5
+ #import <React/RCTViewComponentView.h>
6
+
7
+ NS_ASSUME_NONNULL_BEGIN
8
+
9
+ // NativeBufferView: displays an IOSurface that JS presented
10
+ // (RNWebGPU.presentNativeBuffer) as layer contents, with no swap chain and no
11
+ // GPU device on the display side. See NativeBufferViewRegistry.h.
12
+ @interface WebGPUNativeBufferView : RCTViewComponentView
13
+ @end
14
+
15
+ NS_ASSUME_NONNULL_END