react-native-webgpu 0.22.0 → 0.24.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 (165) hide show
  1. package/Package.swift +18 -129
  2. package/README.md +15 -2
  3. package/android/CMakeLists.txt +2 -1
  4. package/android/cpp/AndroidAnimationFrameSource.h +136 -0
  5. package/android/cpp/AndroidPlatformContext.h +65 -9
  6. package/android/cpp/cpp-adapter.cpp +148 -2
  7. package/android/src/main/java/com/webgpu/WebGPUModule.java +24 -7
  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 +2 -2
  12. package/android/src/main/java/com/webgpu/WebGPUView.java +19 -3
  13. package/android/src/main/java/com/webgpu/WebGPUViewPackage.java +2 -2
  14. package/android/src/newarch/com/webgpu/WebGPUNativeBufferViewManagerSpec.java +24 -0
  15. package/apple/AppleAnimationFrameSource.mm +208 -0
  16. package/apple/ApplePlatformContext.h +8 -1
  17. package/apple/ApplePlatformContext.mm +75 -2
  18. package/apple/NativeBufferFenceWait.mm +88 -0
  19. package/apple/WebGPUNativeBufferView.h +15 -0
  20. package/apple/WebGPUNativeBufferView.mm +200 -0
  21. package/binaries.json +53 -105
  22. package/cpp/dawn/common/ExternalTextureParams.h +3 -3
  23. package/cpp/dawn/include/dawn/dawn_proc.h +53 -0
  24. package/cpp/dawn/include/dawn/dawn_proc_table.h +329 -0
  25. package/cpp/dawn/include/dawn/dawn_thread_dispatch_proc.h +47 -0
  26. package/cpp/dawn/include/dawn/dawn_version.h +51 -0
  27. package/cpp/dawn/include/dawn/native/D3D11Backend.h +65 -0
  28. package/cpp/dawn/include/dawn/native/D3D12Backend.h +104 -0
  29. package/cpp/dawn/include/dawn/native/D3DBackend.h +56 -0
  30. package/cpp/dawn/include/dawn/native/DawnNative.h +375 -0
  31. package/cpp/dawn/include/dawn/native/MetalBackend.h +67 -0
  32. package/cpp/dawn/include/dawn/native/NullBackend.h +39 -0
  33. package/cpp/dawn/include/dawn/native/OpenGLBackend.h +89 -0
  34. package/cpp/dawn/include/dawn/native/VulkanBackend.h +199 -0
  35. package/cpp/dawn/include/dawn/native/WebGPUBackend.h +49 -0
  36. package/cpp/dawn/include/dawn/native/dawn_native_export.h +49 -0
  37. package/cpp/dawn/include/dawn/platform/DawnPlatform.h +210 -0
  38. package/cpp/dawn/include/dawn/platform/dawn_platform_export.h +49 -0
  39. package/cpp/dawn/include/dawn/replay/Replay.h +99 -0
  40. package/cpp/dawn/include/dawn/replay/dawn_replay_export.h +49 -0
  41. package/cpp/dawn/include/dawn/webgpu.h +5119 -0
  42. package/cpp/dawn/include/dawn/webgpu_cpp.h +10506 -0
  43. package/cpp/dawn/include/dawn/webgpu_cpp_print.h +2897 -0
  44. package/cpp/dawn/include/webgpu/webgpu.h +33 -0
  45. package/cpp/dawn/include/webgpu/webgpu_cpp.h +33 -0
  46. package/cpp/dawn/include/webgpu/webgpu_cpp_chained_struct.h +57 -0
  47. package/cpp/dawn/include/webgpu/webgpu_cpp_print.h +33 -0
  48. package/cpp/dawn/include/webgpu/webgpu_enum_class_bitmasks.h +163 -0
  49. package/cpp/dawn/include/webgpu/webgpu_glfw.h +88 -0
  50. package/cpp/rnwgpu/AnimationFrames.cpp +576 -0
  51. package/cpp/rnwgpu/AnimationFrames.h +233 -0
  52. package/cpp/rnwgpu/NativeBufferViewRegistry.cpp +396 -0
  53. package/cpp/rnwgpu/NativeBufferViewRegistry.h +163 -0
  54. package/cpp/rnwgpu/PlatformContext.h +21 -1
  55. package/cpp/rnwgpu/RNWebGPUManager.cpp +17 -4
  56. package/cpp/rnwgpu/SurfaceRegistry.h +2 -2
  57. package/cpp/rnwgpu/api/GPUAdapter.cpp +2 -2
  58. package/cpp/rnwgpu/api/GPUDevice.cpp +16 -131
  59. package/cpp/rnwgpu/api/GPUDevice.h +0 -18
  60. package/cpp/rnwgpu/api/GPUExternalTexture.cpp +35 -3
  61. package/cpp/rnwgpu/api/GPUExternalTexture.h +4 -4
  62. package/cpp/rnwgpu/api/GPUQueue.cpp +1 -1
  63. package/cpp/rnwgpu/api/GPUQueue.h +1 -1
  64. package/cpp/rnwgpu/api/GPUSharedFence.h +1 -0
  65. package/cpp/rnwgpu/api/GPUSharedTextureMemory.cpp +11 -5
  66. package/cpp/rnwgpu/api/GPUSharedTextureMemory.h +21 -2
  67. package/cpp/rnwgpu/api/GPUTexture.h +18 -0
  68. package/cpp/rnwgpu/api/NativeFrameFeatures.h +1 -1
  69. package/cpp/rnwgpu/api/NativeFrameImport.cpp +20 -17
  70. package/cpp/rnwgpu/api/NativeFrameImport.h +31 -20
  71. package/cpp/rnwgpu/api/RNWebGPU.h +206 -7
  72. package/cpp/rnwgpu/api/VideoFrame.h +5 -4
  73. package/cpp/rnwgpu/api/VideoFrameBlit.h +2 -2
  74. package/cpp/rnwgpu/api/descriptors/GPUExternalTextureDescriptor.h +21 -14
  75. package/cpp/rnwgpu/api/descriptors/GPUImageCopyExternalImage.h +1 -1
  76. package/cpp/rnwgpu/api/descriptors/GPUSharedTextureMemoryDescriptor.h +17 -9
  77. package/cpp/rnwgpu/async/RuntimeContext.cpp +21 -4
  78. package/cpp/rnwgpu/async/RuntimeContext.h +8 -0
  79. package/lib/commonjs/NativeBufferView.js +131 -0
  80. package/lib/commonjs/NativeBufferView.js.map +1 -0
  81. package/lib/commonjs/NativeBufferViewNativeComponent.js +10 -0
  82. package/lib/commonjs/NativeBufferViewNativeComponent.js.map +1 -0
  83. package/lib/commonjs/animationFrame.js +91 -0
  84. package/lib/commonjs/animationFrame.js.map +1 -0
  85. package/lib/commonjs/index.js +16 -1
  86. package/lib/commonjs/index.js.map +1 -1
  87. package/lib/commonjs/main/index.js +12 -0
  88. package/lib/commonjs/main/index.js.map +1 -1
  89. package/lib/commonjs/mock.js +30 -1
  90. package/lib/commonjs/mock.js.map +1 -1
  91. package/lib/commonjs/video.js +21 -7
  92. package/lib/commonjs/video.js.map +1 -1
  93. package/lib/module/NativeBufferView.js +122 -0
  94. package/lib/module/NativeBufferView.js.map +1 -0
  95. package/lib/module/NativeBufferViewNativeComponent.js +4 -0
  96. package/lib/module/NativeBufferViewNativeComponent.js.map +1 -0
  97. package/lib/module/animationFrame.js +83 -0
  98. package/lib/module/animationFrame.js.map +1 -0
  99. package/lib/module/index.js +1 -0
  100. package/lib/module/index.js.map +1 -1
  101. package/lib/module/main/index.js +1 -0
  102. package/lib/module/main/index.js.map +1 -1
  103. package/lib/module/mock.js +21 -0
  104. package/lib/module/mock.js.map +1 -1
  105. package/lib/module/video.js +17 -4
  106. package/lib/module/video.js.map +1 -1
  107. package/lib/typescript/lib/commonjs/NativeBufferView.d.ts +48 -0
  108. package/lib/typescript/lib/commonjs/NativeBufferView.d.ts.map +1 -0
  109. package/lib/typescript/lib/commonjs/NativeBufferViewNativeComponent.d.ts +5 -0
  110. package/lib/typescript/lib/commonjs/NativeBufferViewNativeComponent.d.ts.map +1 -0
  111. package/lib/typescript/lib/commonjs/animationFrame.d.ts +54 -0
  112. package/lib/typescript/lib/commonjs/animationFrame.d.ts.map +1 -0
  113. package/lib/typescript/lib/commonjs/index.d.ts +2 -0
  114. package/lib/typescript/lib/commonjs/mock.d.ts +12 -0
  115. package/lib/typescript/lib/commonjs/mock.d.ts.map +1 -1
  116. package/lib/typescript/lib/commonjs/video.d.ts +9 -4
  117. package/lib/typescript/lib/commonjs/video.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/animationFrame.d.ts +3 -0
  123. package/lib/typescript/lib/module/animationFrame.d.ts.map +1 -0
  124. package/lib/typescript/lib/module/index.d.ts +1 -0
  125. package/lib/typescript/lib/module/main/index.d.ts +1 -0
  126. package/lib/typescript/lib/module/mock.d.ts +14 -0
  127. package/lib/typescript/lib/module/mock.d.ts.map +1 -1
  128. package/lib/typescript/lib/module/video.d.ts +4 -3
  129. package/lib/typescript/lib/module/video.d.ts.map +1 -1
  130. package/lib/typescript/react-native.config.d.ts +1 -0
  131. package/lib/typescript/src/NativeBufferView.d.ts +99 -0
  132. package/lib/typescript/src/NativeBufferView.d.ts.map +1 -0
  133. package/lib/typescript/src/NativeBufferViewNativeComponent.d.ts +13 -0
  134. package/lib/typescript/src/NativeBufferViewNativeComponent.d.ts.map +1 -0
  135. package/lib/typescript/src/animationFrame.d.ts +59 -0
  136. package/lib/typescript/src/animationFrame.d.ts.map +1 -0
  137. package/lib/typescript/src/index.d.ts +18 -8
  138. package/lib/typescript/src/index.d.ts.map +1 -1
  139. package/lib/typescript/src/main/index.d.ts +1 -0
  140. package/lib/typescript/src/main/index.d.ts.map +1 -1
  141. package/lib/typescript/src/mock.d.ts +11 -0
  142. package/lib/typescript/src/mock.d.ts.map +1 -1
  143. package/lib/typescript/src/types.d.ts +33 -32
  144. package/lib/typescript/src/types.d.ts.map +1 -1
  145. package/lib/typescript/src/video.d.ts +18 -6
  146. package/lib/typescript/src/video.d.ts.map +1 -1
  147. package/package.json +16 -6
  148. package/react-native-webgpu.podspec +47 -79
  149. package/react-native.config.js +9 -6
  150. package/scripts/apple-binaries-utils.sh +280 -0
  151. package/scripts/prepare-apple-binaries.sh +309 -0
  152. package/scripts/spm-plugin.js +130 -0
  153. package/src/NativeBufferView.tsx +199 -0
  154. package/src/NativeBufferViewNativeComponent.ts +20 -0
  155. package/src/animationFrame.ts +82 -0
  156. package/src/index.tsx +48 -42
  157. package/src/main/index.tsx +1 -0
  158. package/src/mock.ts +35 -0
  159. package/src/types.ts +62 -88
  160. package/src/video.ts +32 -12
  161. package/cpp/rnwgpu/api/GPUNativeBufferExternalTexture.h +0 -60
  162. package/cpp/rnwgpu/api/GPUNativeBufferTexture.h +0 -52
  163. package/cpp/rnwgpu/api/GPUNativeBufferWrapper.cpp +0 -144
  164. package/cpp/rnwgpu/api/GPUNativeBufferWrapper.h +0 -143
  165. package/cpp/rnwgpu/api/descriptors/GPUNativeBufferTextureDescriptor.h +0 -55
