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,163 @@
1
+ #pragma once
2
+
3
+ #include <cstdint>
4
+ #include <functional>
5
+ #include <memory>
6
+ #include <mutex>
7
+ #include <unordered_map>
8
+
9
+ #include "webgpu/webgpu_cpp.h"
10
+
11
+ #include "PlatformContext.h"
12
+
13
+ namespace rnwgpu {
14
+
15
+ // The color space a NativeBufferView displays a buffer in. The buffer holds
16
+ // premultiplied, gamma-encoded values in these primaries. rgba16float gives
17
+ // more precision, not extended range: the view shows values in [0, 1] and
18
+ // clamps the rest.
19
+ enum class NativeBufferColorSpace { SRGB, DisplayP3 };
20
+
21
+ // A native buffer handed to a NativeBufferView: an AHardwareBuffer* (Android)
22
+ // or an IOSurfaceRef (Apple platforms), with a reference of its own, released
23
+ // when the last holder (the registry, a pending fence wait, the view) drops
24
+ // it. The compositor takes references of its own on what it displays
25
+ // (Bitmap.wrapHardwareBuffer, CALayer.contents), so dropping this one while
26
+ // the buffer is on screen is safe.
27
+ class NativeBufferContent {
28
+ public:
29
+ // Validates the frame for display (a single-plane RGBA buffer in a format
30
+ // the view can show) and takes a reference on its buffer. Throws a
31
+ // std::runtime_error naming the problem.
32
+ static std::shared_ptr<NativeBufferContent>
33
+ fromFrame(const VideoFrameHandle &frame);
34
+
35
+ ~NativeBufferContent();
36
+
37
+ NativeBufferContent(const NativeBufferContent &) = delete;
38
+ NativeBufferContent &operator=(const NativeBufferContent &) = delete;
39
+
40
+ void *buffer() const { return _buffer; }
41
+ uint32_t width() const { return _width; }
42
+ uint32_t height() const { return _height; }
43
+ NativeBufferColorSpace colorSpace() const { return _colorSpace; }
44
+
45
+ private:
46
+ NativeBufferContent(void *buffer, uint32_t width, uint32_t height,
47
+ NativeBufferColorSpace colorSpace);
48
+
49
+ void *_buffer;
50
+ uint32_t _width;
51
+ uint32_t _height;
52
+ NativeBufferColorSpace _colorSpace;
53
+ };
54
+
55
+ // Waits for `fence` to reach `signaledValue` without blocking the caller, then
56
+ // calls `done` from another thread: true once the fence signaled, false when
57
+ // the wait failed or gave up after 10 s (the reason is logged). Implemented
58
+ // per platform: a sync-fd poll on a waiter thread on Android, an
59
+ // MTLSharedEvent listener with a timer on Apple platforms.
60
+ void waitForSharedFence(wgpu::SharedFence fence, uint64_t signaledValue,
61
+ std::function<void(bool)> done);
62
+
63
+ // The buffers presented to each NativeBufferView, keyed by a view id that JS
64
+ // allocates (allocateViewId) and passes to the native view as a prop. JS
65
+ // presents a buffer from any runtime (presentNativeBuffer); once its fence
66
+ // has signaled the buffer becomes the view's content and the view's listener
67
+ // is called, from any thread. The view then reads the content on the main
68
+ // thread and hands it to the compositor.
69
+ //
70
+ // Presents are ordered: a buffer whose fence signals after a later present
71
+ // already landed is dropped, so the view always ends on the last buffer
72
+ // presented.
73
+ //
74
+ // An entry has two owners: the JS component (retainFromJS on mount,
75
+ // releaseFromJS on unmount, releaseAllFromJS on reload) and the native view
76
+ // (setListener / detachView). It is erased once both let go, in either order.
77
+ // A native view that attaches after the JS component let go still gets an
78
+ // entry, which detachView erases. React StrictMode's simulated unmount (JS
79
+ // effects re-run, native view kept) releases and retains again.
80
+ class NativeBufferViewRegistry {
81
+ public:
82
+ using Listener = std::function<void()>;
83
+
84
+ static NativeBufferViewRegistry &getInstance() {
85
+ static NativeBufferViewRegistry instance;
86
+ return instance;
87
+ }
88
+
89
+ NativeBufferViewRegistry(const NativeBufferViewRegistry &) = delete;
90
+ NativeBufferViewRegistry &
91
+ operator=(const NativeBufferViewRegistry &) = delete;
92
+
93
+ // Unique for the life of the process: the registry outlives a JS reload.
94
+ // Creates no entry (React StrictMode may discard the id): retainFromJS does.
95
+ int allocateViewId() {
96
+ std::lock_guard<std::mutex> lock(_mutex);
97
+ return ++_nextViewId;
98
+ }
99
+
100
+ // Makes `content` the view's content once `fence` (if any) has reached
101
+ // `signaledValue` and, on Android, once `acquireFenceFd` (a sync fd the
102
+ // producer signals when it is done writing the buffer, or -1) has
103
+ // signaled. Takes ownership of `acquireFenceFd`. Returns immediately.
104
+ //
105
+ // A present to a view the JS component does not hold (released, or never
106
+ // retained) is dropped: nothing would ever free its buffer.
107
+ void present(int viewId, std::shared_ptr<NativeBufferContent> content,
108
+ wgpu::SharedFence fence, uint64_t signaledValue,
109
+ int acquireFenceFd = -1);
110
+
111
+ // The latest ready content and its sequence number (0 when there is none
112
+ // yet). A view keeps the sequence number of what it shows and skips a
113
+ // content it already has.
114
+ std::shared_ptr<NativeBufferContent> content(int viewId, uint64_t *sequence);
115
+
116
+ // The native view attaches (a listener) or detaches (nullptr). The listener
117
+ // is called from any thread whenever new content is ready, and once right
118
+ // away if the view already has content.
119
+ void setListener(int viewId, Listener listener);
120
+
121
+ // The native view is gone for good: drops its listener, and the entry when
122
+ // the JS component has released it too.
123
+ void detachView(int viewId);
124
+
125
+ // The JS component mounted (or mounted again with the same id, when React
126
+ // StrictMode re-runs its effects): creates the entry if needed and takes
127
+ // the JS ownership.
128
+ void retainFromJS(int viewId);
129
+
130
+ // The JS component unmounted: drops the entry when no native view is
131
+ // attached to it (else detachView does).
132
+ void releaseFromJS(int viewId);
133
+
134
+ // The JS runtime is going away (a reload): its components never run their
135
+ // cleanup, so this releases every entry from JS.
136
+ void releaseAllFromJS();
137
+
138
+ private:
139
+ NativeBufferViewRegistry() = default;
140
+
141
+ struct Entry {
142
+ std::shared_ptr<NativeBufferContent> content;
143
+ // The last present, and the one `content` comes from.
144
+ uint64_t presentedSequence = 0;
145
+ uint64_t readySequence = 0;
146
+ Listener listener;
147
+ bool ownedByJS = false;
148
+ };
149
+
150
+ // Erases `it` when neither the JS component nor a native view holds it,
151
+ // moving its content to `released` so the buffer is freed outside the lock.
152
+ void eraseIfUnowned(std::unordered_map<int, Entry>::iterator it,
153
+ std::shared_ptr<NativeBufferContent> *released);
154
+
155
+ void deliver(int viewId, uint64_t sequence,
156
+ std::shared_ptr<NativeBufferContent> content);
157
+
158
+ std::mutex _mutex;
159
+ std::unordered_map<int, Entry> _entries;
160
+ int _nextViewId = 0;
161
+ };
162
+
163
+ } // namespace rnwgpu
@@ -13,6 +13,8 @@
13
13
 
