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,233 @@
1
+ #pragma once
2
+
3
+ #include <atomic>
4
+ #include <condition_variable>
5
+ #include <cstdint>
6
+ #include <functional>
7
+ #include <map>
8
+ #include <memory>
9
+ #include <mutex>
10
+ #include <utility>
11
+ #include <vector>
12
+
13
+ #include <jsi/jsi.h>
14
+
15
+ namespace rnwgpu {
16
+
17
+ namespace jsi = facebook::jsi;
18
+
19
+ /**
20
+ * The display's frames, from the platform: an AChoreographer on a looper
21
+ * thread of its own (Android), a CADisplayLink on a run loop thread of its own
22
+ * (iOS). One-shot like requestAnimationFrame: requestFrame() has the frame
23
+ * callback called once, at the next frame of the display, on the source's
24
+ * thread. Requests made before that frame are coalesced.
25
+ */
26
+ class AnimationFrameSource {
27
+ public:
28
+ // The time of the frame (when the frame of the display started), in
29
+ // nanoseconds of std::chrono::steady_clock.
30
+ using FrameCallback = std::function<void(int64_t frameTimeNanos)>;
31
+
32
+ virtual ~AnimationFrameSource() = default;
33
+
34
+ // Set once, before the first requestFrame().
35
+ void setFrameCallback(FrameCallback callback) {
36
+ _frameCallback = std::move(callback);
37
+ }
38
+
39
+ // Any thread.
40
+ virtual void requestFrame() = 0;
41
+
42
+ protected:
43
+ void deliverFrame(int64_t frameTimeNanos) {
44
+ if (_frameCallback) {
45
+ _frameCallback(frameTimeNanos);
46
+ }
47
+ }
48
+
49
+ private:
50
+ FrameCallback _frameCallback;
51
+ };
52
+
53
+ class RuntimeAnimationFrames;
54
+
55
+ /**
56
+ * requestAnimationFrame for every runtime WebGPU renders from, paced by the
57
+ * display rather than by React Native's timers. See AnimationFrames.cpp for
58
+ * how each kind of runtime is reached, and src/animationFrame.ts for the API.
59
+ *
60
+ * Process-wide: the animation frame source is the platform's and outlives a
61
+ * reload. The per-runtime state (RuntimeAnimationFrames) lives in the
62
+ * runtime's runtimeData, and the dispatcher only holds weak references to it.
63
+ */
64
+ class AnimationFrameDispatcher {
65
+ public:
66
+ struct AnimationFrame {
67
+ uint64_t id = 0;
68
+ int64_t timeNanos = 0;
69
+ };
70
+
71
+ static AnimationFrameDispatcher &shared();
72
+
73
+ // Installed by the platform on install (RNWebGPUManager); without one,
74
+ // every runtime falls back to its own global requestAnimationFrame.
75
+ void setSource(std::shared_ptr<AnimationFrameSource> source);
76
+ bool hasSource();
77
+
78
+ // Whether the app is in the foreground: the host activity is resumed
79
+ // (Android), the app is active (iOS). While it is not, the source is asked
80
+ // for no frame, and what waits for one gets the first frame after the app
81
+ // is back: a render loop stops with the app. Set by the platform, as
82
+ // neither source stops on its own; true where the platform says nothing.
83
+ // Any thread.
84
+ void setForeground(bool foreground);
85
+
86
+ // The latest frame of the display that started.
87
+ AnimationFrame latestFrame();
88
+
89
+ // The latest frame, when the caller is still within it (it started less
90
+ // than a frame interval ago) and it is newer than `after`.
91
+ bool currentFrameAfter(uint64_t after, AnimationFrame &frame);
92
+
93
+ // Has `frames` delivered the next frame, with the request it answers
94
+ // (RuntimeAnimationFrames::deliver, on the source's thread). Any thread.
95
+ void requestDelivery(const std::shared_ptr<RuntimeAnimationFrames> &frames,
96
+ uint64_t request);
97
+
98
+ // Blocks until a frame newer than `after` starts, or `timeoutNanos` passes.
99
+ // Returns false on timeout (the display sends no frames: the app is in the
100
+ // background, say). The frame the caller is still within counts.
101
+ bool waitForFrameAfter(uint64_t after, int64_t timeoutNanos,
102
+ AnimationFrame &frame);
103
+
104
+ static int64_t nowNanos();
105
+
106
+ private:
107
+ AnimationFrameDispatcher() = default;
108
+
109
+ // A runtime that waits for the next frame, and the request it waits with.
110
+ struct Delivery {
111
+ std::weak_ptr<RuntimeAnimationFrames> frames;
112
+ uint64_t request;
113
+ };
114
+
115
+ void onFrame(int64_t frameTimeNanos);
116
+ // Called with _mutex held.
117
+ void requestFrameLocked();
118
+
119
+ std::mutex _mutex;
120
+ std::condition_variable _frameStarted;
121
+ std::shared_ptr<AnimationFrameSource> _source;
122
+ AnimationFrame _latest;
123
+ // The display's frame interval, from consecutive frames: 60 Hz until known.
124
+ int64_t _intervalNanos = 16'666'667;
125
+ bool _frameRequested = false;
126
+ bool _foreground = true;
127
+ // Frames delivered with nothing waiting: the source keeps ticking a few
128
+ // frames after the last request, so a loop that overruns a frame finds the
129
+ // frame it overran into (see currentFrameAfter) rather than waiting for the
130
+ // one after.
131
+ int _idleFrames = 0;
132
+ int _waiters = 0;
133
+ std::vector<Delivery> _pending;
134
+ };
135
+
136
+ /**
137
+ * The animation frame callbacks of one runtime. Owned by the runtime (its
138
+ * runtimeData); the callbacks are only touched on the runtime's thread, and
139
+ * go when the runtime lets go of this (see releaseCallbacks), whoever holds
140
+ * the last reference.
141
+ */
142
+ class RuntimeAnimationFrames
143
+ : public std::enable_shared_from_this<RuntimeAnimationFrames> {
144
+ public:
145
+ enum class Kind {
146
+ // The React Native runtime: frames are posted through its CallInvoker.
147
+ Main,
148
+ // A worklet runtime of the app (createWorkletRuntime, a frame processor):
149
+ // its setTimeout wakes it, and it waits for the frame on its thread.
150
+ Waiting,
151
+ // The runtime's own requestAnimationFrame paces it: the Reanimated UI
152
+ // runtime (worklets' is paced by the display already), and any runtime
153
+ // when no animation frame source is installed.
154
+ Delegated,
155
+ };
156
+
157
+ RuntimeAnimationFrames(jsi::Runtime &runtime, Kind kind);
158
+
159
+ static std::shared_ptr<RuntimeAnimationFrames>
160
+ forRuntime(jsi::Runtime &runtime);
161
+
162
+ // Runtime thread.
163
+ double request(jsi::Runtime &runtime, jsi::Function callback);
164
+ void cancel(double handle);
165
+
166
+ // The source's thread: the frame asked for with requestDelivery started.
167
+ void deliver(const AnimationFrameDispatcher::AnimationFrame &frame,
168
+ uint64_t request);
169
+
170
+ // The runtime is going away, and releases its runtimeData: the callbacks,
171
+ // which are values of the runtime, go now, while it is still there. The
172
+ // dispatcher's thread may hold the last reference to this, and outlive the
173
+ // runtime with it.
174
+ void releaseCallbacks();
175
+
176
+ private:
177
+ // How a run of the callbacks comes about, on the main runtime.
178
+ enum class Run {
179
+ // None yet.
180
+ kNone,
181
+ // On an animation frame: posted as the frame started, while no run was
182
+ // going on. It goes ahead of what waits on the runtime, like React
183
+ // Native's timers.
184
+ kOnFrame,
185
+ // In a frame that had started already: the one a loop overran into. It
186
+ // goes behind what waits on the runtime, and only after a run on an
187
+ // animation frame, so that two in a row at most are back to back.
188
+ kInFrame,
189
+ };
190
+
191
+ void schedule(jsi::Runtime &runtime);
192
+ // Posts the run of `request` in `frame` to the main runtime. Any thread.
193
+ void post(const AnimationFrameDispatcher::AnimationFrame &frame,
194
+ uint64_t request, Run run);
195
+ void scheduleDelegated(jsi::Runtime &runtime);
196
+ void scheduleWaiting(jsi::Runtime &runtime, double delayMs);
197
+ void flush(jsi::Runtime &runtime, uint64_t frameId, double timestampMs);
198
+ static double timestampOf(jsi::Runtime &runtime, int64_t frameTimeNanos);
199
+
200
+ jsi::Runtime &_runtime;
201
+ const Kind _kind;
202
+ // Runtime thread only.
203
+ std::map<double, std::shared_ptr<jsi::Function>> _callbacks;
204
+ std::map<double, std::shared_ptr<jsi::Function>> *_flushing = nullptr;
205
+ double _nextHandle = 1;
206
+ bool _scheduled = false;
207
+ uint64_t _requests = 0;
208
+ // The main runtime, read on the source's thread too (see deliver). What the
209
+ // callbacks wait on: a number per schedule(), 0 once they ran. A run posted
210
+ // for another request finds it answered, and does nothing.
211
+ std::atomic<uint64_t> _request{0};
212
+ // The request a run in its frame was posted for: one each.
213
+ std::atomic<uint64_t> _inFrameRequest{0};
214
+ // Whether the callbacks are running, and how the latest run came about.
215
+ std::atomic<bool> _running{false};
216
+ std::atomic<Run> _lastRun{Run::kNone};
217
+ // The last frame run here.
218
+ std::atomic<uint64_t> _lastFrameId{0};
219
+ };
220
+
221
+ /**
222
+ * The JS face of the above, installed on the main runtime as
223
+ * `__webgpuAnimationFrames` and handed to other runtimes by reference (a
224
+ * HostObject, like WebGPUWorkletHelpers): request(callback) and
225
+ * cancel(handle) act on the runtime that calls them.
226
+ */
227
+ class AnimationFramesHostObject : public jsi::HostObject {
228
+ public:
229
+ jsi::Value get(jsi::Runtime &runtime, const jsi::PropNameID &name) override;
230
+ std::vector<jsi::PropNameID> getPropertyNames(jsi::Runtime &runtime) override;
231
+ };
232
+
233
+ } // namespace rnwgpu
@@ -11,4 +11,20 @@ enum class CanvasColorSpace { SRGB, DisplayP3 };
11
11
  // ("standard", the default) or reach its extended range ("extended").
