react-native-webgpu 0.19.2 → 0.21.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 (72) hide show
  1. package/Package.swift +19 -7
  2. package/android/CMakeLists.txt +1 -0
  3. package/android/build.gradle +7 -0
  4. package/android/cpp/cpp-adapter.cpp +23 -1
  5. package/android/src/main/java/com/webgpu/WebGPUModule.java +34 -3
  6. package/apple/ApplePlatformContext.h +6 -1
  7. package/apple/ApplePlatformContext.mm +7 -8
  8. package/apple/AppleVideoPlayer.mm +21 -11
  9. package/apple/MetalLayerColorSpace.mm +24 -1
  10. package/apple/WebGPUModule.mm +30 -1
  11. package/cpp/jsi/Promise.cpp +4 -0
  12. package/cpp/jsi/Promise.h +3 -0
  13. package/cpp/rnwgpu/CanvasColorSpace.h +5 -0
  14. package/cpp/rnwgpu/DawnBlobCache.cpp +477 -0
  15. package/cpp/rnwgpu/DawnBlobCache.h +76 -0
  16. package/cpp/rnwgpu/RNWebGPUManager.cpp +2 -4
  17. package/cpp/rnwgpu/SurfaceRegistry.h +16 -7
  18. package/cpp/rnwgpu/WebGPURuntime.cpp +2 -1
  19. package/cpp/rnwgpu/api/GPU.cpp +6 -6
  20. package/cpp/rnwgpu/api/GPU.h +1 -1
  21. package/cpp/rnwgpu/api/GPUAdapter.cpp +43 -7
  22. package/cpp/rnwgpu/api/GPUBuffer.cpp +5 -6
  23. package/cpp/rnwgpu/api/GPUCanvasContext.cpp +2 -1
  24. package/cpp/rnwgpu/api/GPUDevice.cpp +165 -48
  25. package/cpp/rnwgpu/api/GPUDevice.h +67 -14
  26. package/cpp/rnwgpu/api/GPUQueue.cpp +11 -2
  27. package/cpp/rnwgpu/api/GPUQueue.h +7 -2
  28. package/cpp/rnwgpu/api/GPUShaderModule.cpp +2 -2
  29. package/cpp/rnwgpu/api/RNWebGPU.h +11 -10
  30. package/cpp/rnwgpu/api/descriptors/GPUCanvasConfiguration.h +24 -0
  31. package/cpp/rnwgpu/async/AsyncTaskHandle.cpp +33 -45
  32. package/cpp/rnwgpu/async/AsyncTaskHandle.h +5 -6
  33. package/cpp/rnwgpu/async/RuntimeContext.cpp +321 -112
  34. package/cpp/rnwgpu/async/RuntimeContext.h +90 -82
  35. package/lib/commonjs/Canvas.js +1 -0
  36. package/lib/commonjs/Canvas.js.map +1 -1
  37. package/lib/commonjs/WebGPUViewNativeComponent.js.map +1 -1
  38. package/lib/commonjs/WebGPUViewNativeComponent.web.js.map +1 -1
  39. package/lib/commonjs/external/reanimated/registerWebGPUForReanimated.js +19 -1
  40. package/lib/commonjs/external/reanimated/registerWebGPUForReanimated.js.map +1 -1
  41. package/lib/commonjs/install.js +6 -5
  42. package/lib/commonjs/install.js.map +1 -1
  43. package/lib/module/Canvas.js +1 -0
  44. package/lib/module/Canvas.js.map +1 -1
  45. package/lib/module/WebGPUViewNativeComponent.js.map +1 -1
  46. package/lib/module/WebGPUViewNativeComponent.web.js.map +1 -1
  47. package/lib/module/external/reanimated/registerWebGPUForReanimated.js +19 -1
  48. package/lib/module/external/reanimated/registerWebGPUForReanimated.js.map +1 -1
  49. package/lib/module/install.js +6 -5
  50. package/lib/module/install.js.map +1 -1
  51. package/lib/typescript/lib/commonjs/Canvas.d.ts.map +1 -1
  52. package/lib/typescript/lib/commonjs/external/reanimated/registerWebGPUForReanimated.d.ts.map +1 -1
  53. package/lib/typescript/lib/commonjs/install.d.ts +6 -5
  54. package/lib/typescript/lib/commonjs/install.d.ts.map +1 -1
  55. package/lib/typescript/lib/module/Canvas.d.ts.map +1 -1
  56. package/lib/typescript/lib/module/external/reanimated/registerWebGPUForReanimated.d.ts.map +1 -1
  57. package/lib/typescript/lib/module/install.d.ts.map +1 -1
  58. package/lib/typescript/src/Canvas.d.ts.map +1 -1
  59. package/lib/typescript/src/WebGPUViewNativeComponent.d.ts +6 -7
  60. package/lib/typescript/src/WebGPUViewNativeComponent.d.ts.map +1 -1
  61. package/lib/typescript/src/WebGPUViewNativeComponent.web.d.ts +2 -3
  62. package/lib/typescript/src/WebGPUViewNativeComponent.web.d.ts.map +1 -1
  63. package/lib/typescript/src/external/reanimated/registerWebGPUForReanimated.d.ts +1 -0
  64. package/lib/typescript/src/external/reanimated/registerWebGPUForReanimated.d.ts.map +1 -1
  65. package/lib/typescript/src/install.d.ts +6 -5
  66. package/lib/typescript/src/install.d.ts.map +1 -1
  67. package/package.json +3 -2
  68. package/src/Canvas.tsx +4 -2
  69. package/src/WebGPUViewNativeComponent.ts +6 -10
  70. package/src/WebGPUViewNativeComponent.web.ts +2 -3
  71. package/src/external/reanimated/registerWebGPUForReanimated.ts +21 -1
  72. package/src/install.ts +6 -5