14
14
  namespace rnwgpu {
15
15
 
16
+ class AnimationFrameSource;
17
+
16
18
  struct ImageData {
17
19
  std::vector<uint8_t> data;
18
20
  size_t width;
@@ -226,6 +228,17 @@ public:
226
228
  virtual VideoFrameHandle createTestVideoFrame(uint32_t width, uint32_t height,
227
229
  VideoPixelFormat format) = 0;
228
230
 
231
+ // Allocate an empty, GPU-renderable buffer that a NativeBufferView can
232
+ // display: an AHardwareBuffer (Android) or an IOSurface (Apple platforms),
233
+ // with premultiplied pixels in `format`, tagged with `displayP3` or sRGB
234
+ // primaries (VideoFrameHandle.colorSpace.primaries; on Apple platforms the
235
+ // IOSurface is tagged too). Throws a message containing "unsupported" for a
236
+ // format the platform can't display (bgra8unorm on Android, rgba8unorm on
237
+ // Apple platforms).
238
+ virtual VideoFrameHandle createNativeBuffer(uint32_t width, uint32_t height,
239
+ wgpu::TextureFormat format,
240
+ bool displayP3) = 0;
241
+
229
242
  // Open a video file at `path` for playback. The returned player yields
230
243
  // IOSurface / AHardwareBuffer-backed frames via copyLatestFrame().
231
244
  //
@@ -249,6 +262,13 @@ public:
249
262
  // with it. The releaser can run on any thread.
250
263
  virtual std::function<void(void *)> retainNativeWindow(void *window) = 0;
251
264
 
265
+ // The display's frames, for requestAnimationFrame (see AnimationFrames.h);
266
+ // null where the platform has none, and every runtime then uses its own
267
+ // global requestAnimationFrame.
268
+ virtual std::shared_ptr<AnimationFrameSource> makeAnimationFrameSource() {
269
+ return nullptr;
270
+ }
271
+
252
272
  // Write a small procedurally-generated test video to a temporary location
253
273
  // and return its absolute path. Lets the SharedTextureMemory example play
254
274
  // a real decoded video without bundling an asset.
@@ -1,6 +1,9 @@
1
1
  #include "RNWebGPUManager.h"
2
2
 
3
+ #include "AnimationFrames.h"
4
+
3
5
  #include "GPU.h"
6
+ #include "NativeBufferViewRegistry.h"
4
7
  #include "NativeObject.h"
5
8
  #include "RNWebGPU.h"
6
9
 
@@ -22,8 +25,6 @@
22
25
  #include "GPUError.h"
23
26
  #include "GPUExternalTexture.h"
24
27
  #include "GPUInternalError.h"
25
- #include "GPUNativeBufferExternalTexture.h"
26
- #include "GPUNativeBufferTexture.h"
27
28
  #include "GPUOutOfMemoryError.h"
28
29
  #include "GPUPipelineLayout.h"
29
30
  #include "GPUQuerySet.h"
@@ -95,6 +96,17 @@ RNWebGPUManager::RNWebGPUManager(
95
96
  _jsRuntime->global().setProperty(*_jsRuntime, "GPUTextureUsage",
96
97
  GPUTextureUsage::create(*_jsRuntime));
97
98
 
99
+ // requestAnimationFrame paced by the display, on every runtime (see
100
+ // src/animationFrame.ts). The source is the platform's, kept across reloads;
101
+ // the HostObject is handed to other runtimes by reference, like the
102
+ // helpers below.
103
+ AnimationFrameDispatcher::shared().setSource(
104
+ _platformContext->makeAnimationFrameSource());
105
+ _jsRuntime->global().setProperty(
106
+ *_jsRuntime, "__webgpuAnimationFrames",
107
+ jsi::Object::createFromHostObject(
108
+ *_jsRuntime, std::make_shared<AnimationFramesHostObject>()));
109
+
98
110
  // Install global helper functions for Worklets serialization
99
111
  // These are standalone functions that don't require RNWebGPU instance
100
112
  installWebGPUWorkletHelpers(*_jsRuntime);
@@ -118,8 +130,6 @@ void RNWebGPUManager::installConstructors(jsi::Runtime &runtime) {
118
130
  GPUDeviceLostInfo::installConstructor(runtime);
119
131
  GPUError::installConstructor(runtime);
120
132
  GPUExternalTexture::installConstructor(runtime);
121
- GPUNativeBufferExternalTexture::installConstructor(runtime);
122
- GPUNativeBufferTexture::installConstructor(runtime);
123
133
  GPUInternalError::installConstructor(runtime);
124
134
  GPUOutOfMemoryError::installConstructor(runtime);
125
135
  GPUValidationError::installConstructor(runtime);
@@ -169,6 +179,9 @@ RNWebGPUManager::~RNWebGPUManager() {
169
179
  // never run their JS cleanup, and their ids are not handed out again (see
170
180
  // SurfaceRegistry::allocateContextId).
171
181
  SurfaceRegistry::getInstance().clear();
182
+ // Same for the NativeBufferView entries: their buffers are freed once
183
+ // their native views detach (or right away when there is none).
184
+ NativeBufferViewRegistry::getInstance().releaseAllFromJS();
172
185
  if (PlatformContext::current() == _platformContext) {
173
186
  PlatformContext::setCurrent(nullptr);
174
187
  }
@@ -10,6 +10,7 @@
10
10
  #include <functional>
11
11
  #include <memory>
12
12
  #include <mutex>
13
+ #include <optional>
13
14
  #include <shared_mutex>
14
15
  #include <stdexcept>
15
16
  #include <thread>
@@ -37,17 +38,6 @@ void WaitForCommandsToBeScheduled(WGPUDevice device);
37
38
 
38
39
  namespace rnwgpu {
39
40
 
40
- #ifdef __APPLE__
41
- // Tags the CAMetalLayer with the colorspace matching the configured texture
42
- // format and the canvas's colorSpace, and opts it into the display's extended
43
- // dynamic range for an "extended" toneMapping mode. Implemented in
44
- // apple/MetalLayerColorSpace.mm.
45
- void applyCAMetalLayerColorSpace(void *nativeSurface,
46
- wgpu::TextureFormat format,
47
- CanvasColorSpace colorSpace,
48
- CanvasToneMappingMode toneMappingMode);
49
- #endif
50
-
51
41
  struct NativeInfo {
52
42
  void *nativeSurface;
53
43
  int width;
@@ -224,6 +214,21 @@ public:
224
214
  }
225
215
  }
226
216
 
217
+ #ifdef __APPLE__
218
+ // The colorSpace and toneMapping the platform view tagged its layer with
219
+ // when the canvas mounted, which configure() is checked against (see
220
+ // GPUCanvasContext::configure). Unset until a view attaches.
221
+ void setLayerColorSpace(CanvasLayerColorSpace colorSpace) {
222
+ std::unique_lock<std::shared_mutex> lock(_mutex);
223
+ _layerColorSpace = colorSpace;
224
+ }
225
+
226
+ std::optional<CanvasLayerColorSpace> getLayerColorSpace() {
227
+ std::shared_lock<std::shared_mutex> lock(_mutex);
228
+ return _layerColorSpace;
229
+ }
230
+ #endif
231
+
227
232
  // The platform surface is being destroyed: detach immediately. If the
228
233
  // context is configured, rendering continues into an offscreen texture whose
229
234
  // content is blitted to the next attached surface; present() no-ops until
@@ -298,10 +303,6 @@ public:
298
303
  config.usage |= wgpu::TextureUsage::CopyDst;
299
304
  }
300
305
  configureSurfaceLocked(config);
301
- #ifdef __APPLE__
302
- applyCAMetalLayerColorSpace(_nativeSurface, _config.format, _colorSpace,
303
- _toneMappingMode);
304
- #endif
305
306
  if (blit) {
306
307
  presentBlit = blitOffscreenToSurfaceLocked();
307
308
  device = _config.device;
@@ -336,16 +337,15 @@ public:
336
337
  // --- Rendering thread
337
338
  // -------------------------------------------------------
338
339
 
339
- void configure(
340
- wgpu::SurfaceConfiguration &newConfig,
341
- std::vector<wgpu::TextureFormat> viewFormats,
342
- CanvasColorSpace colorSpace = CanvasColorSpace::SRGB,
343
- CanvasToneMappingMode toneMappingMode = CanvasToneMappingMode::Standard) {
340
+ // The colorspace of a CAMetalLayer is not set here: the platform view tags
341
+ // the layer on the main thread as the canvas mounts (see
342
+ // apple/MetalLayerColorSpace.h), so that nothing here changes the layer in
343
+ // a CATransaction of the calling thread.
344
+ void configure(wgpu::SurfaceConfiguration &newConfig,
345
+ std::vector<wgpu::TextureFormat> viewFormats) {
344
346
  applyPendingAttach(/* supersedeInFlightFrame = */ true);
345
347
  std::unique_lock<std::shared_mutex> lock(_mutex);
346
348
  _viewFormats = std::move(viewFormats);
347
- _colorSpace = colorSpace;
348
- _toneMappingMode = toneMappingMode;
349
349
  _config = newConfig;
350
350
  // The caller's viewFormats storage dies with the call; point the stored
351
351
  // configuration at our own copy.
@@ -410,8 +410,6 @@ public:
410
410
  }
411
411
  _texture = nullptr;
412
412
  _config = {};
413
- _colorSpace = CanvasColorSpace::SRGB;
414
- _toneMappingMode = CanvasToneMappingMode::Standard;
415
413
  _viewFormats.clear();
416
414
  _acquiredFromSurface = false;
417
415
  _frameEpoch++;
@@ -917,10 +915,6 @@ private:
917
915
  void _configureLocked() {
918
916
  if (_surface) {
919
917
  configureSurfaceLocked(_config);
920
- #ifdef __APPLE__
921
- applyCAMetalLayerColorSpace(_nativeSurface, _config.format, _colorSpace,
922
- _toneMappingMode);
923
- #endif
924
918
  } else {
925
919
  _texture = createOffscreenTextureLocked();
926
920
  }
@@ -1283,8 +1277,10 @@ private:
1283
1277
  // that _config.viewFormats points at.
1284
1278
  wgpu::SurfaceConfiguration _config;
1285
1279
  std::vector<wgpu::TextureFormat> _viewFormats;
1286
- CanvasColorSpace _colorSpace = CanvasColorSpace::SRGB;
1287
- CanvasToneMappingMode _toneMappingMode = CanvasToneMappingMode::Standard;
1280
+ #ifdef __APPLE__
1281
+ // What the platform view tagged its layer with, see setLayerColorSpace.
1282
+ std::optional<CanvasLayerColorSpace> _layerColorSpace;
1283
+ #endif
1288
1284
  // Keeps the Dawn instance alive for as long as any canvas exists.
1289
1285
  wgpu::Instance _gpu;
1290
1286
  // Native view size in dp (surfaced as clientWidth/clientHeight on the JS
@@ -30,7 +30,7 @@ async::AsyncTaskHandle GPUAdapter::requestDevice(
30
30
  jsi::Runtime &runtime,
31
31
  std::optional<std::shared_ptr<GPUDeviceDescriptor>> descriptor) {
32
32
  // Native frame import (importSharedTextureMemory, importExternalTexture,
33
- // copyExternalImageToTexture with a NativeVideoFrame) needs no feature
33
+ // copyExternalImageToTexture with a NativeBuffer) needs no feature
34
34
  // request, like importExternalTexture on the web: the Dawn features behind
35
35
  // it are added to requiredFeatures here, each one when the adapter supports
36
36
  // it. Requesting a feature the adapter lacks would make RequestDevice fail,
@@ -1,15 +1,30 @@
1
1
  #include "GPUCanvasContext.h"
2
2
  #include "Convertors.h"
3
3
  #include "RNWebGPUManager.h"
4
+ #include "WGPULogger.h"
4
5
  #include <algorithm>
5
6
  #include <memory>
6
7
  #include <mutex>
8
+ #include <string>
7
9
  #include <utility>
8
10
  #include <vector>
9
11
 
10
12
  namespace rnwgpu {
11
13
 
14
+ namespace {
15
+
16
+ const char *colorSpaceName(CanvasColorSpace colorSpace) {
17
+ return colorSpace == CanvasColorSpace::DisplayP3 ? "display-p3" : "srgb";
18
+ }
19
+
20
+ const char *toneMappingModeName(CanvasToneMappingMode mode) {
21
+ return mode == CanvasToneMappingMode::Extended ? "extended" : "standard";
22
+ }
23
+
24
+ } // namespace
25
+
12
26
  void GPUCanvasContext::configure(
27
+ jsi::Runtime &runtime,
13
28
  std::shared_ptr<GPUCanvasConfiguration> configuration) {
14
29
  Convertor conv;
15
30
  wgpu::SurfaceConfiguration surfaceConfiguration;
@@ -27,11 +42,34 @@ void GPUCanvasContext::configure(
27
42
 
28
43
  #ifdef __APPLE__
29
44
  surfaceConfiguration.alphaMode = configuration->alphaMode;
45
+ // The layer of a Canvas is tagged on the main thread when it mounts, from
46
+ // its colorSpace and toneMapping props, and keeps that tag: tagging it from
47
+ // here would commit a CATransaction off the main thread. Say so when the
48
+ // configuration asks for something else, once per context.
49
+ const CanvasLayerColorSpace requested{configuration->colorSpace,
50
+ configuration->toneMappingMode};
51
+ auto layerColorSpace = _surfaceInfo->getLayerColorSpace();
52
+ if (!_warnedLayerColorSpace && layerColorSpace.has_value() &&
53
+ *layerColorSpace != requested) {
54
+ _warnedLayerColorSpace = true;
55
+ std::string message =
56
+ std::string("[WebGPU] configure() asks for colorSpace \"") +
57
+ colorSpaceName(requested.colorSpace) + "\" and toneMapping \"" +
58
+ toneMappingModeName(requested.toneMappingMode) +
59
+ "\", but the canvas was mounted with colorSpace \"" +
60
+ colorSpaceName(layerColorSpace->colorSpace) + "\" and toneMapping \"" +
61
+ toneMappingModeName(layerColorSpace->toneMappingMode) +
62
+ "\". On iOS and macOS these come from the colorSpace and toneMapping "
63
+ "props of the Canvas, read when it mounts: pass the same values there.";
64
+ try {
65
+ Logger::warnToJavascriptConsole(runtime, message);
66
+ } catch (const jsi::JSIException &) {
67
+ // A runtime without a console (a bare worklet runtime).
68
+ }
69
+ }
30
70
  #endif
31
71
  surfaceConfiguration.presentMode = wgpu::PresentMode::Fifo;
32
- _surfaceInfo->configure(surfaceConfiguration, std::move(viewFormats),
33
- configuration->colorSpace,
34
- configuration->toneMappingMode);
72
+ _surfaceInfo->configure(surfaceConfiguration, std::move(viewFormats));
35
73
  }
36
74
 
37
75
  void GPUCanvasContext::unconfigure() { _surfaceInfo->unconfigure(); }
@@ -53,8 +53,8 @@ public:
53
53
  static void definePrototype(jsi::Runtime &runtime, jsi::Object &prototype) {
54
54
  installGetter(runtime, prototype, "__brand", &GPUCanvasContext::getBrand);
55
55
  installGetter(runtime, prototype, "canvas", &GPUCanvasContext::getCanvas);
56
- installMethod(runtime, prototype, "configure",
57
- &GPUCanvasContext::configure);
56
+ installMethodWithRuntime(runtime, prototype, "configure",
57
+ &GPUCanvasContext::configure);
58
58
  installMethod(runtime, prototype, "unconfigure",
59
59
  &GPUCanvasContext::unconfigure);
60
60
  installMethod(runtime, prototype, "getCurrentTexture",
@@ -64,7 +64,8 @@ public:
64
64
 
65
65
  // TODO: is this ok?
66
66
  inline const wgpu::Surface get() { return nullptr; }
67
- void configure(std::shared_ptr<GPUCanvasConfiguration> configuration);
67
+ void configure(jsi::Runtime &runtime,
68
+ std::shared_ptr<GPUCanvasConfiguration> configuration);
68
69
  void unconfigure();
69
70
  std::shared_ptr<GPUTexture> getCurrentTexture();
70
71
  // Present is explicit on every runtime (main JS, Reanimated UI, and dedicated
@@ -84,6 +85,9 @@ private:
84
85
  std::mutex _currentTextureMutex;
85
86
  std::shared_ptr<GPUTexture> _currentTexture;
86
87
  uint64_t _currentTextureEpoch = 0;
88
+ // Whether configure() already warned that its colorSpace or toneMapping
89
+ // differs from the Canvas props the layer was tagged with (Apple only).
90
+ bool _warnedLayerColorSpace = false;
87
91
  };
88
92
 
89
93
  } // namespace rnwgpu
@@ -446,54 +446,25 @@ std::shared_ptr<GPUExternalTexture> GPUDevice::importExternalTexture(
446
446
 
447
447
  std::shared_ptr<GPUSharedTextureMemory> GPUDevice::importSharedTextureMemory(
448
448
  std::shared_ptr<GPUSharedTextureMemoryDescriptor> descriptor) {
449
- if (!descriptor || descriptor->handle == nullptr) {
450
- throw std::runtime_error("GPUDevice::importSharedTextureMemory(): handle "
451
- "must be a non-null native pointer");
449
+ static constexpr const char *kCaller = "GPUDevice::importSharedTextureMemory";
450
+ if (!descriptor || (!descriptor->source && descriptor->handle == nullptr)) {
451
+ throw std::runtime_error(
452
+ "GPUDevice::importSharedTextureMemory(): source (a NativeBuffer) or "
453
+ "handle (a non-null native pointer) is required");
452
454
  }
453
-
454
- wgpu::SharedTextureMemoryDescriptor desc{};
455
455
  std::string label = descriptor->label.value_or("");
456
- if (!label.empty()) {
457
- desc.label = wgpu::StringView(label.c_str(), label.size());
458
- }
459
-
460
- #if defined(__APPLE__)
461
- wgpu::SharedTextureMemoryIOSurfaceDescriptor platformDesc{};
462
- platformDesc.ioSurface = descriptor->handle;
463
- // Default off: enabling it propagates StorageBinding into properties.usage,
464
- // which then forces memory.createTexture() (no-descriptor form) to validate
465
- // the format against storage capabilities. bgra8unorm (the standard
466
- // CVPixelBuffer format) only supports storage when the device opts into the
467
- // bgra8unorm-storage feature, so unconditionally setting this here breaks
468
- // the common sample-only case.
469
- platformDesc.allowStorageBinding = false;
470
- desc.nextInChain = &platformDesc;
471
- #elif defined(__ANDROID__)
472
- wgpu::SharedTextureMemoryAHardwareBufferDescriptor platformDesc{};
473
- platformDesc.handle = descriptor->handle;
474
- desc.nextInChain = &platformDesc;
475
- #else
476
- throw std::runtime_error(
477
- "GPUDevice::importSharedTextureMemory(): unsupported platform");
478
- #endif
479
-
480
- auto memory = _instance.ImportSharedTextureMemory(&desc);
481
- // Dawn reports a failed import (feature missing, unusable handle) as a
482
- // validation error and returns an error object rather than null, with no
483
- // format in its properties: the format getter of any texture created from
484
- // it would throw. Fail the import instead.
485
- wgpu::SharedTextureMemoryProperties properties{};
486
- if (memory == nullptr ||
487
- memory.GetProperties(&properties) != wgpu::Status::Success ||
488
- properties.format == wgpu::TextureFormat::Undefined) {
489
- throw std::runtime_error(
490
- "GPUDevice::importSharedTextureMemory(): the import failed - is the "
491
- "'shared-texture-memory-iosurface' (Apple) or "
492
- "'shared-texture-memory-ahardware-buffer' (Android) feature enabled "
493
- "on the device, and the handle a usable IOSurface / AHardwareBuffer?");
456
+ wgpu::SharedTextureMemory memory;
457
+ if (descriptor->source) {
458
+ memory = native_frame::importMemory(_instance, descriptor->source->handle(),
459
+ label, kCaller);
460
+ } else {
461
+ VideoFrameHandle frame;
462
+ frame.handle = descriptor->handle;
463
+ memory = native_frame::importMemory(_instance, frame, label, kCaller);
494
464
  }
495
- return std::make_shared<GPUSharedTextureMemory>(_instance, std::move(memory),
496
- std::move(label));
465
+ return std::make_shared<GPUSharedTextureMemory>(
466
+ _instance, std::move(memory), std::move(label),
467
+ std::move(descriptor->source));
497
468
  }
498
469
 
499
470
  std::shared_ptr<GPUSharedFence> GPUDevice::importSharedFence(
@@ -546,92 +517,6 @@ std::shared_ptr<GPUSharedFence> GPUDevice::importSharedFence(
546
517
  std::move(label));
547
518
  }
548
519
 
549
- std::shared_ptr<GPUNativeBufferTexture> GPUDevice::createNativeBufferTexture(
550
- std::shared_ptr<VideoFrame> source,
551
- std::optional<std::shared_ptr<GPUNativeBufferTextureDescriptor>>
552
- descriptor) {
553
- static constexpr const char *kCaller = "GPUDevice::createNativeBufferTexture";
554
- if (!source) {
555
- throw std::runtime_error("GPUDevice::createNativeBufferTexture(): "
556
- "source (NativeVideoFrame) is required");
557
- }
558
- std::string label;
559
- std::optional<double> usage;
560
- if (descriptor.has_value() && *descriptor) {
561
- label = (*descriptor)->label.value_or("");
562
- usage = (*descriptor)->usage;
563
- }
564
- auto memory =
565
- native_frame::importMemory(_instance, source->handle(), label, kCaller);
566
- wgpu::Texture texture;
567
- if (usage.has_value()) {
568
- // Dawn's layer describes the texture from the memory's properties, with
569
- // the caller's usage. An unsupported usage is a validation error and an
570
- // error texture, as with createTexture().
571
- wgpu::SharedTextureMemoryProperties properties{};
572
- (void)memory.GetProperties(&properties);
573
- wgpu::TextureDescriptor desc{};
574
- if (!label.empty()) {
575
- desc.label = wgpu::StringView(label.c_str(), label.size());
576
- }
577
- desc.usage = static_cast<wgpu::TextureUsage>(static_cast<uint64_t>(*usage));
578
- desc.dimension = wgpu::TextureDimension::e2D;
579
- desc.size = properties.size;
580
- desc.format = properties.format;
581
- desc.mipLevelCount = 1;
582
- desc.sampleCount = 1;
583
- texture = memory.CreateTexture(&desc);
584
- } else {
585
- texture = memory.CreateTexture();
586
- }
587
- if (texture == nullptr) {
588
- throw std::runtime_error("GPUDevice::createNativeBufferTexture(): "
589
- "CreateTexture returned null");
590
- }
591
- auto wrapped = std::make_shared<GPUTexture>(std::move(texture), label);
592
- return std::make_shared<GPUNativeBufferTexture>(
593
- _instance, std::move(memory), std::move(wrapped), std::move(source),
594
- std::move(label));
595
- }
596
-
597
- std::shared_ptr<GPUNativeBufferExternalTexture>
598
- GPUDevice::createNativeBufferExternalTexture(
599
- std::shared_ptr<VideoFrame> source,
600
- std::optional<std::shared_ptr<GPUExternalTextureDescriptor>> descriptor) {
601
- static constexpr const char *kCaller =
602
- "GPUDevice::createNativeBufferExternalTexture";
603
- if (!source) {
604
- throw std::runtime_error(
605
- "GPUDevice::createNativeBufferExternalTexture(): source "
606
- "(NativeVideoFrame) is required");
607
- }
608
- std::shared_ptr<GPUExternalTextureDescriptor> options =
609
- descriptor.has_value() && *descriptor
610
- ? *descriptor
611
- : std::make_shared<GPUExternalTextureDescriptor>();
612
- const auto &frame = source->handle();
613
- std::string label = options->label.value_or("external-texture");
614
- // The import, the texture and the external texture, once per buffer. No
615
- // access begins here: the wrapper's beginAccess() / endAccess() bracket
616
- // each use.
617
- auto memory = native_frame::importMemory(_instance, frame, label, kCaller);
618
- auto texture = memory.CreateTexture();
619
- if (texture == nullptr) {
620
- throw std::runtime_error(
621
- "GPUDevice::createNativeBufferExternalTexture(): CreateTexture "
622
- "returned null");
623
- }
624
- auto external = native_frame::createExternalTexture(
625
- _instance, memory, texture, frame, *options, label, kCaller);
626
- // Non-owning: the wrapper owns the import (see GPUExternalTexture's
627
- // constructor).
628
- auto externalTexture = std::make_shared<GPUExternalTexture>(
629
- std::move(external), nullptr, nullptr, nullptr, label);
630
- return std::make_shared<GPUNativeBufferExternalTexture>(
631
- _instance, std::move(memory), std::move(texture),
632
- std::move(externalTexture), std::move(source), std::move(label));
633
- }
634
-
635
520
  async::AsyncTaskHandle GPUDevice::createComputePipelineAsync(
636
521
  jsi::Runtime &runtime,
637
522
  std::shared_ptr<GPUComputePipelineDescriptor> descriptor) {