12
12
  enum class CanvasToneMappingMode { Standard, Extended };
13
13
 
14
+ // What a canvas's layer is tagged with on Apple platforms: the colorSpace and
15
+ // toneMapping props of the Canvas, read when it mounts (see
16
+ // apple/MetalLayerColorSpace.h).
17
+ struct CanvasLayerColorSpace {
18
+ CanvasColorSpace colorSpace = CanvasColorSpace::SRGB;
19
+ CanvasToneMappingMode toneMappingMode = CanvasToneMappingMode::Standard;
20
+
21
+ bool operator==(const CanvasLayerColorSpace &other) const {
22
+ return colorSpace == other.colorSpace &&
23
+ toneMappingMode == other.toneMappingMode;
24
+ }
25
+ bool operator!=(const CanvasLayerColorSpace &other) const {
26
+ return !(*this == other);
27
+ }
28
+ };
29
+
14
30
  } // namespace rnwgpu
@@ -0,0 +1,396 @@
1
+ #include "NativeBufferViewRegistry.h"
2
+
3
+ #include <cerrno>
4
+ #include <condition_variable>
5
+ #include <deque>
6
+ #include <memory>
7
+ #include <stdexcept>
8
+ #include <string>
9
+ #include <thread>
10
+ #include <unordered_map>
11
+ #include <utility>
12
+ #include <vector>
13
+
14
+ #if defined(__ANDROID__)
15
+ #include <android/hardware_buffer.h>
16
+ #include <android/log.h>
17
+ #include <poll.h>
18
+ #include <unistd.h>
19
+ #elif defined(__APPLE__)
20
+ #include <CoreFoundation/CoreFoundation.h>
21
+ #include <CoreVideo/CoreVideo.h>
22
+ #include <IOSurface/IOSurfaceRef.h>
23
+ #endif
24
+
25
+ namespace rnwgpu {
26
+
27
+ namespace {
28
+
29
+ constexpr const char *kCaller = "presentNativeBuffer";
30
+
31
+ [[noreturn]] void fail(const std::string &message) {
32
+ throw std::runtime_error(std::string(kCaller) + "(): " + message);
33
+ }
34
+
35
+ } // namespace
36
+
37
+ // --- NativeBufferContent ----------------------------------------------------
38
+
39
+ std::shared_ptr<NativeBufferContent>
40
+ NativeBufferContent::fromFrame(const VideoFrameHandle &frame) {
41
+ if (frame.handle == nullptr) {
42
+ fail("the frame has been released");
43
+ }
44
+ if (frame.pixelFormat == VideoPixelFormat::NV12) {
45
+ fail("a YUV frame can't be displayed as it is; draw it into an RGBA "
46
+ "buffer (createNativeBuffer) first");
47
+ }
48
+ #if defined(__ANDROID__)
49
+ AHardwareBuffer_Desc desc{};
50
+ AHardwareBuffer_describe(static_cast<AHardwareBuffer *>(frame.handle), &desc);
51
+ switch (desc.format) {
52
+ case AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM:
53
+ case AHARDWAREBUFFER_FORMAT_R8G8B8X8_UNORM:
54
+ case AHARDWAREBUFFER_FORMAT_R16G16B16A16_FLOAT:
55
+ break;
56
+ default:
57
+ fail("unsupported AHardwareBuffer format " + std::to_string(desc.format) +
58
+ " (expected R8G8B8A8_UNORM, R8G8B8X8_UNORM or R16G16B16A16_FLOAT)");
59
+ }
60
+ if (desc.layers != 1) {
61
+ fail("the AHardwareBuffer has " + std::to_string(desc.layers) +
62
+ " layers; only single-layer buffers can be displayed");
63
+ }
64
+ #elif defined(__APPLE__)
65
+ const OSType format =
66
+ IOSurfaceGetPixelFormat(static_cast<IOSurfaceRef>(frame.handle));
67
+ if (format != kCVPixelFormatType_32BGRA &&
68
+ format != kCVPixelFormatType_64RGBAHalf) {
69
+ fail("unsupported IOSurface pixel format (expected 'BGRA' or 'RGhA', "
70
+ "that is bgra8unorm or rgba16float)");
71
+ }
72
+ #endif
73
+ const auto colorSpace =
74
+ frame.colorSpace.primaries == wgpu::ColorSpacePrimariesDawn::DisplayP3
75
+ ? NativeBufferColorSpace::DisplayP3
76
+ : NativeBufferColorSpace::SRGB;
77
+ return std::shared_ptr<NativeBufferContent>(new NativeBufferContent(
78
+ frame.handle, frame.width, frame.height, colorSpace));
79
+ }
80
+
81
+ NativeBufferContent::NativeBufferContent(void *buffer, uint32_t width,
82
+ uint32_t height,
83
+ NativeBufferColorSpace colorSpace)
84
+ : _buffer(buffer), _width(width), _height(height), _colorSpace(colorSpace) {
85
+ #if defined(__ANDROID__)
86
+ AHardwareBuffer_acquire(static_cast<AHardwareBuffer *>(_buffer));
87
+ #elif defined(__APPLE__)
88
+ CFRetain(_buffer);
89
+ #endif
90
+ }
91
+
92
+ NativeBufferContent::~NativeBufferContent() {
93
+ #if defined(__ANDROID__)
94
+ AHardwareBuffer_release(static_cast<AHardwareBuffer *>(_buffer));
95
+ #elif defined(__APPLE__)
96
+ CFRelease(_buffer);
97
+ #endif
98
+ }
99
+
100
+ // --- Fence wait (Android; Apple platforms: NativeBufferFenceWait.mm) ---------
101
+
102
+ #if defined(__ANDROID__)
103
+
104
+ namespace {
105
+
106
+ #define NBV_LOG_TAG "WebGPUNativeBufferView"
107
+
108
+ // One thread for every NativeBufferView, started on first use and kept for
109
+ // the life of the process. Presents are occasional, and their fences signal
110
+ // in submission order, so a single FIFO is enough.
111
+ class FenceWaiter {
112
+ public:
113
+ static FenceWaiter &shared() {
114
+ // Leaked on purpose: the detached thread may still be waiting at exit.
115
+ static FenceWaiter *waiter = new FenceWaiter();
116
+ return *waiter;
117
+ }
118
+
119
+ // Waits for `fenceFd` (borrowed from `fence`, -1 for none) and `ownedFd`
120
+ // (closed after the wait, -1 for none).
121
+ void enqueue(wgpu::SharedFence fence, int fenceFd, int ownedFd,
122
+ std::function<void(bool)> done) {
123
+ std::lock_guard<std::mutex> lock(_mutex);
124
+ _jobs.push_back({std::move(fence), fenceFd, ownedFd, std::move(done)});
125
+ if (!_started) {
126
+ _started = true;
127
+ std::thread([this]() { run(); }).detach();
128
+ }
129
+ _cv.notify_one();
130
+ }
131
+
132
+ private:
133
+ struct Job {
134
+ // Owns `fenceFd`: Dawn's export is borrowed and closed with the fence.
135
+ wgpu::SharedFence fence;
136
+ int fenceFd;
137
+ int ownedFd;
138
+ std::function<void(bool)> done;
139
+ };
140
+
141
+ // A fence that has not signaled after this long belongs to work that will
142
+ // never finish (a lost device): the buffer is dropped.
143
+ static constexpr int kTimeoutMs = 10000;
144
+
145
+ void run() {
146
+ for (;;) {
147
+ Job job;
148
+ {
149
+ std::unique_lock<std::mutex> lock(_mutex);
150
+ _cv.wait(lock, [this]() { return !_jobs.empty(); });
151
+ job = std::move(_jobs.front());
152
+ _jobs.pop_front();
153
+ }
154
+ bool signaled = job.fenceFd < 0 || waitFd(job.fenceFd);
155
+ if (job.ownedFd >= 0) {
156
+ signaled = signaled && waitFd(job.ownedFd);
157
+ ::close(job.ownedFd);
158
+ }
159
+ if (!signaled) {
160
+ __android_log_print(ANDROID_LOG_WARN, NBV_LOG_TAG,
161
+ "the fence of a presented buffer did not signal; "
162
+ "the buffer is dropped");
163
+ }
164
+ job.done(signaled);
165
+ // The fence (and its fd) is released here, after the wait.
166
+ }
167
+ }
168
+
169
+ // Sync fds turn readable (POLLIN) once signaled. poll() keeps this to libc,
170
+ // with no libsync dependency.
171
+ static bool waitFd(int fd) {
172
+ struct pollfd pfd = {fd, POLLIN, 0};
173
+ for (;;) {
174
+ const int result = ::poll(&pfd, 1, kTimeoutMs);
175
+ if (result > 0) {
176
+ return (pfd.revents & (POLLERR | POLLNVAL)) == 0;
177
+ }
178
+ if (result < 0 && errno == EINTR) {
179
+ continue;
180
+ }
181
+ return false;
182
+ }
183
+ }
184
+
185
+ std::mutex _mutex;
186
+ std::condition_variable _cv;
187
+ std::deque<Job> _jobs;
188
+ bool _started = false;
189
+ };
190
+
191
+ } // namespace
192
+
193
+ namespace {
194
+
195
+ // Waits for `fence` (if any) and `ownedFd` (if >= 0, closed afterwards).
196
+ void waitForFences(wgpu::SharedFence fence, int ownedFd,
197
+ std::function<void(bool)> done) {
198
+ int fenceFd = -1;
199
+ if (fence) {
200
+ // Exported on the calling thread, where the device is in use anyway.
201
+ wgpu::SharedFenceExportInfo info{};
202
+ wgpu::SharedFenceSyncFDExportInfo fdInfo{};
203
+ info.nextInChain = &fdInfo;
204
+ fence.ExportInfo(&info);
205
+ if (info.type != wgpu::SharedFenceType::SyncFD) {
206
+ __android_log_print(ANDROID_LOG_WARN, NBV_LOG_TAG,
207
+ "presentNativeBuffer: the fence is not a sync fd; "
208
+ "the buffer is dropped");
209
+ if (ownedFd >= 0) {
210
+ ::close(ownedFd);
211
+ }
212
+ done(false);
213
+ return;
214
+ }
215
+ // -1 is a fence that has already signaled.
216
+ fenceFd = fdInfo.handle;
217
+ }
218
+ if (fenceFd < 0 && ownedFd < 0) {
219
+ done(true);
220
+ return;
221
+ }
222
+ FenceWaiter::shared().enqueue(std::move(fence), fenceFd, ownedFd,
223
+ std::move(done));
224
+ }
225
+
226
+ } // namespace
227
+
228
+ void waitForSharedFence(wgpu::SharedFence fence, uint64_t /* signaledValue */,
229
+ std::function<void(bool)> done) {
230
+ waitForFences(std::move(fence), -1, std::move(done));
231
+ }
232
+
233
+ #endif // __ANDROID__
234
+
235
+ // --- NativeBufferViewRegistry ------------------------------------------------
236
+
237
+ void NativeBufferViewRegistry::present(
238
+ int viewId, std::shared_ptr<NativeBufferContent> content,
239
+ wgpu::SharedFence fence, uint64_t signaledValue, int acquireFenceFd) {
240
+ uint64_t sequence = 0;
241
+ {
242
+ std::lock_guard<std::mutex> lock(_mutex);
243
+ auto it = _entries.find(viewId);
244
+ if (it != _entries.end() && it->second.ownedByJS) {
245
+ sequence = ++it->second.presentedSequence;
246
+ }
247
+ }
248
+ if (sequence == 0) {
249
+ // Released by JS (a present that lands after unmount), or an id that
250
+ // was never retained.
251
+ #if defined(__ANDROID__)
252
+ if (acquireFenceFd >= 0) {
253
+ ::close(acquireFenceFd);
254
+ }
255
+ #endif
256
+ return;
257
+ }
258
+ auto onSignaled = [viewId, sequence,
259
+ content = std::move(content)](bool signaled) mutable {
260
+ if (signaled) {
261
+ NativeBufferViewRegistry::getInstance().deliver(viewId, sequence,
262
+ std::move(content));
263
+ }
264
+ };
265
+ #if defined(__ANDROID__)
266
+ // Sync fds have no value to wait for.
267
+ (void)signaledValue;
268
+ if (fence || acquireFenceFd >= 0) {
269
+ waitForFences(std::move(fence), acquireFenceFd, std::move(onSignaled));
270
+ return;
271
+ }
272
+ #else
273
+ (void)acquireFenceFd;
274
+ if (fence) {
275
+ waitForSharedFence(std::move(fence), signaledValue, std::move(onSignaled));
276
+ return;
277
+ }
278
+ #endif
279
+ onSignaled(true);
280
+ }
281
+
282
+ void NativeBufferViewRegistry::deliver(
283
+ int viewId, uint64_t sequence,
284
+ std::shared_ptr<NativeBufferContent> content) {
285
+ Listener listener;
286
+ {
287
+ std::lock_guard<std::mutex> lock(_mutex);
288
+ auto it = _entries.find(viewId);
289
+ // Gone (the view unmounted while the fence was pending), or superseded
290
+ // by a later present whose fence signaled first.
291
+ if (it == _entries.end() || sequence <= it->second.readySequence) {
292
+ return;
293
+ }
294
+ it->second.readySequence = sequence;
295
+ it->second.content = std::move(content);
296
+ listener = it->second.listener;
297
+ }
298
+ // Outside the lock: the listener may read the content back.
299
+ if (listener) {
300
+ listener();
301
+ }
302
+ }
303
+
304
+ std::shared_ptr<NativeBufferContent>
305
+ NativeBufferViewRegistry::content(int viewId, uint64_t *sequence) {
306
+ std::lock_guard<std::mutex> lock(_mutex);
307
+ auto it = _entries.find(viewId);
308
+ if (it == _entries.end()) {
309
+ *sequence = 0;
310
+ return nullptr;
311
+ }
312
+ *sequence = it->second.readySequence;
313
+ return it->second.content;
314
+ }
315
+
316
+ void NativeBufferViewRegistry::setListener(int viewId, Listener listener) {
317
+ if (viewId <= 0) {
318
+ return;
319
+ }
320
+ bool hasContent = false;
321
+ {
322
+ std::lock_guard<std::mutex> lock(_mutex);
323
+ // Created when the JS component already let go: detachView erases it.
324
+ auto &entry = _entries[viewId];
325
+ entry.listener = listener;
326
+ hasContent = entry.content != nullptr;
327
+ }
328
+ if (listener && hasContent) {
329
+ listener();
330
+ }
331
+ }
332
+
333
+ void NativeBufferViewRegistry::detachView(int viewId) {
334
+ std::shared_ptr<NativeBufferContent> released;
335
+ Listener listener;
336
+ {
337
+ std::lock_guard<std::mutex> lock(_mutex);
338
+ auto it = _entries.find(viewId);
339
+ if (it == _entries.end()) {
340
+ return;
341
+ }
342
+ listener = std::move(it->second.listener);
343
+ it->second.listener = nullptr;
344
+ eraseIfUnowned(it, &released);
345
+ }
346
+ // The buffer and the listener's captures are released outside the lock.
347
+ }
348
+
349
+ void NativeBufferViewRegistry::retainFromJS(int viewId) {
350
+ if (viewId <= 0) {
351
+ return;
352
+ }
353
+ std::lock_guard<std::mutex> lock(_mutex);
354
+ _entries[viewId].ownedByJS = true;
355
+ }
356
+
357
+ void NativeBufferViewRegistry::releaseFromJS(int viewId) {
358
+ std::shared_ptr<NativeBufferContent> released;
359
+ {
360
+ std::lock_guard<std::mutex> lock(_mutex);
361
+ auto it = _entries.find(viewId);
362
+ if (it == _entries.end()) {
363
+ return;
364
+ }
365
+ it->second.ownedByJS = false;
366
+ eraseIfUnowned(it, &released);
367
+ }
368
+ }
369
+
370
+ void NativeBufferViewRegistry::releaseAllFromJS() {
371
+ std::vector<std::shared_ptr<NativeBufferContent>> released;
372
+ {
373
+ std::lock_guard<std::mutex> lock(_mutex);
374
+ for (auto it = _entries.begin(); it != _entries.end();) {
375
+ it->second.ownedByJS = false;
376
+ if (it->second.listener) {
377
+ ++it;
378
+ } else {
379
+ released.push_back(std::move(it->second.content));
380
+ it = _entries.erase(it);
381
+ }
382
+ }
383
+ }
384
+ }
385
+
386
+ void NativeBufferViewRegistry::eraseIfUnowned(
387
+ std::unordered_map<int, Entry>::iterator it,
388
+ std::shared_ptr<NativeBufferContent> *released) {
389
+ if (it->second.ownedByJS || it->second.listener) {
390
+ return;
391
+ }
392
+ *released = std::move(it->second.content);
393
+ _entries.erase(it);
394
+ }
395
+
396
+ } // namespace rnwgpu