@@ -17,6 +17,7 @@
17
17
  #endif
18
18
 
19
19
  #include "Convertors.h"
20
+ #include "DawnBlobCache.h"
20
21
 
21
22
  #include "GPUFeatures.h"
22
23
  #include "JSIConverter.h"
@@ -254,8 +255,9 @@ async::AsyncTaskHandle GPUAdapter::requestDevice(
254
255
  // (MediaTek mt6855) segfaults while Skia Graphite compiles its
255
256
  // pipelines (wcandillon/react-native-skia#4340). With one cache the
256
257
  // only vkDestroyPipelineCache runs at device teardown, and pipelines
257
- // that share binaries compile faster. PerformIdleTasks is not needed:
258
- // nothing persists the cache.
258
+ // that share binaries compile faster. Dawn writes that cache to the
259
+ // blob cache only when told the device is idle, which GPUDevice does
260
+ // (see GPUDevice::flushPipelineCache).
259
261
  static const char *const kAndroidEnabledToggles[] = {
260
262
  "ignore_imported_ahardwarebuffer_vulkan_image_size",
261
263
  "vulkan_monolithic_pipeline_cache"};
@@ -271,6 +273,32 @@ async::AsyncTaskHandle GPUAdapter::requestDevice(
271
273
  enabledToggles.push_back(name);
272
274
  }
273
275
  }
276
+ #endif
277
+ #if defined(__APPLE__)
278
+ // iOS refuses GPU work from an app in the background, and Dawn loses
279
+ // the device over a refused command buffer. With this toggle Dawn
280
+ // holds the commits while the app is in the background, from
281
+ // UIApplication's own notifications, and commits them when it comes
282
+ // back: nothing is lost, nothing is refused, and a promise on the
283
+ // held work settles once the app is back (the same toggle Skia
284
+ // requests on the device it shares, see react-native-skia's
285
+ // DawnUtils::requestDevice). Dawn applies it on iOS and tvOS only, and
286
+ // a Dawn without it (react-native-webgpu-dawn before 157.1.0) drops
287
+ // the name. The caller opts out through disabledToggles.
288
+ {
289
+ static const char *const kName =
290
+ "metal_suspend_submissions_in_background";
291
+ const auto named = [](const char *t) {
292
+ return std::strcmp(t, kName) == 0;
293
+ };
294
+ const bool explicitlyDisabled = std::any_of(
295
+ disabledToggles.begin(), disabledToggles.end(), named);
296
+ const bool alreadyEnabled =
297
+ std::any_of(enabledToggles.begin(), enabledToggles.end(), named);
298
+ if (!explicitlyDisabled && !alreadyEnabled) {
299
+ enabledToggles.push_back(kName);
300
+ }
301
+ }
274
302
  #endif