@@ -0,0 +1,576 @@
1
+ #include "AnimationFrames.h"
2
+
3
+ #include <chrono>
4
+ #include <exception>
5
+ #include <map>
6
+ #include <memory>
7
+ #include <string>
8
+ #include <utility>
9
+ #include <vector>
10
+
11
+ #include <ReactCommon/CallInvoker.h>
12
+
13
+ #include "rnwgpu/async/RuntimeContext.h"
14
+
15
+ /**
16
+ * How a frame reaches each kind of runtime.
17
+ *
18
+ * React Native's own requestAnimationFrame is a timer (setTimeout(0)): on
19
+ * Android it fires at a frame of the display only if it was registered before
20
+ * that frame started, which leaves a loop that asks for its next frame at the
21
+ * end of its work about 6 ms of the 8.3 ms of a 120 Hz frame, and drops it to
22
+ * 60 fps past that; on iOS its display link runs at 60 Hz. Worklets'
23
+ * requestAnimationFrame on a runtime of the app's polls every 16 ms. Here,
24
+ * the display's frames come from an animation frame source of the platform's
25
+ * (AnimationFrameSource), and:
26
+ *
27
+ * - The main runtime gets them through its CallInvoker: each frame runs every
28
+ * callback queued before it, with the frame's time.
29
+ * - A worklet runtime of the app has no way in from native code (this package
30
+ * does not link worklets), only its own timers: its setTimeout wakes it, and
31
+ * the runtime then waits on its own thread for the frame to start. That
32
+ * wait is the rest of the current frame at most, during which nothing else
33
+ * runs on the runtime; it gives up (and tries again later) when the display
34
+ * sends no frames, in the background say.
35
+ * - The Reanimated UI runtime keeps worklets' requestAnimationFrame, which is
36
+ * paced by the display already (and runs on the main thread, which a source
37
+ * of ours would have to hop to). So does any runtime when there is no
38
+ * animation frame source.
39
+ *
40
+ * Like a browser, a frame runs the callbacks requested before it started, and
41
+ * a callback requested while they run gets the next frame. The rules:
42
+ *
43
+ * - One run per frame of the display, counted from when the run starts. A
44
+ * run that starts late (the runtime was busy) is the run of the frame it
45
+ * starts in, not of the frame it was posted for: the next request then
46
+ * waits for the next frame, where it would otherwise find a frame that has
47
+ * not run here and run a second time in the same one.
48
+ * - A loop that overruns its frame does not wait for the frame after: when
49
+ * the frame it overran into is still going on, it runs in it (see
50
+ * currentFrameAfter). On a worklet runtime it always does, so a loop that
51
+ * takes 10 ms runs at 100 fps at 120 Hz, not 60.
52
+ * - The main runtime is not the loop's alone. A run in the frame the loop
53
+ * overran into goes behind whatever waits there (React's updates, the
54
+ * app's other tasks: see post), and only follows a run on an animation
55
+ * frame: the run after it waits for a frame of the display, which leaves
56
+ * the runtime to itself until then. A loop that takes 10 ms runs twice
57
+ * every three frames at 120 Hz, 80 fps. With every run posted as the one
58
+ * before it ends, the scheduler would never run out of tasks: React would
59
+ * not render, and the thread would not go back to its own loop, where iOS
60
+ * finds React Native's timers due. React Native's timer leaves the runtime
61
+ * the rest of each frame.
62
+ * - No frame while the app is not in the foreground (see setForeground): a
63
+ * loop stops with the app and starts again with it. Neither source stops
64
+ * on its own: an AChoreographer sends its frames to a paused app, and a
65
+ * CADisplayLink runs on in the background until the system suspends the
66
+ * app.
67
+ */
68
+
69
+ namespace rnwgpu {
70
+
71
+ namespace {
72
+
73
+ constexpr const char *kPropRequest = "request";
74
+ constexpr const char *kPropCancel = "cancel";
75
+
76
+ // A frame longer than this is a stretch without frames, not an interval.
77
+ constexpr int64_t kShortestInterval = 4'000'000;
78
+ constexpr int64_t kLongestInterval = 50'000'000;
79
+ // After this many frames without a request, the source stops ticking.
80
+ constexpr int kIdleFramesBeforeStop = 4;
81
+ // How long a waiting runtime waits for a frame before it gives the thread
82
+ // back, and how long it then sleeps before it asks again.
83
+ constexpr int64_t kWaitTimeoutNanos = 100'000'000;
84
+ constexpr double kRetryDelayMs = 100;
85
+
86
+ jsi::UUID runtimeDataUUID() {
87
+ // Fixed random UUID for this slot of runtimeData. Never the all-zero UUID,
88
+ // which Hermes reserves (see RuntimeContext::runtimeDataUUID).
89
+ static constexpr jsi::UUID uuid(0x5A3C9E71, 0x2D4B, 0x4F8A, 0x9C1E,
90
+ 0x7B6D2E4F8A13ULL);
91
+ return uuid;
92
+ }
93
+
94
+ jsi::Function getGlobalFunction(jsi::Runtime &runtime, const char *name) {
95
+ auto value = runtime.global().getProperty(runtime, name);
96
+ if (!value.isObject() || !value.asObject(runtime).isFunction(runtime)) {
97
+ throw jsi::JSError(runtime, std::string("[react-native-webgpu] ") + name +
98
+ " is not available on this runtime.");
99
+ }
100
+ return value.asObject(runtime).asFunction(runtime);
101
+ }
102
+
103
+ } // namespace
104
+
105
+ // AnimationFrameDispatcher
106
+
107
+ AnimationFrameDispatcher &AnimationFrameDispatcher::shared() {
108
+ // Never destroyed: the animation frame source calls into it from its own
109
+ // thread for the life of the process.
110
+ static auto *dispatcher = new AnimationFrameDispatcher();
111
+ return *dispatcher;
112
+ }
113
+
114
+ int64_t AnimationFrameDispatcher::nowNanos() {
115
+ return std::chrono::duration_cast<std::chrono::nanoseconds>(
116
+ std::chrono::steady_clock::now().time_since_epoch())
117
+ .count();
118
+ }
119
+
120
+ void AnimationFrameDispatcher::setSource(
121
+ std::shared_ptr<AnimationFrameSource> source) {
122
+ if (source == nullptr) {
123
+ return;
124
+ }
125
+ std::lock_guard<std::mutex> lock(_mutex);
126
+ // The platform's source outlives a reload: the first one stays.
127
+ if (_source != nullptr) {
128
+ return;
129
+ }
130
+ source->setFrameCallback(
131
+ [this](int64_t frameTimeNanos) { onFrame(frameTimeNanos); });
132
+ _source = std::move(source);
133
+ }
134
+
135
+ bool AnimationFrameDispatcher::hasSource() {
136
+ std::lock_guard<std::mutex> lock(_mutex);
137
+ return _source != nullptr;
138
+ }
139
+
140
+ void AnimationFrameDispatcher::setForeground(bool foreground) {
141
+ std::lock_guard<std::mutex> lock(_mutex);
142
+ if (_foreground == foreground) {
143
+ return;
144
+ }
145
+ _foreground = foreground;
146
+ // What asked for a frame while the app was away gets the next one.
147
+ if (foreground && (!_pending.empty() || _waiters > 0)) {
148
+ _idleFrames = 0;
149
+ requestFrameLocked();
150
+ }
151
+ }
152
+
153
+ AnimationFrameDispatcher::AnimationFrame
154
+ AnimationFrameDispatcher::latestFrame() {
155
+ std::lock_guard<std::mutex> lock(_mutex);
156
+ return _latest;
157
+ }
158
+
159
+ bool AnimationFrameDispatcher::currentFrameAfter(uint64_t after,
160
+ AnimationFrame &frame) {
161
+ std::lock_guard<std::mutex> lock(_mutex);
162
+ if (_foreground && _latest.id > after &&
163
+ nowNanos() - _latest.timeNanos < _intervalNanos) {
164
+ frame = _latest;
165
+ return true;
166
+ }
167
+ return false;
168
+ }
169
+
170
+ void AnimationFrameDispatcher::requestDelivery(
171
+ const std::shared_ptr<RuntimeAnimationFrames> &frames, uint64_t request) {
172
+ std::lock_guard<std::mutex> lock(_mutex);
173
+ _pending.push_back({frames, request});
174
+ _idleFrames = 0;
175
+ requestFrameLocked();
176
+ }
177
+
178
+ bool AnimationFrameDispatcher::waitForFrameAfter(uint64_t after,
179
+ int64_t timeoutNanos,
180
+ AnimationFrame &frame) {
181
+ std::unique_lock<std::mutex> lock(_mutex);
182
+ _idleFrames = 0;
183
+ requestFrameLocked();
184
+ if (_foreground && _latest.id > after &&
185
+ nowNanos() - _latest.timeNanos < _intervalNanos) {
186
+ // Caught up with the frame the caller is in (see currentFrameAfter).
187
+ frame = _latest;
188
+ return true;
189
+ }
190
+ const uint64_t current = _latest.id;
191
+ _waiters++;
192
+ const bool started =
193
+ _frameStarted.wait_for(lock, std::chrono::nanoseconds(timeoutNanos),
194
+ [&]() { return _latest.id > current; });
195
+ _waiters--;
196
+ if (started) {
197
+ frame = _latest;
198
+ }
199
+ return started;
200
+ }
201
+
202
+ void AnimationFrameDispatcher::requestFrameLocked() {
203
+ if (_source == nullptr || _frameRequested || !_foreground) {
204
+ return;
205
+ }
206
+ _frameRequested = true;
207
+ _source->requestFrame();
208
+ }
209
+
210
+ void AnimationFrameDispatcher::onFrame(int64_t frameTimeNanos) {
211
+ std::vector<Delivery> pending;
212
+ AnimationFrame frame;
213
+ {
214
+ std::lock_guard<std::mutex> lock(_mutex);
215
+ _frameRequested = false;
216
+ if (!_foreground) {
217
+ // Asked for before the app left the foreground: what waits for a frame
218
+ // gets the first one after it is back (see setForeground).
219
+ return;
220
+ }
221
+ const int64_t elapsed = frameTimeNanos - _latest.timeNanos;
222
+ if (_latest.id > 0 && elapsed >= kShortestInterval &&
223
+ elapsed <= kLongestInterval) {
224
+ _intervalNanos = elapsed;
225
+ }
226
+ _latest = {_latest.id + 1, frameTimeNanos};
227
+ frame = _latest;
228
+ pending.swap(_pending);
229
+ if (!pending.empty() || _waiters > 0) {
230
+ _idleFrames = 0;
231
+ } else {
232
+ _idleFrames++;
233
+ }
234
+ if (_idleFrames < kIdleFramesBeforeStop) {
235
+ requestFrameLocked();
236
+ }
237
+ }
238
+ _frameStarted.notify_all();
239
+ for (auto &delivery : pending) {
240
+ if (auto frames = delivery.frames.lock()) {
241
+ frames->deliver(frame, delivery.request);
242
+ }
243
+ }
244
+ }
245
+
246
+ // RuntimeAnimationFrames
247
+
248
+ RuntimeAnimationFrames::RuntimeAnimationFrames(jsi::Runtime &runtime, Kind kind)
249
+ : _runtime(runtime), _kind(kind) {}
250
+
251
+ namespace {
252
+
253
+ /**
254
+ * What a runtime holds of its animation frames, as its runtimeData.
255
+ *
256
+ * The callbacks are values of the runtime: they have to go while it is still
257
+ * there, from the thread that takes it down. The runtime releasing its
258
+ * runtimeData is that moment, and the last one. It is not always the last
259
+ * reference to the RuntimeAnimationFrames though: the dispatcher holds one on
260
+ * its own thread for the time of a deliver(), once per frame, and a runtime
261
+ * that goes away meanwhile (a reload) would leave the callbacks to be
262
+ * destroyed there, after the runtime. So they are released here, and whoever
263
+ * holds the last reference destroys an object without any.
264
+ */
265
+ struct RuntimeData {
266
+ explicit RuntimeData(std::shared_ptr<RuntimeAnimationFrames> frames)
267
+ : frames(std::move(frames)) {}
268
+ ~RuntimeData() { frames->releaseCallbacks(); }
269
+
270
+ std::shared_ptr<RuntimeAnimationFrames> frames;
271
+ };
272
+
273
+ } // namespace
274
+
275
+ std::shared_ptr<RuntimeAnimationFrames>
276
+ RuntimeAnimationFrames::forRuntime(jsi::Runtime &runtime) {
277
+ auto existing = std::static_pointer_cast<RuntimeData>(
278
+ runtime.getRuntimeData(runtimeDataUUID()));
279
+ if (existing) {
280
+ return existing->frames;
281
+ }
282
+ using RuntimeKind = async::RuntimeContext::RuntimeKind;
283
+ Kind kind = Kind::Delegated;
284
+ if (AnimationFrameDispatcher::shared().hasSource()) {
285
+ switch (async::RuntimeContext::runtimeKindOf(runtime)) {
286
+ case RuntimeKind::Main:
287
+ if (async::RuntimeContext::mainInvoker() != nullptr) {
288
+ kind = Kind::Main;
289
+ }
290
+ break;
291
+ case RuntimeKind::UI:
292
+ break;
293
+ case RuntimeKind::Other:
294
+ kind = Kind::Waiting;
295
+ break;
296
+ }
297
+ }
298
+ auto frames = std::make_shared<RuntimeAnimationFrames>(runtime, kind);
299
+ runtime.setRuntimeData(runtimeDataUUID(),
300
+ std::make_shared<RuntimeData>(frames));
301
+ return frames;
302
+ }
303
+
304
+ void RuntimeAnimationFrames::releaseCallbacks() {
305
+ _callbacks.clear();
306
+ _scheduled = false;
307
+ // A frame being delivered finds nothing waiting for it.
308
+ _request.store(0, std::memory_order_release);
309
+ }
310
+
311
+ double RuntimeAnimationFrames::request(jsi::Runtime &runtime,
312
+ jsi::Function callback) {
313
+ const double handle = _nextHandle++;
314
+ _callbacks.emplace(handle,
315
+ std::make_shared<jsi::Function>(std::move(callback)));
316
+ if (!_scheduled) {
317
+ schedule(runtime);
318
+ }
319
+ return handle;
320
+ }
321
+
322
+ void RuntimeAnimationFrames::cancel(double handle) {
323
+ _callbacks.erase(handle);
324
+ if (_flushing != nullptr) {
325
+ _flushing->erase(handle);
326
+ }
327
+ }
328
+
329
+ void RuntimeAnimationFrames::schedule(jsi::Runtime &runtime) {
330
+ switch (_kind) {
331
+ case Kind::Main: {
332
+ _scheduled = true;
333
+ const uint64_t request = ++_requests;
334
+ _request.store(request, std::memory_order_release);
335
+ auto &dispatcher = AnimationFrameDispatcher::shared();
336
+ AnimationFrameDispatcher::AnimationFrame frame;
337
+ // The frame we are in has not run here: a loop that overran its frame
338
+ // runs in this one, unless its last run was in its frame too.
339
+ if (_lastRun.load(std::memory_order_acquire) != Run::kInFrame &&
340
+ dispatcher.currentFrameAfter(
341
+ _lastFrameId.load(std::memory_order_acquire), frame)) {
342
+ _inFrameRequest.store(request, std::memory_order_release);
343
+ post(frame, request, Run::kInFrame);
344
+ }
345
+ // And on the next animation frame at the latest: whichever comes first
346
+ // runs the callbacks, and the other finds the request answered.
347
+ dispatcher.requestDelivery(shared_from_this(), request);
348
+ return;
349
+ }
350
+ case Kind::Waiting:
351
+ scheduleWaiting(runtime, 0);
352
+ _scheduled = true;
353
+ return;
354
+ case Kind::Delegated:
355
+ scheduleDelegated(runtime);
356
+ _scheduled = true;
357
+ return;
358
+ }
359
+ }
360
+
361
+ void RuntimeAnimationFrames::deliver(
362
+ const AnimationFrameDispatcher::AnimationFrame &frame, uint64_t request) {
363
+ if (_request.load(std::memory_order_acquire) != request) {
364
+ // Answered since.
365
+ return;
366
+ }
367
+ if (!_running.load(std::memory_order_acquire)) {
368
+ post(frame, request, Run::kOnFrame);
369
+ return;
370
+ }
371
+ // The callbacks of an earlier frame are still running: a loop that asks for
372
+ // its next frame first, and overruns. Its next run is in this frame, when
373
+ // the one going on came on an animation frame, and on a frame that starts
374
+ // once it is over otherwise.
375
+ if (_lastRun.load(std::memory_order_acquire) == Run::kOnFrame &&
376
+ _inFrameRequest.exchange(request, std::memory_order_acq_rel) != request) {
377
+ post(frame, request, Run::kInFrame);
378
+ }
379
+ AnimationFrameDispatcher::shared().requestDelivery(shared_from_this(),
380
+ request);
381
+ }
382
+
383
+ void RuntimeAnimationFrames::post(
384
+ const AnimationFrameDispatcher::AnimationFrame &frame, uint64_t request,
385
+ Run run) {
386
+ auto invoker = async::RuntimeContext::mainInvoker();
387
+ if (invoker == nullptr) {
388
+ return;
389
+ }
390
+ std::weak_ptr<RuntimeAnimationFrames> weak = weak_from_this();
391
+ facebook::react::CallFunc task = [weak, frame, request,
392
+ run](jsi::Runtime &runtime) {
393
+ auto self = weak.lock();
394
+ // A runtime created since (a reload) has frames of its own.
395
+ if (self == nullptr || &runtime != &self->_runtime) {
396
+ return;
397
+ }
398
+ // Answered already, by the other run posted for it (see schedule).
399
+ if (self->_request.load(std::memory_order_acquire) != request) {
400
+ return;
401
+ }
402
+ self->_lastRun.store(run, std::memory_order_release);
403
+ // One run per frame of the display, counted from when the run starts:
404
+ // posted for a frame and started in a later one (the runtime was busy),
405
+ // this is the run of the frame it starts in.
406
+ const auto latest = AnimationFrameDispatcher::shared().latestFrame();
407
+ const auto &current = latest.id > frame.id ? latest : frame;
408
+ self->flush(runtime, current.id, timestampOf(runtime, current.timeNanos));
409
+ };
410
+ if (run == Run::kInFrame) {
411
+ // The scheduler runs its tasks by expiry, and an idle task expires after
412
+ // everything that waits: React's updates and the app's other tasks go
413
+ // first.
414
+ invoker->invokeAsync(facebook::react::SchedulerPriority::IdlePriority,
415
+ std::move(task));
416
+ } else {
417
+ // Without a priority, which is the scheduler's highest: a frame of the
418
+ // display goes ahead of what waits, like React Native's own timers.
419
+ invoker->invokeAsync(std::move(task));
420
+ }
421
+ }
422
+
423
+ void RuntimeAnimationFrames::scheduleDelegated(jsi::Runtime &runtime) {
424
+ auto requestAnimationFrame =
425
+ getGlobalFunction(runtime, "requestAnimationFrame");
426
+ std::weak_ptr<RuntimeAnimationFrames> weak = weak_from_this();
427
+ auto onFrame = jsi::Function::createFromHostFunction(
428
+ runtime, jsi::PropNameID::forAscii(runtime, "RNWGPUAnimationFrame"), 1,
429
+ [weak](jsi::Runtime &runtime, const jsi::Value &, const jsi::Value *args,
430
+ size_t count) -> jsi::Value {
431
+ auto self = weak.lock();
432
+ if (self == nullptr || &runtime != &self->_runtime) {
433
+ return jsi::Value::undefined();
434
+ }
435
+ double timestamp = 0;
436
+ if (count > 0 && args[0].isNumber()) {
437
+ timestamp = args[0].asNumber();
438
+ } else {
439
+ timestamp =
440
+ timestampOf(runtime, AnimationFrameDispatcher::nowNanos());
441
+ }
442
+ self->flush(runtime, 0, timestamp);
443
+ return jsi::Value::undefined();
444
+ });
445
+ requestAnimationFrame.call(runtime, std::move(onFrame));
446
+ }
447
+
448
+ void RuntimeAnimationFrames::scheduleWaiting(jsi::Runtime &runtime,
449
+ double delayMs) {
450
+ auto setTimeout = getGlobalFunction(runtime, "setTimeout");
451
+ std::weak_ptr<RuntimeAnimationFrames> weak = weak_from_this();
452
+ auto tick = jsi::Function::createFromHostFunction(
453
+ runtime, jsi::PropNameID::forAscii(runtime, "RNWGPUAnimationFrameTick"),
454
+ 0,
455
+ [weak](jsi::Runtime &runtime, const jsi::Value &, const jsi::Value *,
456
+ size_t) -> jsi::Value {
457
+ auto self = weak.lock();
458
+ if (self == nullptr || &runtime != &self->_runtime) {
459
+ return jsi::Value::undefined();
460
+ }
461
+ AnimationFrameDispatcher::AnimationFrame frame;
462
+ if (!AnimationFrameDispatcher::shared().waitForFrameAfter(
463
+ self->_lastFrameId.load(std::memory_order_acquire),
464
+ kWaitTimeoutNanos, frame)) {
465
+ // No frames (the app is in the background): give the runtime
466
+ // back, and ask again later.
467
+ self->scheduleWaiting(runtime, kRetryDelayMs);
468
+ return jsi::Value::undefined();
469
+ }
470
+ self->flush(runtime, frame.id, timestampOf(runtime, frame.timeNanos));
471
+ return jsi::Value::undefined();
472
+ });
473
+ setTimeout.call(runtime, std::move(tick), jsi::Value(delayMs));
474
+ }
475
+
476
+ double RuntimeAnimationFrames::timestampOf(jsi::Runtime &runtime,
477
+ int64_t frameTimeNanos) {
478
+ // The frame's time on the runtime's performance.now() clock, whatever its
479
+ // origin: now, minus how long ago the frame started.
480
+ const double ageMs =
481
+ static_cast<double>(AnimationFrameDispatcher::nowNanos() -
482
+ frameTimeNanos) /
483
+ 1e6;
484
+ auto performance = runtime.global().getProperty(runtime, "performance");
485
+ if (performance.isObject()) {
486
+ auto object = performance.asObject(runtime);
487
+ auto now = object.getProperty(runtime, "now");
488
+ if (now.isObject() && now.asObject(runtime).isFunction(runtime)) {
489
+ auto value = now.asObject(runtime).asFunction(runtime).callWithThis(
490
+ runtime, object);
491
+ if (value.isNumber()) {
492
+ return value.asNumber() - (ageMs > 0 ? ageMs : 0);
493
+ }
494
+ }
495
+ }
496
+ return static_cast<double>(frameTimeNanos) / 1e6;
497
+ }
498
+
499
+ void RuntimeAnimationFrames::flush(jsi::Runtime &runtime, uint64_t frameId,
500
+ double timestampMs) {
501
+ _scheduled = false;
502
+ _request.store(0, std::memory_order_release);
503
+ if (frameId > 0) {
504
+ _lastFrameId.store(frameId, std::memory_order_release);
505
+ }
506
+ _running.store(true, std::memory_order_release);
507
+ // The callbacks requested before this frame; one requested while they run
508
+ // goes to the next frame, and one cancelled meanwhile does not run.
509
+ std::map<double, std::shared_ptr<jsi::Function>> callbacks;
510
+ callbacks.swap(_callbacks);
511
+ _flushing = &callbacks;
512
+ std::exception_ptr first = nullptr;
513
+ while (!callbacks.empty()) {
514
+ auto callback = callbacks.begin()->second;
515
+ callbacks.erase(callbacks.begin());
516
+ try {
517
+ callback->call(runtime, jsi::Value(timestampMs));
518
+ } catch (...) {
519
+ // Like a browser, the other callbacks of the frame still run.
520
+ if (first == nullptr) {
521
+ first = std::current_exception();
522
+ }
523
+ }
524
+ }
525
+ _flushing = nullptr;
526
+ _running.store(false, std::memory_order_release);
527
+ if (first != nullptr) {
528
+ std::rethrow_exception(first);
529
+ }
530
+ }
531
+
532
+ // AnimationFramesHostObject
533
+
534
+ jsi::Value AnimationFramesHostObject::get(jsi::Runtime &runtime,
535
+ const jsi::PropNameID &name) {
536
+ auto property = name.utf8(runtime);
537
+ if (property == kPropRequest) {
538
+ return jsi::Function::createFromHostFunction(
539
+ runtime, name, 1,
540
+ [](jsi::Runtime &runtime, const jsi::Value &, const jsi::Value *args,
541
+ size_t count) -> jsi::Value {
542
+ if (count < 1 || !args[0].isObject() ||
543
+ !args[0].asObject(runtime).isFunction(runtime)) {
544
+ throw jsi::JSError(runtime, "requestAnimationFrame: the first "
545
+ "argument must be a function.");
546
+ }
547
+ auto callback = args[0].asObject(runtime).asFunction(runtime);
548
+ return jsi::Value(
549
+ RuntimeAnimationFrames::forRuntime(runtime)->request(
550
+ runtime, std::move(callback)));
551
+ });
552
+ }
553
+ if (property == kPropCancel) {
554
+ return jsi::Function::createFromHostFunction(
555
+ runtime, name, 1,
556
+ [](jsi::Runtime &runtime, const jsi::Value &, const jsi::Value *args,
557
+ size_t count) -> jsi::Value {
558
+ if (count >= 1 && args[0].isNumber()) {
559
+ RuntimeAnimationFrames::forRuntime(runtime)->cancel(
560
+ args[0].asNumber());
561
+ }
562
+ return jsi::Value::undefined();
563
+ });
564
+ }
565
+ return jsi::Value::undefined();
566
+ }
567
+
568
+ std::vector<jsi::PropNameID>
569
+ AnimationFramesHostObject::getPropertyNames(jsi::Runtime &runtime) {
570
+ std::vector<jsi::PropNameID> names;
571
+ names.push_back(jsi::PropNameID::forAscii(runtime, kPropRequest));
572
+ names.push_back(jsi::PropNameID::forAscii(runtime, kPropCancel));
573
+ return names;
574
+ }
575
+
576
+ } // namespace rnwgpu