275
303
  if (!enabledToggles.empty() || !disabledToggles.empty()) {
276
304
  toggles.enabledToggleCount = enabledToggles.size();
@@ -279,8 +307,14 @@ async::AsyncTaskHandle GPUAdapter::requestDevice(
279
307
  toggles.disabledToggles = disabledToggles.data();
280
308
  deviceDesc.nextInChain = &toggles;
281
309
  }
282
- _instance.RequestDevice(
283
- &deviceDesc, wgpu::CallbackMode::AllowProcessEvents,
310
+ // Compiled pipelines are kept on disk across launches (see
311
+ // DawnBlobCache). Chained in front of the toggles, and alive for the
312
+ // synchronous RequestDevice call below, like them.
313
+ WGPUDawnCacheDeviceDescriptor blobCache =
314
+ WGPU_DAWN_CACHE_DEVICE_DESCRIPTOR_INIT;
315
+ DawnBlobCache::chain(deviceDesc, blobCache);
316
+ return _instance.RequestDevice(
317
+ &deviceDesc, wgpu::CallbackMode::WaitAnyOnly,
284
318
  [context, resolve, reject, label, creationRuntime,
285
319
  deviceLostBinding](wgpu::RequestDeviceStatus status,
286
320
  wgpu::Device device, wgpu::StringView message) {
@@ -329,13 +363,15 @@ async::AsyncTaskHandle GPUAdapter::requestDevice(
329
363
  },
330
364
  creationRuntime);
331
365
 
332
- auto deviceHost = std::make_shared<GPUDevice>(std::move(device),
333
- context, label);
366
+ auto deviceHost =
367
+ std::make_shared<GPUDevice>(std::move(device), context, label,
368
+ GPUDevice::Origin::Requested);
334
369
  *deviceLostBinding = deviceHost;
335
370
 
336
371
  // Register the device in the static registry so the uncaptured
337
372
  // error callback can find it
338
- GPUDevice::registerDevice(deviceHost->get().Get(), deviceHost);
373
+ GPUDevice::registerDevice(deviceHost->get().Get(),
374
+ deviceHost.get());
339
375
 
340
376
  resolve([deviceHost = std::move(deviceHost)](
341
377
  jsi::Runtime &runtime) mutable {
@@ -55,18 +55,17 @@ async::AsyncTaskHandle GPUBuffer::mapAsync(jsi::Runtime &runtime,
55
55
  // Post to the CALLING runtime's context, not the one captured at buffer
56
56
  // creation (_async): the buffer may have been created on another runtime and
57
57
  // boxed across (e.g. device created on the main JS runtime, mapAsync called
58
- // from a worklet). The returned Promise lives on the calling runtime, so it
59
- // must be settled from that runtime's own thread — and postTask itself
60
- // schedules the pump through its context's runtime (setTimeout), which is
61
- // only safe for the runtime we are currently executing on.
58
+ // The returned Promise lives on the calling runtime, so it
59
+ // must be settled from that runtime's own thread, which its context knows
60
+ // how to reach (see RuntimeContext).
62
61
  auto context =
63
62
  async::RuntimeContext::getOrCreate(runtime, _async->instance());
64
63
  return context->postTask(
65
64
  [bufferHandle, mode, resolvedOffset,
66
65
  rangeSize](const async::AsyncTaskHandle::ResolveFunction &resolve,
67
66
  const async::AsyncTaskHandle::RejectFunction &reject) {
68
- bufferHandle.MapAsync(
69
- mode, resolvedOffset, rangeSize, wgpu::CallbackMode::AllowProcessEvents,
67
+ return bufferHandle.MapAsync(
68
+ mode, resolvedOffset, rangeSize, wgpu::CallbackMode::WaitAnyOnly,
70
69
  [resolve, reject](wgpu::MapAsyncStatus status,
71
70
  wgpu::StringView message) {
72
71
  switch (status) {
@@ -30,7 +30,8 @@ void GPUCanvasContext::configure(
30
30
  #endif
31
31
  surfaceConfiguration.presentMode = wgpu::PresentMode::Fifo;
32
32
  _surfaceInfo->configure(surfaceConfiguration, std::move(viewFormats),
33
- configuration->colorSpace);
33
+ configuration->colorSpace,
34
+ configuration->toneMappingMode);
34
35
  }
35
36
 
36
37
  void GPUCanvasContext::unconfigure() { _surfaceInfo->unconfigure(); }
@@ -1,5 +1,8 @@
1
1
  #include "GPUDevice.h"
2
2
 
3
+ #include <atomic>
4
+ #include <chrono>
5
+ #include <cstdint>
3
6
  #include <cstdio>
4
7
  #include <memory>
5
8
  #include <string>
@@ -9,7 +12,10 @@
9
12
 
10
13
  #include <ReactCommon/CallInvoker.h>
11
14
 
15
+ #include "dawn/native/DawnNative.h"
16
+
12
17
  #include "Convertors.h"
18
+ #include "DawnBlobCache.h"
13
19
  #include "JSIConverter.h"
14
20
 
15
21
  #include "GPUFeatures.h"
@@ -45,8 +51,125 @@ void defineHiddenProperty(jsi::Runtime &runtime, const jsi::Object &target,
45
51
  jsi::String::createFromUtf8(runtime, name), descriptor);
46
52
  }
47
53
 
54
+ // Has Dawn write what its pipeline cache holds to the blob cache. Nothing is
55
+ // left to write once the device is lost or destroyed (Dawn drops the pipeline
56
+ // cache with the backend), and nothing is written once the cache has refused
57
+ // its data as too large. Any thread that may use the device.
58
+ void flushDawnPipelineCache(const wgpu::Device &device,
59
+ std::atomic<bool> &outgrown) {
60
+ if (outgrown.load(std::memory_order_relaxed) ||
61
+ dawn::native::IsDeviceLost(device.Get())) {
62
+ return;
63
+ }
64
+ // Dawn stores on this thread, before PerformIdleTasks returns, and stores
65
+ // nothing but the pipeline cache on idle: a store refused as too large on
66
+ // the way is the pipeline cache's, and from then on serializing it (Dawn
67
+ // copies the whole of it out of the driver, hashes it and copies it again)
68
+ // would be for nothing.
69
+ const uint64_t refused = DawnBlobCache::refusedStoresOnThisThread();
70
+ dawn::native::PerformIdleTasks(device);
71
+ if (DawnBlobCache::refusedStoresOnThisThread() != refused) {
72
+ outgrown.store(true, std::memory_order_relaxed);
73
+ }
74
+ }
75
+
48
76
  } // namespace
49
77
 
78
+ void GPUDevice::flushPipelineCache() {
79
+ // An imported device's cache is its owner's: nothing chained the blob cache
80
+ // onto it, and its owner's own threads may be using it.
81
+ if (_origin == Origin::Imported) {
82
+ return;
83
+ }
84
+ flushDawnPipelineCache(_instance, *_pipelineCacheOutgrown);
85
+ }
86
+
87
+ void GPUDevice::flushPipelineCacheIfDue() {
88
+ if (_origin == Origin::Imported ||
89
+ _pipelineCacheOutgrown->load(std::memory_order_relaxed)) {
90
+ return;
91
+ }
92
+ using Clock = std::chrono::steady_clock;
93
+ static constexpr auto kInterval =
94
+ std::chrono::duration_cast<Clock::duration>(std::chrono::seconds(10))
95
+ .count();
96
+ const auto now = Clock::now().time_since_epoch().count();
97
+ auto last = _lastPipelineCacheFlush.load(std::memory_order_relaxed);
98
+ if (now - last < kInterval) {
99
+ return;
100
+ }
101
+ // Threads submitting at once (ImplicitDeviceSynchronization) race for the
102
+ // flush, and the one that claims the time does it.
103
+ if (!_lastPipelineCacheFlush.compare_exchange_strong(
104
+ last, now, std::memory_order_relaxed)) {
105
+ return;
106
+ }
107
+ // Off the submitting thread when Dawn's lock lets any thread use the
108
+ // device. The job holds the device by its Dawn handle, not this wrapper: it
109
+ // may outlive the wrapper, which must only go on its runtime's thread (see
110
+ // flushPipelineCaches).
111
+ if (_instance.HasFeature(wgpu::FeatureName::ImplicitDeviceSynchronization)) {
112
+ DawnBlobCache::post(
113
+ [device = _instance, outgrown = _pipelineCacheOutgrown] {
114
+ flushDawnPipelineCache(device, *outgrown);
115
+ });
116
+ return;
117
+ }
118
+ flushPipelineCache();
119
+ }
120
+
121
+ void GPUDevice::flushPipelineCaches() {
122
+ // What flushing a device takes, copied out of its wrapper under the
123
+ // registry's mutex, rather than the wrapper itself: a strong reference to
124
+ // the wrapper released on this thread (the platform's UI thread) could be
125
+ // its last, and a wrapper, with its JSI members, must only go on its
126
+ // runtime's thread.
127
+ struct Flush {
128
+ wgpu::Device device;
129
+ std::shared_ptr<std::atomic<bool>> outgrown;
130
+ std::shared_ptr<async::RuntimeContext> async;
131
+ std::weak_ptr<GPUDevice> wrapper;
132
+ };
133
+ std::vector<Flush> flushes;
134
+ {
135
+ std::lock_guard<std::mutex> lock(getRegistryMutex());
136
+ for (const auto &entry : getRegistry()) {
137
+ GPUDevice *device = entry.second;
138
+ // A wrapper on its way out (its last reference gone, its destructor
139
+ // about to unregister it) has nothing left to flush; nor has an
140
+ // imported device, whose owner keeps its cache.
141
+ if (device->_origin == Origin::Imported ||
142
+ device->weak_from_this().expired()) {
143
+ continue;
144
+ }
145
+ flushes.push_back({device->_instance, device->_pipelineCacheOutgrown,
146
+ device->_async, device->weak_from_this()});
147
+ }
148
+ }
149
+ for (const auto &flush : flushes) {
150
+ // Dawn locks a device that synchronizes itself around the flush, so this
151
+ // thread can do it, and does: the runtime's thread may be busy, and a
152
+ // runtime that polls its mailbox would hold the job until its next
153
+ // operation, which may never come before the process is killed.
154
+ if (flush.device.HasFeature(
155
+ wgpu::FeatureName::ImplicitDeviceSynchronization)) {
156
+ flushDawnPipelineCache(flush.device, *flush.outgrown);
157
+ continue;
158
+ }
159
+ if (!flush.async) {
160
+ continue;
161
+ }
162
+ // A device used from its runtime's thread only is flushed there. Held
163
+ // weakly: a device collected before its runtime gets to the job has
164
+ // nothing left to flush, and the job must not keep it alive.
165
+ flush.async->post([weak = flush.wrapper](jsi::Runtime &) {
166
+ if (auto device = weak.lock()) {
167
+ device->flushPipelineCache();
168
+ }
169
+ });
170
+ }
171
+ }
172
+
50
173
  void GPUDevice::notifyDeviceLost(wgpu::DeviceLostReason reason,
51
174
  std::string message) {
52
175
  std::vector<PendingLostPromise> toResolve;
@@ -68,41 +191,35 @@ void GPUDevice::notifyDeviceLost(wgpu::DeviceLostReason reason,
68
191
  return;
69
192
  }
70
193
 
71
- // getLost() only registers promises when the device's context has a
72
- // CallInvoker (main JS runtime), so a non-empty list implies an invoker.
73
- auto invoker = _async ? _async->callInvoker() : nullptr;
74
- if (!invoker) {
75
- return;
76
- }
77
-
78
- // Settle on the owning runtime's JS thread. The promises are held weakly:
79
- // if the device graph was collected in the meantime there is nothing to do,
80
- // since nobody could observe the resolution anyway. The shared_ptr is only
81
- // there because jsi::WeakObject is move-only and std::function requires a
82
- // copyable closure; it also ensures the WeakObjects are destroyed on the JS
83
- // thread.
84
- auto pending =
85
- std::make_shared<std::vector<PendingLostPromise>>(std::move(toResolve));
86
- invoker->invokeAsync([pending, info]() {
87
- for (auto &entry : *pending) {
88
- auto &runtime = *entry.runtime;
89
- auto locked = entry.promise.lock(runtime);
194
+ // Settle each promise on the thread of the runtime that read it, through
195
+ // that runtime's context. The promises are held weakly: if the device graph
196
+ // was collected in the meantime there is nothing to do, since nobody could
197
+ // observe the resolution anyway. The shared_ptr is only there because
198
+ // jsi::WeakObject is move-only and std::function requires a copyable
199
+ // closure.
200
+ for (auto &entry : toResolve) {
201
+ auto context = entry.context.lock();
202
+ if (context == nullptr) {
203
+ continue;
204
+ }
205
+ auto pending = std::make_shared<jsi::WeakObject>(std::move(entry.promise));
206
+ context->post([pending, info](jsi::Runtime &runtime) {
207
+ auto locked = pending->lock(runtime);
90
208
  if (!locked.isObject()) {
91
- continue;
209
+ return;
92
210
  }
93
211
  auto promiseObj = locked.getObject(runtime);
94
212
  auto resolveProp = promiseObj.getProperty(runtime, kLostResolveProp);
95
213
  if (!resolveProp.isObject() ||
96
214
  !resolveProp.getObject(runtime).isFunction(runtime)) {
97
- continue;
215
+ return;
98
216
  }
99
217
  auto resolveFn = resolveProp.getObject(runtime).getFunction(runtime);
100
218
  resolveFn.call(runtime,
101
219
  JSIConverter<std::shared_ptr<GPUDeviceLostInfo>>::toJSI(
102
220
  runtime, info));
103
- }
104
- pending->clear();
105
- });
221
+ });
222
+ }
106
223
  }
107
224
 
108
225
  void GPUDevice::forceLossForTesting() {
@@ -143,7 +260,7 @@ std::shared_ptr<GPUAdapterInfo> GPUDevice::getAdapterInfo() {
143
260
  std::shared_ptr<GPUQueue> GPUDevice::getQueue() {
144
261
  auto result = _instance.GetQueue();
145
262
  return std::make_shared<GPUQueue>(_instance, result, _async, _videoFrameBlit,
146
- _label);
263
+ _label, weak_from_this());
147
264
  }
148
265
 
149
266
  std::shared_ptr<GPUCommandEncoder> GPUDevice::createCommandEncoder(
@@ -160,6 +277,9 @@ std::shared_ptr<GPUCommandEncoder> GPUDevice::createCommandEncoder(
160
277
  }
161
278
 
162
279
  void GPUDevice::destroy() {
280
+ // The last chance to write what the pipelines added to Dawn's pipeline
281
+ // cache: once destroyed, the device has nothing left to serialize.
282
+ flushPipelineCache();
163
283
  // DAWN_WORKAROUND_DEVICE_DESTROY_BEFORE_SURFACE_RELEASE
164
284
  // Any canvas surface holding a swapchain for this device must let go of it
165
285
  // while the device is alive (see SurfaceInfo::releaseSurfaceForDevice).
@@ -534,8 +654,8 @@ async::AsyncTaskHandle GPUDevice::createComputePipelineAsync(
534
654
  const async::AsyncTaskHandle::RejectFunction
535
655
  &reject) {
536
656
  (void)descriptor;
537
- device.CreateComputePipelineAsync(
538
- &desc, wgpu::CallbackMode::AllowProcessEvents,
657
+ return device.CreateComputePipelineAsync(
658
+ &desc, wgpu::CallbackMode::WaitAnyOnly,
539
659
  [pipelineHolder, resolve,
540
660
  reject](wgpu::CreatePipelineAsyncStatus status,
541
661
  wgpu::ComputePipeline pipeline, wgpu::StringView msg) {
@@ -581,8 +701,8 @@ async::AsyncTaskHandle GPUDevice::createRenderPipelineAsync(
581
701
  const async::AsyncTaskHandle::RejectFunction
582
702
  &reject) {
583
703
  (void)descriptor;
584
- device.CreateRenderPipelineAsync(
585
- &desc, wgpu::CallbackMode::AllowProcessEvents,
704
+ return device.CreateRenderPipelineAsync(
705
+ &desc, wgpu::CallbackMode::WaitAnyOnly,
586
706
  [pipelineHolder, resolve,
587
707
  reject](wgpu::CreatePipelineAsyncStatus status,
588
708
  wgpu::RenderPipeline pipeline, wgpu::StringView msg) {
@@ -617,8 +737,8 @@ async::AsyncTaskHandle GPUDevice::popErrorScope(jsi::Runtime &runtime) {
617
737
  &resolve,
618
738
  const async::AsyncTaskHandle::RejectFunction
619
739
  &reject) {
620
- device.PopErrorScope(
621
- wgpu::CallbackMode::AllowProcessEvents,
740
+ return device.PopErrorScope(
741
+ wgpu::CallbackMode::WaitAnyOnly,
622
742
  [resolve, reject](wgpu::PopErrorScopeStatus status,
623
743
  wgpu::ErrorType type, wgpu::StringView message) {
624
744
  if (status == wgpu::PopErrorScopeStatus::Error ||
@@ -731,12 +851,12 @@ jsi::Value GPUDevice::getLost(jsi::Runtime &runtime,
731
851
  *capturedResolve);
732
852
 
733
853
  // Register a WEAK reference so notifyDeviceLost() can settle the promise
734
- // if it is still alive. Only wired for the device's own runtime when a
735
- // CallInvoker exists (main JS runtime): spontaneous events are delivered
736
- // through that invoker. A promise created on another runtime stays
737
- // pending, matching the previous best-effort behavior.
854
+ // if it is still alive, on the thread of the runtime that read it,
855
+ // through that runtime's context (see RuntimeContext::post).
738
856
  bool settledMeanwhile = false;
739
- if (_async && _async->callInvoker() && &runtime == &_async->runtime()) {
857
+ if (_async) {
858
+ auto context =
859
+ async::RuntimeContext::getOrCreate(runtime, _async->instance());
740
860
  std::lock_guard<std::mutex> lock(_lostMutex);
741
861
  if (_lostSettled) {
742
862
  // The device was lost between the check above and now.
@@ -744,7 +864,7 @@ jsi::Value GPUDevice::getLost(jsi::Runtime &runtime,
744
864
  settledInfo = _lostInfo;
745
865
  } else {
746
866
  _lostPromises.push_back(
747
- PendingLostPromise{&runtime, jsi::WeakObject(runtime, promiseObj)});
867
+ PendingLostPromise{jsi::WeakObject(runtime, promiseObj), context});
748
868
  }
749
869
  }
750
870
  if (settledMeanwhile) {
@@ -775,20 +895,17 @@ void GPUDevice::removeEventListener(std::string type, jsi::Function callback) {
775
895
 
776
896
  void GPUDevice::notifyUncapturedError(wgpu::ErrorType type,
777
897
  std::string message) {
778
- // Dawn can surface an uncaptured error from any ProcessEvents pump (a worklet
779
- // runtime sharing this instance may pump it on the wrong thread). Marshal to
780
- // the owning runtime's JS thread via its CallInvoker before touching JSI. The
781
- // invoker is wired only for the main JS runtime, so a device created on a
782
- // worklet runtime does not deliver uncaptured errors to JS (best-effort; see
783
- // README "Threading model").
784
- auto invoker = _async ? _async->callInvoker() : nullptr;
785
- if (!invoker) {
898
+ // Dawn reports an uncaptured error from whichever thread detects it. The
899
+ // listeners run on the thread of the runtime the device was created on,
900
+ // through its context (see RuntimeContext::post).
901
+ if (!_async) {
786
902
  return;
787
903
  }
788
904
  auto self = shared_from_this();
789
- invoker->invokeAsync([self, type, message = std::move(message)]() mutable {
790
- self->deliverUncapturedError(type, std::move(message));
791
- });
905
+ _async->post(
906
+ [self, type, message = std::move(message)](jsi::Runtime &) mutable {
907
+ self->deliverUncapturedError(type, std::move(message));
908
+ });
792
909
  }
793
910
 
794
911
  void GPUDevice::deliverUncapturedError(wgpu::ErrorType type,
@@ -1,5 +1,7 @@
1
1
  #pragma once
2
2
 
3
+ #include <atomic>
4
+ #include <chrono>
3
5
  #include <functional>
4
6
  #include <memory>
5
7
  #include <mutex>
@@ -68,20 +70,28 @@ class GPUDevice : public NativeObject<GPUDevice> {
68
70
  public:
69
71
  static constexpr const char *CLASS_NAME = "GPUDevice";
70
72
 
73
+ // Where the device came from: requestDevice(), or another library through
74
+ // importDevice(). An imported device's pipeline cache is its owner's.
75
+ enum class Origin { Requested, Imported };
76
+
71
77
  explicit GPUDevice(wgpu::Device instance,
72
78
  std::shared_ptr<async::RuntimeContext> async,
73
- std::string label)
79
+ std::string label, Origin origin)
74
80
  : NativeObject(CLASS_NAME), _instance(instance), _async(async),
75
- _label(label) {}
81
+ _label(label), _origin(origin) {}
76
82
 
77
83
  ~GPUDevice() override {
78
84
  // Unregister from the static registry
79
85
  unregisterDevice(_instance.Get());
80
86
  }
81
87
 
82
- // Static registry for looking up GPUDevice from wgpu::Device in callbacks
83
- static void registerDevice(WGPUDevice handle,
84
- std::weak_ptr<GPUDevice> device) {
88
+ // Static registry for looking up GPUDevice from wgpu::Device in callbacks.
89
+ // Holds the wrapper by plain pointer: it unregisters itself in its
90
+ // destructor, under the registry's mutex, before any of its members go, so
91
+ // an entry's wrapper is alive for as long as the mutex is held, and its
92
+ // weak_from_this() tells whether it may still be shared (expired once it is
93
+ // being destroyed).
94
+ static void registerDevice(WGPUDevice handle, GPUDevice *device) {
85
95
  std::lock_guard<std::mutex> lock(getRegistryMutex());
86
96
  getRegistry()[handle] = device;
87
97
  }
@@ -95,15 +105,14 @@ public:
95
105
  std::lock_guard<std::mutex> lock(getRegistryMutex());
96
106
  auto it = getRegistry().find(handle);
97
107
  if (it != getRegistry().end()) {
98
- return it->second.lock();
108
+ return it->second->weak_from_this().lock();
99
109
  }
100
110
  return nullptr;
101
111
  }
102
112
 
103
113
  private:
104
- static std::unordered_map<WGPUDevice, std::weak_ptr<GPUDevice>> &
105
- getRegistry() {
106
- static std::unordered_map<WGPUDevice, std::weak_ptr<GPUDevice>> registry;
114
+ static std::unordered_map<WGPUDevice, GPUDevice *> &getRegistry() {
115
+ static std::unordered_map<WGPUDevice, GPUDevice *> registry;
107
116
  return registry;
108
117
  }
109
118
 
@@ -298,16 +307,61 @@ public:
298
307
 
299
308
  inline const wgpu::Device get() { return _instance; }
300
309
 
310
+ // Has Dawn write what its monolithic Vulkan pipeline cache holds to the blob
311
+ // cache (see DawnBlobCache). Dawn keeps that cache in memory and writes it
312
+ // only when the embedder says the device is idle (the
313
+ // vulkan_monolithic_pipeline_cache toggle says so), so without this a
314
+ // relaunch would start with an empty one. Cheap when no pipeline was
315
+ // compiled since the last call: Dawn keeps a flag, and skips a cache whose
316
+ // size has not changed. Nothing to do on other backends, nor on an imported
317
+ // device, whose owner keeps its cache, nor once the blob cache has refused
318
+ // the pipeline cache's data as too large (see DawnBlobCache::setDirectory):
319
+ // serializing it again would be for nothing. Runs on the calling thread,
320
+ // which must be one that may use the device: the thread of its runtime, or
321
+ // any thread when the device synchronizes itself
322
+ // (ImplicitDeviceSynchronization). destroy() calls it, and so do
323
+ // flushPipelineCacheIfDue() and flushPipelineCaches().
324
+ void flushPipelineCache();
325
+
326
+ // flushPipelineCache(), at most once every ten seconds. GPUQueue::submit
327
+ // calls it, so that a session that ends without destroy() or a pause (a
328
+ // crash, the system killing the app in the foreground) loses at most those
329
+ // seconds of pipeline building. Serializing the pipeline cache would hold up
330
+ // the frame being submitted (Dawn copies the whole of it out of the driver,
331
+ // hashes it and copies it again), so a device that synchronizes itself (the
332
+ // default) is flushed on the blob cache's thread instead; a device only its
333
+ // runtime's thread may use is flushed here. Any thread that may use the
334
+ // device.
335
+ void flushPipelineCacheIfDue();
336
+
337
+ // Flushes every live device: here when the device synchronizes itself (the
338
+ // default), else on the thread of its runtime, which a runtime that polls
339
+ // its mailbox (a worklet runtime's) reaches with its next operation. Any
340
+ // thread: the platform modules call it when the app goes to the background,
341
+ // the last moment to write before the process may be killed.
342
+ static void flushPipelineCaches();
343
+
301
344
  private:
302
345
  friend class GPUAdapter;
303
346
 
304
347
  // Runs the uncapturederror listeners on the creation runtime's JS thread.
305
- // Invoked from notifyUncapturedError via the main CallInvoker.
348
+ // Invoked from notifyUncapturedError through the runtime's context.
306
349
  void deliverUncapturedError(wgpu::ErrorType type, std::string message);
307
350
 
308
351
  wgpu::Device _instance;
309
352
  std::shared_ptr<async::RuntimeContext> _async;
310
353
  std::string _label;
354
+ const Origin _origin;
355
+ // Set once the blob cache refused the pipeline cache's data as too large
356
+ // (see flushPipelineCache). Shared with the flushes on the cache's thread,
357
+ // which hold the device by its Dawn handle and may outlive this wrapper.
358
+ std::shared_ptr<std::atomic<bool>> _pipelineCacheOutgrown =
359
+ std::make_shared<std::atomic<bool>>(false);
360
+ // When flushPipelineCacheIfDue() last flushed, in steady_clock ticks. A
361
+ // flush is claimed by swapping in the time, so that threads submitting at
362
+ // once flush once.
363
+ std::atomic<std::chrono::steady_clock::rep> _lastPipelineCacheFlush{
364
+ std::chrono::steady_clock::now().time_since_epoch().count()};
311
365
  // Renders native video frames into textures for
312
366
  // GPUQueue.copyExternalImageToTexture; shared by every GPUQueue wrapper of
313
367
  // this device so the pipelines are created once.
@@ -327,12 +381,11 @@ private:
327
381
  // resolve function lives as a hidden property on the promise object itself,
328
382
  // so if the promise is still alive when the device is lost we can settle
329
383
  // it; if it was collected, nobody could have observed the resolution.
330
- // Entries are only added for the device's own runtime when a CallInvoker is
331
- // available (main JS runtime), matching the best-effort contract for
332
- // spontaneous events.
384
+ // Each entry is settled on the thread of the runtime that read `lost`,
385
+ // through that runtime's context; a runtime gone since is skipped.
333
386
  struct PendingLostPromise {
334
- jsi::Runtime *runtime;
335
387
  jsi::WeakObject promise;
388
+ std::weak_ptr<async::RuntimeContext> context;
336
389
  };
337
390
  std::vector<PendingLostPromise> _lostPromises;
338
391
 
@@ -10,6 +10,7 @@
10
10
 
11
11
  #include "Convertors.h"
12
12
  #include "EnforceRange.h"
13
+ #include "GPUDevice.h"
13
14
  #include "ImageBitmap.h"
14
15
  #include "PlatformContext.h"
15
16
 
@@ -33,6 +34,12 @@ void GPUQueue::submit(
33
34
  return;
34
35
  }
35
36
  _instance.Submit(bufs_size, bufs.data());
37
+ // Now and then, what the pipelines compiled since the last flush added to
38
+ // Dawn's pipeline cache goes to the disk (see
39
+ // GPUDevice::flushPipelineCacheIfDue).
40
+ if (auto device = _deviceHost.lock()) {
41
+ device->flushPipelineCacheIfDue();
42
+ }
36
43
  }
37
44
 
38
45
  void GPUQueue::writeBuffer(std::shared_ptr<GPUBuffer> buffer,
@@ -94,8 +101,8 @@ async::AsyncTaskHandle GPUQueue::onSubmittedWorkDone(jsi::Runtime &runtime) {
94
101
  return context->postTask(
95
102
  [queue](const async::AsyncTaskHandle::ResolveFunction &resolve,
96
103
  const async::AsyncTaskHandle::RejectFunction &reject) {
97
- queue.OnSubmittedWorkDone(
98
- wgpu::CallbackMode::AllowProcessEvents,
104
+ return queue.OnSubmittedWorkDone(
105
+ wgpu::CallbackMode::WaitAnyOnly,
99
106
  [resolve, reject](wgpu::QueueWorkDoneStatus status,
100
107
  wgpu::StringView message) {
101
108
  if (status == wgpu::QueueWorkDoneStatus::Success) {
@@ -531,6 +538,8 @@ async::AsyncTaskHandle GPUQueue::drawElementImageToTexture(
531
538
  });
532
539
  },
533
540
  [reject](std::string error) { reject(std::move(error)); });
541
+ // Not Dawn's work: nothing to wait for, the snapshot calls back.
542
+ return std::nullopt;
534
543
  });
535
544
  }
536
545
 
@@ -27,6 +27,8 @@ namespace rnwgpu {
27
27
 
28
28
  namespace jsi = facebook::jsi;
29
29
 
30
+ class GPUDevice;
31
+
30
32
  class GPUQueue : public NativeObject<GPUQueue> {
31
33
  public:
32
34
  static constexpr const char *CLASS_NAME = "GPUQueue";
@@ -34,10 +36,10 @@ public:
34
36
  explicit GPUQueue(wgpu::Device device, wgpu::Queue instance,
35
37
  std::shared_ptr<async::RuntimeContext> async,
36
38
  std::shared_ptr<VideoFrameBlit> videoFrameBlit,
37
- std::string label)
39
+ std::string label, std::weak_ptr<GPUDevice> deviceHost)
38
40
  : NativeObject(CLASS_NAME), _device(device), _instance(instance),
39
41
  _async(async), _videoFrameBlit(std::move(videoFrameBlit)),
40
- _label(label) {}
42
+ _label(label), _deviceHost(std::move(deviceHost)) {}
41
43
 
42
44
  public:
43
45
  std::string getBrand() { return CLASS_NAME; }
@@ -104,6 +106,9 @@ private:
104
106
  std::shared_ptr<async::RuntimeContext> _async;
105
107
  std::shared_ptr<VideoFrameBlit> _videoFrameBlit;
106
108
  std::string _label;
109
+ // The device's wrapper, which submit() has flush its pipeline cache now and
110
+ // then.
111
+ std::weak_ptr<GPUDevice> _deviceHost;
107
112
  };
108
113
 
109
114
  } // namespace rnwgpu
@@ -19,8 +19,8 @@ GPUShaderModule::getCompilationInfo(jsi::Runtime &runtime) {
19
19
  [module](const async::AsyncTaskHandle::ResolveFunction &resolve,
20
20
  const async::AsyncTaskHandle::RejectFunction &reject) {
21
21
  auto result = std::make_shared<GPUCompilationInfo>();
22
- module.GetCompilationInfo(
23
- wgpu::CallbackMode::AllowProcessEvents,
22
+ return module.GetCompilationInfo(
23
+ wgpu::CallbackMode::WaitAnyOnly,
24
24
  [result, resolve,
25
25
  reject](wgpu::CompilationInfoRequestStatus status,
26
26
  const wgpu::CompilationInfo *compilationInfo) {