react-native-webgpu 0.20.0 → 0.21.1

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.
@@ -55,6 +55,7 @@ add_library(${PACKAGE_NAME} SHARED
55
55
  ../cpp/rnwgpu/api/GPUComputePassEncoder.cpp
56
56
  ../cpp/rnwgpu/api/GPUComputePipeline.cpp
57
57
  ../cpp/rnwgpu/api/GPUCanvasContext.cpp
58
+ ../cpp/rnwgpu/DawnBlobCache.cpp
58
59
  ../cpp/rnwgpu/RNWebGPUManager.cpp
59
60
  ../cpp/rnwgpu/WebGPURuntime.cpp
60
61
  ../cpp/jsi/Promise.cpp
@@ -21,7 +21,9 @@
21
21
  #include <webgpu/webgpu_cpp.h>
22
22
 
23
23
  #include "AndroidPlatformContext.h"
24
+ #include "DawnBlobCache.h"
24
25
  #include "GPUCanvasContext.h"
26
+ #include "GPUDevice.h"
25
27
  #include "RNWebGPUManager.h"
26
28
  #include "WebGPURuntime.h"
27
29
 
@@ -31,8 +33,18 @@ std::shared_ptr<rnwgpu::RNWebGPUManager> manager;
31
33
 
32
34
  extern "C" JNIEXPORT void JNICALL Java_com_webgpu_WebGPUModule_initializeNative(
33
35
  JNIEnv *env, jobject thiz, jlong jsRuntime, jobject jsCallInvokerHolder,
34
- jobject blobModule) {
36
+ jobject blobModule, jstring cacheDirectory) {
35
37
  auto runtime = reinterpret_cast<facebook::jsi::Runtime *>(jsRuntime);
38
+ if (cacheDirectory != nullptr) {
39
+ const char *path = env->GetStringUTFChars(cacheDirectory, nullptr);
40
+ if (path == nullptr) {
41
+ // The JVM could not copy the string, and an OutOfMemoryError is pending:
42
+ // no further JNI call is allowed, so let it reach the caller.
43
+ return;
44
+ }
45
+ rnwgpu::DawnBlobCache::setDirectory(path);
46
+ env->ReleaseStringUTFChars(cacheDirectory, path);
47
+ }
36
48
  jobject globalBlobModule = env->NewGlobalRef(blobModule);
37
49
  jobject globalModule = env->NewGlobalRef(thiz);
38
50
  auto jsCallInvoker{
@@ -45,6 +57,16 @@ extern "C" JNIEXPORT void JNICALL Java_com_webgpu_WebGPUModule_initializeNative(
45
57
  platformContext);
46
58
  }
47
59
 
60
+ // WebGPUModule.onHostPause (UI thread): the app is going to the background,
61
+ // the last moment to write what Dawn's pipeline caches hold before the process
62
+ // may be killed. Each device flushes here, or on the thread of its own runtime
63
+ // when it does not synchronize itself.
64
+ extern "C" JNIEXPORT void JNICALL
65
+ Java_com_webgpu_WebGPUModule_flushPipelineCaches(JNIEnv * /* env */,
66
+ jobject /* this */) {
67
+ rnwgpu::GPUDevice::flushPipelineCaches();
68
+ }
69
+
48
70
  // Completion of WebGPUModule.snapshotView (UI thread). Reclaims the callbacks
49
71
  // handed to Java and delivers either the bitmap's pixels or the error.
50
72
  extern "C" JNIEXPORT void JNICALL Java_com_webgpu_WebGPUModule_onViewSnapshot(
@@ -8,12 +8,14 @@ import android.view.View;
8
8
 
9
9
  import androidx.annotation.OptIn;
10
10
 
11
+ import java.io.File;
11
12
  import java.util.HashSet;
12
13
  import java.util.Set;
13
14
 
14
15
  import com.facebook.proguard.annotations.DoNotStrip;
15
16
  import com.facebook.react.bridge.ReactApplicationContext;
16
17
  import com.facebook.react.bridge.JavaScriptContextHolder;
18
+ import com.facebook.react.bridge.LifecycleEventListener;
17
19
  import com.facebook.react.bridge.ReactMethod;
18
20
  import com.facebook.react.bridge.UIManager;
19
21
  import com.facebook.react.bridge.UiThreadUtil;
@@ -26,7 +28,7 @@ import com.facebook.react.turbomodule.core.CallInvokerHolderImpl;
26
28
  import com.facebook.react.turbomodule.core.interfaces.CallInvokerHolder;
27
29
 
28
30
  @ReactModule(name = WebGPUModule.NAME)
29
- public class WebGPUModule extends NativeWebGPUModuleSpec {
31
+ public class WebGPUModule extends NativeWebGPUModuleSpec implements LifecycleEventListener {
30
32
  static {
31
33
  System.loadLibrary("react-native-webgpu"); // Load the C++ library
32
34
  }
@@ -35,8 +37,34 @@ public class WebGPUModule extends NativeWebGPUModuleSpec {
35
37
  super(reactContext);
36
38
  // Initialize the C++ module
37
39
  initialize();
40
+ reactContext.addLifecycleEventListener(this);
38
41
  }
39
42
 
43
+ @Override
44
+ public void invalidate() {
45
+ getReactApplicationContext().removeLifecycleEventListener(this);
46
+ super.invalidate();
47
+ }
48
+
49
+ @Override
50
+ public void onHostResume() {}
51
+
52
+ /**
53
+ * The app is going to the background: the last moment to write what Dawn's
54
+ * pipeline caches hold before the process may be killed (see
55
+ * GPUDevice::flushPipelineCaches).
56
+ */
57
+ @Override
58
+ public void onHostPause() {
59
+ flushPipelineCaches();
60
+ }
61
+
62
+ @Override
63
+ public void onHostDestroy() {}
64
+
65
+ @DoNotStrip
66
+ private native void flushPipelineCaches();
67
+
40
68
  @OptIn(markerClass = FrameworkAPI.class)
41
69
  @ReactMethod(isBlockingSynchronousMethod = true)
42
70
  public boolean install() {
@@ -47,13 +75,16 @@ public class WebGPUModule extends NativeWebGPUModuleSpec {
47
75
  if (blobModule == null) {
48
76
  throw new RuntimeException("React Native's BlobModule was not found!");
49
77
  }
50
- initializeNative(jsContext.get(), (CallInvokerHolderImpl) callInvokerHolder, blobModule);
78
+ // Dawn keeps the pipelines it compiles here, so a relaunch does not
79
+ // compile them again (see DawnBlobCache).
80
+ String cacheDirectory = new File(context.getCacheDir(), "webgpu-dawn").getAbsolutePath();
81
+ initializeNative(jsContext.get(), (CallInvokerHolderImpl) callInvokerHolder, blobModule, cacheDirectory);
51
82
  return true;
52
83
  }
53
84
 
54
85
  @OptIn(markerClass = FrameworkAPI.class)
55
86
  @DoNotStrip
56
- private native void initializeNative(long jsRuntime, CallInvokerHolderImpl jsInvoker, BlobModule blobModule);
87
+ private native void initializeNative(long jsRuntime, CallInvokerHolderImpl jsInvoker, BlobModule blobModule, String cacheDirectory);
57
88
 
58
89
  /**
59
90
  * Called from C++ (AndroidPlatformContext::snapshotView) on an arbitrary
@@ -141,6 +141,15 @@ public:
141
141
  // The metadata loads asynchronously, so that a remote asset never blocks
142
142
  // the calling thread; the getters report 0 until it has.
143
143
  AVAsset *asset = item.asset;
144
+ void (^readVideoTrack)(AVAssetTrack *) = ^(AVAssetTrack *track) {
145
+ if (track) {
146
+ CGSize size = track.naturalSize;
147
+ state->width = static_cast<uint32_t>(size.width);
148
+ state->height = static_cast<uint32_t>(size.height);
149
+ state->rotation = rotationFromTransform(track.preferredTransform);
150
+ state->frameRate = track.nominalFrameRate;
151
+ }
152
+ };
144
153
  #pragma clang diagnostic push
145
154
  #pragma clang diagnostic ignored "-Wdeprecated-declarations"
146
155
  [asset
@@ -155,17 +164,18 @@ public:
155
164
  }
156
165
  if ([asset statusOfValueForKey:@"tracks" error:nil] ==
157
166
  AVKeyValueStatusLoaded) {
158
- AVAssetTrack *track =
159
- [[asset tracksWithMediaType:AVMediaTypeVideo]
160
- firstObject];
161
- if (track) {
162
- CGSize size = track.naturalSize;
163
- state->width = static_cast<uint32_t>(size.width);
164
- state->height = static_cast<uint32_t>(size.height);
165
- state->rotation =
166
- rotationFromTransform(track.preferredTransform);
167
- state->frameRate = track.nominalFrameRate;
168
- }
167
+ #if TARGET_OS_VISION
168
+ // tracksWithMediaType: is unavailable on visionOS.
169
+ [asset loadTracksWithMediaType:AVMediaTypeVideo
170
+ completionHandler:^(
171
+ NSArray<AVAssetTrack *> *tracks,
172
+ NSError * /*error*/) {
173
+ readVideoTrack(tracks.firstObject);
174
+ }];
175
+ #else
176
+ readVideoTrack(
177
+ [[asset tracksWithMediaType:AVMediaTypeVideo] firstObject]);
178
+ #endif
169
179
  }
170
180
  }];
171
181
  #pragma clang diagnostic pop
@@ -54,11 +54,18 @@ void applyCAMetalLayerColorSpace(void *nativeSurface,
54
54
  }
55
55
  const bool extendedRange =
56
56
  isFloat && toneMappingMode == CanvasToneMappingMode::Extended;
57
- if (@available(iOS 16.0, tvOS 16.0, *)) {
57
+ // The property does not exist on tvOS (the SDK marks it unavailable, which
58
+ // @available cannot work around), so it is compiled only where it exists.
59
+ // On tvOS "extended" behaves like "standard".
60
+ #if TARGET_OS_IOS || TARGET_OS_OSX || TARGET_OS_VISION
61
+ if (@available(iOS 16.0, macOS 10.11, visionOS 1.0, *)) {
58
62
  if (metalLayer.wantsExtendedDynamicRangeContent != extendedRange) {
59
63
  metalLayer.wantsExtendedDynamicRangeContent = extendedRange;
60
64
  }
61
65
  }
66
+ #else
67
+ (void)extendedRange;
68
+ #endif
62
69
  // The change must be set synchronously so the first present already sees
63
70
  // it, and it must reach the render server. On a non-main thread (RN JS or
64
71
  // worklet runtime) the property lands in that thread's implicit
@@ -1,5 +1,6 @@
1
1
  #import "WebGPUModule.h"
2
2
  #include "ApplePlatformContext.h"
3
+ #include "DawnBlobCache.h"
3
4
  #import "GPUCanvasContext.h"
4
5
  #import "RNWGUIKit.h"
5
6
 
@@ -109,6 +110,20 @@ RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(install) {
109
110
  std::shared_ptr<rnwgpu::PlatformContext> platformContext =
110
111
  std::make_shared<rnwgpu::ApplePlatformContext>(
111
112
  std::move(viewLookup), std::move(blobManagerLookup));
113
+ // Dawn keeps the pipelines it compiles here, so a relaunch does not compile
114
+ // them again (see DawnBlobCache). The caches directory is per app on iOS but
115
+ // shared on macOS, hence the bundle identifier.
116
+ NSString *caches = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,
117
+ NSUserDomainMask, YES)
118
+ .firstObject;
119
+ NSString *bundle = NSBundle.mainBundle.bundleIdentifier;
120
+ if (caches != nil) {
121
+ if (bundle != nil) {
122
+ caches = [caches stringByAppendingPathComponent:bundle];
123
+ }
124
+ rnwgpu::DawnBlobCache::setDirectory(
125
+ [caches stringByAppendingPathComponent:@"webgpu-dawn"].UTF8String);
126
+ }
112
127
  webgpuManager = std::make_shared<rnwgpu::RNWebGPUManager>(runtime, jsInvoker,
113
128
  platformContext);
114
129
  return @true;
@@ -0,0 +1,477 @@
1
+ #include "DawnBlobCache.h"
2
+
3
+ #include <dirent.h>
4
+ #include <sys/stat.h>
5
+ #include <unistd.h>
6
+
7
+ #include <chrono>
8
+ #include <condition_variable>
9
+ #include <cstdint>
10
+ #include <cstdio>
11
+ #include <cstring>
12
+ #include <ctime>
13
+ #include <deque>
14
+ #include <functional>
15
+ #include <mutex>
16
+ #include <string>
17
+ #include <system_error>
18
+ #include <thread>
19
+ #include <utility>
20
+ #include <vector>
21
+
22
+ namespace rnwgpu {
23
+
24
+ namespace {
25
+
26
+ // Entries only accumulate as an app's shaders change from release to release.
27
+ // A cache found past this size when it is set up is cleared, and a session
28
+ // whose stores would take it past this size drops them until the next setup.
29
+ constexpr off_t kMaxCacheBytes = 64 * 1024 * 1024;
30
+
31
+ // An entry this large is not stored, so that one entry cannot take more than
32
+ // half the cache from all the others. The entry already on disk under its key,
33
+ // if any, is left as it is, and a blob that has outgrown this stops being
34
+ // updated.
35
+ constexpr off_t kMaxEntryBytes = kMaxCacheBytes / 2;
36
+
37
+ // A temporary file this old is taken for a write that will never finish (its
38
+ // process was killed). A younger one may still be being written by another
39
+ // process using the same cache, so it is left. A writer suspended for longer
40
+ // than this loses its entry (its rename fails), which only costs a cache miss.
41
+ constexpr time_t kAbandonedWriteSeconds = 60;
42
+
43
+ // Before a store is dropped for taking the cache past its limit, the
44
+ // directory is measured again, in case the entries counted so far are gone.
45
+ // Not before every one, though: a session at its limit may be refused a store
46
+ // per shader it compiles, and a measure reads every entry. The directory is
47
+ // measured again when its modification time changed since the last measure
48
+ // (an entry written to it or removed from it, by anyone, changes it) and, as
49
+ // that time can be coarse, when the last measure is this old.
50
+ constexpr std::chrono::seconds kMeasureAgainAfter{10};
51
+
52
+ // Never destroyed: a store can still be queued when the process starts to
53
+ // exit.
54
+ std::mutex &directoryMutex() {
55
+ static std::mutex *const mutex = new std::mutex;
56
+ return *mutex;
57
+ }
58
+
59
+ std::string &directorySlot() {
60
+ static std::string *const directory = new std::string;
61
+ return *directory;
62
+ }
63
+
64
+ std::string directory() {
65
+ std::lock_guard<std::mutex> lock(directoryMutex());
66
+ return directorySlot();
67
+ }
68
+
69
+ // Stores refused on this thread because the entry was too large. Dawn stores
70
+ // on the thread that has it write (see refusedStoresOnThisThread()).
71
+ thread_local uint64_t refusedStores = 0;
72
+
73
+ // Everything that changes the directory runs here, one job after another: the
74
+ // tidying of setDirectory() and the stores. Dawn stores from the thread that
75
+ // compiles, a JS thread included, and holds the device's lock while it stores
76
+ // its pipeline cache, so none of them should wait for the disk. Never
77
+ // destroyed, so a job queued as the process exits never runs into a destroyed
78
+ // queue; a write cut short by the exit leaves a temporary file the next setup
79
+ // removes.
80
+ class Writer {
81
+ public:
82
+ static Writer &shared() {
83
+ static Writer *const writer = new Writer;
84
+ return *writer;
85
+ }
86
+
87
+ // Queues `job` for the thread. Without a thread to be had (a process at its
88
+ // limit) the jobs queued so far are dropped, not run here: a store run on
89
+ // Dawn's thread would keep it waiting for the disk, and two run at once
90
+ // would write the same temporary file. The next post tries for a thread
91
+ // again, and the first store to run tidies the directory in place of the
92
+ // tidying dropped (see writeEntry).
93
+ void post(std::function<void()> job) {
94
+ std::lock_guard<std::mutex> lock(_mutex);
95
+ _queue.push_back(std::move(job));
96
+ if (!_started) {
97
+ try {
98
+ std::thread([this] { run(); }).detach();
99
+ _started = true;
100
+ } catch (const std::system_error &) {
101
+ _queue.clear();
102
+ return;
103
+ }
104
+ }
105
+ _wake.notify_one();
106
+ }
107
+
108
+ // Blocks until every job posted so far has run.
109
+ void wait() {
110
+ std::unique_lock<std::mutex> lock(_mutex);
111
+ _idle.wait(lock, [this] { return _queue.empty() && !_busy; });
112
+ }
113
+
114
+ // The directory last tidied, and the bytes of the entries in it: what the
115
+ // tidying found, plus what this session stored since. Read and written by
116
+ // jobs only.
117
+ std::string tidied;
118
+ off_t total = 0;
119
+
120
+ // When the directory was last measured: its modification time then, and the
121
+ // time (see kMeasureAgainAfter). Read and written by jobs only.
122
+ timespec measuredModification{};
123
+ std::chrono::steady_clock::time_point measuredAt{};
124
+
125
+ private:
126
+ void run() {
127
+ std::unique_lock<std::mutex> lock(_mutex);
128
+ for (;;) {
129
+ _wake.wait(lock, [this] { return !_queue.empty(); });
130
+ std::function<void()> job = std::move(_queue.front());
131
+ _queue.pop_front();
132
+ _busy = true;
133
+ lock.unlock();
134
+ try {
135
+ job();
136
+ } catch (...) {
137
+ // Out of memory, most likely. The cache is best effort, and a write
138
+ // cut short leaves a temporary file the next setup removes; on a
139
+ // detached thread the exception would end the process instead.
140
+ }
141
+ // Frees the job's copy of the blob before the queue is locked again.
142
+ job = nullptr;
143
+ lock.lock();
144
+ _busy = false;
145
+ if (_queue.empty()) {
146
+ _idle.notify_all();
147
+ }
148
+ }
149
+ }
150
+
151
+ std::mutex _mutex;
152
+ std::condition_variable _wake;
153
+ std::condition_variable _idle;
154
+ std::deque<std::function<void()>> _queue;
155
+ bool _started = false;
156
+ bool _busy = false;
157
+ };
158
+
159
+ // Creates `dir` and any of its parents that are missing.
160
+ void makeDirectories(const std::string &dir) {
161
+ for (size_t slash = dir.find('/', 1); slash != std::string::npos;
162
+ slash = dir.find('/', slash + 1)) {
163
+ mkdir(dir.substr(0, slash).c_str(), 0700);
164
+ }
165
+ mkdir(dir.c_str(), 0700);
166
+ }
167
+
168
+ // One file per entry, named by a 64-bit FNV-1a hash of its key.
169
+ std::string entryPath(const std::string &dir, size_t keySize,
170
+ const uint8_t *key) {
171
+ uint64_t hash = 14695981039346656037ull;
172
+ for (size_t i = 0; i < keySize; ++i) {
173
+ hash ^= key[i];
174
+ hash *= 1099511628211ull;
175
+ }
176
+ char name[18];
177
+ snprintf(name, sizeof(name), "/%016llx",
178
+ static_cast<unsigned long long>(hash));
179
+ return dir + name;
180
+ }
181
+
182
+ off_t entryBytes(size_t keySize, size_t valueSize) {
183
+ return static_cast<off_t>(2 * sizeof(uint64_t) + keySize + valueSize);
184
+ }
185
+
186
+ timespec modificationTime(const struct stat &info) {
187
+ #ifdef __APPLE__
188
+ return info.st_mtimespec;
189
+ #else
190
+ return info.st_mtim;
191
+ #endif
192
+ }
193
+
194
+ // What measure() found in the directory.
195
+ struct Contents {
196
+ std::vector<std::string> entries;
197
+ off_t bytes = 0;
198
+ };
199
+
200
+ Contents measure(const std::string &dir);
201
+ void tidy(const std::string &dir);
202
+
203
+ // Whether the directory may hold other entries than the last measure found:
204
+ // it was changed since, or is gone, or the measure is old enough for its
205
+ // modification time to be the same as then although it was changed (see
206
+ // kMeasureAgainAfter). Runs on the writer.
207
+ bool changedSinceMeasured(const std::string &dir) {
208
+ const Writer &writer = Writer::shared();
209
+ if (std::chrono::steady_clock::now() - writer.measuredAt >
210
+ kMeasureAgainAfter) {
211
+ return true;
212
+ }
213
+ struct stat info{};
214
+ if (stat(dir.c_str(), &info) != 0) {
215
+ return true;
216
+ }
217
+ const timespec modified = modificationTime(info);
218
+ return modified.tv_sec != writer.measuredModification.tv_sec ||
219
+ modified.tv_nsec != writer.measuredModification.tv_nsec;
220
+ }
221
+
222
+ // An entry is the key's size, the value's size, the key and the value. The
223
+ // stored key is compared on load, so a hash collision reads as a miss, and so
224
+ // does an entry shorter than its recorded size. Dawn asks for the size first
225
+ // (no buffer), then for the value.
226
+ size_t loadEntry(size_t keySize, const uint8_t *key, size_t valueSize,
227
+ uint8_t *value, void * /* userdata1 */,
228
+ void * /* userdata2 */) {
229
+ const std::string dir = directory();
230
+ if (dir.empty()) {
231
+ return 0;
232
+ }
233
+ FILE *file = fopen(entryPath(dir, keySize, key).c_str(), "rb");
234
+ if (file == nullptr) {
235
+ return 0;
236
+ }
237
+ size_t result = 0;
238
+ uint64_t sizes[2] = {0, 0};
239
+ if (fread(sizes, sizeof(sizes), 1, file) == 1 && sizes[0] == keySize) {
240
+ std::vector<uint8_t> storedKey(keySize);
241
+ if (fread(storedKey.data(), 1, keySize, file) == keySize &&
242
+ memcmp(storedKey.data(), key, keySize) == 0) {
243
+ const long start = ftell(file);
244
+ fseek(file, 0, SEEK_END);
245
+ const size_t stored = static_cast<size_t>(ftell(file) - start);
246
+ if (stored == sizes[1]) {
247
+ if (value == nullptr || valueSize == 0) {
248
+ result = stored;
249
+ } else if (valueSize >= stored) {
250
+ fseek(file, start, SEEK_SET);
251
+ result = fread(value, 1, stored, file) == stored ? stored : 0;
252
+ }
253
+ }
254
+ }
255
+ }
256
+ fclose(file);
257
+ return result;
258
+ }
259
+
260
+ // Written aside and renamed into place, so a load on another thread never
261
+ // sees half an entry. Runs on the writer.
262
+ void writeEntry(const std::string &dir, const std::vector<uint8_t> &key,
263
+ const std::vector<uint8_t> &value) {
264
+ Writer &writer = Writer::shared();
265
+ // The tidying of setDirectory() has not run for this directory: it was
266
+ // dropped for want of a thread then, or this store was queued ahead of it,
267
+ // or the store is bound for a directory set before the current one. Done
268
+ // now, so that the store is counted against its own directory.
269
+ if (writer.tidied != dir) {
270
+ tidy(dir);
271
+ }
272
+ const std::string path = entryPath(dir, key.size(), key.data());
273
+ const off_t bytes = entryBytes(key.size(), value.size());
274
+ struct stat replaced{};
275
+ const off_t previousBytes =
276
+ stat(path.c_str(), &replaced) == 0 ? replaced.st_size : 0;
277
+ if (previousBytes == 0) {
278
+ // A new entry, unless the system or the app cleared the cache directory,
279
+ // or its parent, during the session: then it has to be made again.
280
+ struct stat info{};
281
+ if (stat(dir.c_str(), &info) != 0) {
282
+ makeDirectories(dir);
283
+ }
284
+ }
285
+ // Past the limit the cache stops growing until the next setup clears it.
286
+ // Replacing an entry with one no larger is not growth: Dawn's monolithic
287
+ // pipeline cache is one entry stored over and over. Before a store is
288
+ // dropped the directory is measured again, if it may have changed, since
289
+ // the entries counted so far may be gone: the system clears app caches as
290
+ // it needs the space (iOS removes the files, not always the directory), and
291
+ // so may the app.
292
+ const off_t growth = bytes > previousBytes ? bytes - previousBytes : 0;
293
+ if (growth > 0 && writer.total + growth > kMaxCacheBytes) {
294
+ if (changedSinceMeasured(dir)) {
295
+ writer.total = measure(dir).bytes;
296
+ }
297
+ if (writer.total + growth > kMaxCacheBytes) {
298
+ return;
299
+ }
300
+ }
301
+ const std::string temporary = path + "." + std::to_string(getpid()) + ".tmp";
302
+ FILE *file = fopen(temporary.c_str(), "wb");
303
+ if (file == nullptr) {
304
+ return;
305
+ }
306
+ const uint64_t sizes[2] = {key.size(), value.size()};
307
+ bool written = fwrite(sizes, sizeof(sizes), 1, file) == 1 &&
308
+ fwrite(key.data(), 1, key.size(), file) == key.size() &&
309
+ fwrite(value.data(), 1, value.size(), file) == value.size();
310
+ written = fclose(file) == 0 && written;
311
+ if (!written || rename(temporary.c_str(), path.c_str()) != 0) {
312
+ remove(temporary.c_str());
313
+ return;
314
+ }
315
+ writer.total += bytes - previousBytes;
316
+ }
317
+
318
+ // Dawn's buffers last only for this call: the bytes are copied, and written
319
+ // later on the writer.
320
+ void storeEntry(size_t keySize, const uint8_t *key, size_t valueSize,
321
+ const uint8_t *value, void * /* userdata1 */,
322
+ void * /* userdata2 */) {
323
+ const std::string dir = directory();
324
+ if (dir.empty()) {
325
+ return;
326
+ }
327
+ if (entryBytes(keySize, valueSize) > kMaxEntryBytes) {
328
+ refusedStores++;
329
+ return;
330
+ }
331
+ Writer::shared().post(
332
+ [dir, key = std::vector<uint8_t>(key, key + keySize),
333
+ value = std::vector<uint8_t>(value, value + valueSize)] {
334
+ writeEntry(dir, key, value);
335
+ });
336
+ }
337
+
338
+ enum class Kind { Entry, Temporary, Other };
339
+
340
+ // An entry's name is 16 lowercase hex digits. A temporary file's is one
341
+ // followed by a dot, the writing process's id and ".tmp". Anything else in
342
+ // the directory is not the cache's to remove.
343
+ Kind kindOf(const std::string &name) {
344
+ if (name.size() < 16) {
345
+ return Kind::Other;
346
+ }
347
+ for (size_t i = 0; i < 16; i++) {
348
+ const char c = name[i];
349
+ if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'))) {
350
+ return Kind::Other;
351
+ }
352
+ }
353
+ if (name.size() == 16) {
354
+ return Kind::Entry;
355
+ }
356
+ if (name[16] != '.') {
357
+ return Kind::Other;
358
+ }
359
+ size_t i = 17;
360
+ while (i < name.size() && name[i] >= '0' && name[i] <= '9') {
361
+ i++;
362
+ }
363
+ return i > 17 && name.compare(i, std::string::npos, ".tmp") == 0
364
+ ? Kind::Temporary
365
+ : Kind::Other;
366
+ }
367
+
368
+ // Remembers the directory as measured now, as it is (see
369
+ // changedSinceMeasured). Runs on the writer.
370
+ void noteMeasured(const std::string &dir) {
371
+ Writer &writer = Writer::shared();
372
+ struct stat info{};
373
+ writer.measuredModification =
374
+ stat(dir.c_str(), &info) == 0 ? modificationTime(info) : timespec{};
375
+ writer.measuredAt = std::chrono::steady_clock::now();
376
+ }
377
+
378
+ // The entries in the directory and their bytes together: none when the
379
+ // directory is gone. Removes the temporary files of writes a killed process
380
+ // left unfinished on the way. Runs on the writer.
381
+ Contents measure(const std::string &dir) {
382
+ Contents contents;
383
+ if (DIR *listing = opendir(dir.c_str())) {
384
+ const time_t now = time(nullptr);
385
+ while (dirent *entry = readdir(listing)) {
386
+ const std::string name = entry->d_name;
387
+ const Kind kind = kindOf(name);
388
+ if (kind == Kind::Other) {
389
+ continue;
390
+ }
391
+ const std::string path = dir + "/" + name;
392
+ struct stat info{};
393
+ if (stat(path.c_str(), &info) != 0) {
394
+ continue;
395
+ }
396
+ if (kind == Kind::Temporary) {
397
+ if (now - info.st_mtime > kAbandonedWriteSeconds) {
398
+ remove(path.c_str());
399
+ }
400
+ continue;
401
+ }
402
+ contents.bytes += info.st_size;
403
+ contents.entries.push_back(path);
404
+ }
405
+ closedir(listing);
406
+ }
407
+ noteMeasured(dir);
408
+ return contents;
409
+ }
410
+
411
+ // Measures the directory, and removes every entry when together they are past
412
+ // kMaxCacheBytes: a cache that has outgrown the limit holds mostly what the
413
+ // app no longer uses, and one launch that builds everything is the price of
414
+ // starting over. Leaves the writer's total at what the directory holds. Runs
415
+ // on the writer.
416
+ void tidy(const std::string &dir) {
417
+ Writer &writer = Writer::shared();
418
+ Contents contents = measure(dir);
419
+ if (contents.bytes > kMaxCacheBytes) {
420
+ for (const auto &path : contents.entries) {
421
+ remove(path.c_str());
422
+ }
423
+ contents.bytes = 0;
424
+ noteMeasured(dir);
425
+ }
426
+ writer.total = contents.bytes;
427
+ writer.tidied = dir;
428
+ }
429
+
430
+ } // namespace
431
+
432
+ void DawnBlobCache::setDirectory(const std::string &dir) {
433
+ std::string usable = dir;
434
+ if (!usable.empty()) {
435
+ makeDirectories(usable);
436
+ struct stat info{};
437
+ if (stat(usable.c_str(), &info) != 0 || !S_ISDIR(info.st_mode)) {
438
+ // Nowhere to keep blobs: leave the cache off rather than fail every
439
+ // load and store.
440
+ usable.clear();
441
+ }
442
+ }
443
+ {
444
+ std::lock_guard<std::mutex> lock(directoryMutex());
445
+ directorySlot() = usable;
446
+ }
447
+ // Posted once the directory is in use, so that a store that reaches the
448
+ // writer first is bound for this directory, and counted by the tidying. A
449
+ // store still bound for the previous directory, queued after the tidying,
450
+ // is counted against that one (see writeEntry).
451
+ if (!usable.empty()) {
452
+ Writer::shared().post([usable] { tidy(usable); });
453
+ }
454
+ }
455
+
456
+ bool DawnBlobCache::chain(wgpu::DeviceDescriptor &descriptor,
457
+ WGPUDawnCacheDeviceDescriptor &storage) {
458
+ if (directory().empty()) {
459
+ return false;
460
+ }
461
+ storage.dawnLoadCacheDataCallbackInfo.callback = loadEntry;
462
+ storage.dawnStoreCacheDataCallbackInfo.callback = storeEntry;
463
+ storage.chain.next = reinterpret_cast<WGPUChainedStruct *>(
464
+ const_cast<wgpu::ChainedStruct *>(descriptor.nextInChain));
465
+ descriptor.nextInChain = reinterpret_cast<wgpu::ChainedStruct *>(&storage);
466
+ return true;
467
+ }
468
+
469
+ void DawnBlobCache::post(std::function<void()> job) {
470
+ Writer::shared().post(std::move(job));
471
+ }
472
+
473
+ uint64_t DawnBlobCache::refusedStoresOnThisThread() { return refusedStores; }
474
+
475
+ void DawnBlobCache::waitForWrites() { Writer::shared().wait(); }
476
+
477
+ } // namespace rnwgpu
@@ -0,0 +1,76 @@
1
+ #pragma once
2
+
3
+ #include <cstdint>
4
+ #include <functional>
5
+ #include <string>
6
+
7
+ #include "webgpu/webgpu_cpp.h"
8
+
9
+ namespace rnwgpu {
10
+
11
+ // Dawn's blob cache, kept on disk so what a device produces while building
12
+ // shaders and pipelines (Vulkan pipeline data, translated MSL) survives a
13
+ // relaunch. Dawn only reuses those blobs across launches when the embedder
14
+ // gives it storage: load and store callbacks on the device descriptor, or a
15
+ // caching interface on the platform the instance was created with (how Chrome
16
+ // does it). The instance can be React Native Skia's, so the callbacks go on
17
+ // each device. Without them every launch builds every pipeline from scratch,
18
+ // and on Vulkan drivers that can take a noticeable time per pipeline.
19
+ //
20
+ // Each platform's module points the cache at the app's cache directory when it
21
+ // installs, and requestDevice() chains it onto every device it creates. A
22
+ // device requested with the `disable_blob_cache` Dawn toggle does not use it.
23
+ //
24
+ // Loads read the file on the calling thread, since Dawn needs the bytes
25
+ // before it goes on. Stores copy the bytes and return: a thread of the cache's
26
+ // own writes them, so neither the thread Dawn compiles on (a JS thread
27
+ // included) nor a device lock Dawn holds while it stores waits for the disk.
28
+ //
29
+ // The cache is best effort. By default Dawn checks a hash of every blob it
30
+ // loads, and an entry that is torn, truncated or for another key reads as a
31
+ // miss. Entries are replaced whole, so the writer that finishes last wins:
32
+ // devices or processes that share a key (Dawn's monolithic Vulkan pipeline
33
+ // cache has one per device) can replace a fuller blob with a smaller one,
34
+ // which only costs the pipelines in it being built again.
35
+ class DawnBlobCache {
36
+ public:
37
+ // The directory to keep the blobs in, created (with its parents) if
38
+ // missing. Each platform's module calls this when it installs. The cache is
39
+ // then tidied on its own thread: abandoned writes are removed, and when the
40
+ // entries together are past the limit (about 64 MB) all of them are, so that
41
+ // a cache full of what the app no longer uses starts over, at the price of
42
+ // one launch that builds everything. A session whose stores would take the
43
+ // cache past the limit drops them (replacing an entry with one no larger is
44
+ // never dropped), and an entry larger than half the limit is not stored.
45
+ // Only the cache's own files are ever removed. An empty path, or one where
46
+ // no directory can be made, leaves the cache off.
47
+ static void setDirectory(const std::string &directory);
48
+
49
+ // Chains the cache onto `descriptor`, in front of whatever it already
50
+ // chains, and returns true. `storage` holds the chained struct and must
51
+ // outlive the RequestDevice call that reads it. Does nothing, and returns
52
+ // false, without a directory.
53
+ static bool chain(wgpu::DeviceDescriptor &descriptor,
54
+ WGPUDawnCacheDeviceDescriptor &storage);
55
+
56
+ // Runs `job` on the cache's thread, after the jobs queued so far (the
57
+ // tidying, the stores), or not at all when no thread can be had. GPUDevice
58
+ // has Dawn write a device's pipeline cache there (flushPipelineCacheIfDue),
59
+ // so that the thread submitting a frame does not wait while Dawn serializes
60
+ // it.
61
+ static void post(std::function<void()> job);
62
+
63
+ // How many stores asked for on the calling thread the cache has refused
64
+ // because the entry was too large (see setDirectory). Dawn stores on the
65
+ // thread that has it write, so a flush (GPUDevice::flushPipelineCache) that
66
+ // sees this grow learns that the device's pipeline cache has outgrown what
67
+ // the cache keeps, and stops having Dawn serialize it.
68
+ static uint64_t refusedStoresOnThisThread();
69
+
70
+ // Blocks until the cache's thread has done everything asked of it so far:
71
+ // the tidying of setDirectory(), the stores and the posted jobs. Nothing in
72
+ // an app needs to wait for a write; tests do.
73
+ static void waitForWrites();
74
+ };
75
+
76
+ } // namespace rnwgpu
@@ -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"};
@@ -305,6 +307,12 @@ async::AsyncTaskHandle GPUAdapter::requestDevice(
305
307
  toggles.disabledToggles = disabledToggles.data();
306
308
  deviceDesc.nextInChain = &toggles;
307
309
  }
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);
308
316
  return _instance.RequestDevice(
309
317
  &deviceDesc, wgpu::CallbackMode::WaitAnyOnly,
310
318
  [context, resolve, reject, label, creationRuntime,
@@ -355,13 +363,15 @@ async::AsyncTaskHandle GPUAdapter::requestDevice(
355
363
  },
356
364
  creationRuntime);
357
365
 
358
- auto deviceHost = std::make_shared<GPUDevice>(std::move(device),
359
- context, label);
366
+ auto deviceHost =
367
+ std::make_shared<GPUDevice>(std::move(device), context, label,
368
+ GPUDevice::Origin::Requested);
360
369
  *deviceLostBinding = deviceHost;
361
370
 
362
371
  // Register the device in the static registry so the uncaptured
363
372
  // error callback can find it
364
- GPUDevice::registerDevice(deviceHost->get().Get(), deviceHost);
373
+ GPUDevice::registerDevice(deviceHost->get().Get(),
374
+ deviceHost.get());
365
375
 
366
376
  resolve([deviceHost = std::move(deviceHost)](
367
377
  jsi::Runtime &runtime) mutable {
@@ -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;
@@ -137,7 +260,7 @@ std::shared_ptr<GPUAdapterInfo> GPUDevice::getAdapterInfo() {
137
260
  std::shared_ptr<GPUQueue> GPUDevice::getQueue() {
138
261
  auto result = _instance.GetQueue();
139
262
  return std::make_shared<GPUQueue>(_instance, result, _async, _videoFrameBlit,
140
- _label);
263
+ _label, weak_from_this());
141
264
  }
142
265
 
143
266
  std::shared_ptr<GPUCommandEncoder> GPUDevice::createCommandEncoder(
@@ -154,6 +277,9 @@ std::shared_ptr<GPUCommandEncoder> GPUDevice::createCommandEncoder(
154
277
  }
155
278
 
156
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();
157
283
  // DAWN_WORKAROUND_DEVICE_DESTROY_BEFORE_SURFACE_RELEASE
158
284
  // Any canvas surface holding a swapchain for this device must let go of it
159
285
  // while the device is alive (see SurfaceInfo::releaseSurfaceForDevice).
@@ -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,6 +307,40 @@ 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
 
@@ -308,6 +351,17 @@ private:
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.
@@ -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,
@@ -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
@@ -148,7 +148,8 @@ public:
148
148
  wgpu::Device device = wgpu::Device::Acquire(raw);
149
149
  auto ctx = async::RuntimeContext::getOrCreate(
150
150
  runtime, device.GetAdapter().GetInstance());
151
- return std::make_shared<GPUDevice>(device, ctx, "Imported Device");
151
+ return std::make_shared<GPUDevice>(device, ctx, "Imported Device",
152
+ GPUDevice::Origin::Imported);
152
153
  }
153
154
 
154
155
  // Wrap an externally created WGPUTexture in a GPUTexture, TAKING OWNERSHIP
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-native-webgpu",
3
- "version": "0.20.0",
3
+ "version": "0.21.1",
4
4
  "description": "React Native WebGPU",
5
5
  "main": "lib/commonjs/index",
6
6
  "module": "lib/module/index",
@@ -31,6 +31,7 @@
31
31
  "test:ref": "REFERENCE=true NODE_OPTIONS='--experimental-require-module' jest -i",
32
32
  "test:node": "NODE_WEBGPU=true NODE_OPTIONS='--experimental-require-module' jest -i",
33
33
  "test:plugin": "jest -c plugin/jest.config.js",
34
+ "test:cpp": "cmake -S tests/cpp -B node_modules/.cache/cpp-tests && cmake --build node_modules/.cache/cpp-tests --parallel && ctest --test-dir node_modules/.cache/cpp-tests --output-on-failure",
34
35
  "lint": "eslint . --ext .ts,.tsx --max-warnings 0 --cache --fix",
35
36
  "tsc": "tsc --noEmit",
36
37
  "build": "bob build && yarn build:plugin",
@@ -40,7 +41,7 @@
40
41
  "clang-format-ios": "find apple/ -iname \"*.h\" -o -iname \"*.mm\" -o -iname \"*.cpp\" | xargs clang-format -i",
41
42
  "clang-format-android": "find android/cpp/ -iname \"*.h\" -o -iname \"*.m\" -o -iname \"*.cpp\" | xargs clang-format -i",
42
43
  "clang-format-common": "find cpp/rnwgpu -iname \"*.h\" -o -iname \"*.m\" -o -iname \"*.cpp\" | xargs clang-format -i",
43
- "cpplint": "cpplint --linelength=230 --filter=-legal/copyright,-whitespace/indent,-whitespace/comments,-whitespace/ending_newline,-build/include_order,-runtime/references,-readability/todo,-whitespace/blank_line,-whitespace/todo,-runtime/int,-build/c++11,-whitespace/parens --exclude=example --exclude=android/.cxx --exclude=cpp/webgpu --exclude=cpp/dawn --exclude=ios --exclude=android/build --exclude=node_modules --recursive .",
44
+ "cpplint": "cpplint --linelength=230 --filter=-legal/copyright,-whitespace/indent,-whitespace/comments,-whitespace/ending_newline,-build/include_order,-runtime/references,-readability/todo,-whitespace/blank_line,-whitespace/todo,-runtime/int,-build/c++11,-whitespace/parens --exclude=android/.cxx --exclude=cpp/dawn --exclude=libs --exclude=android/build --exclude=node_modules --recursive .",
44
45
  "check-dawn": "tsx scripts/check-dawn.ts"
45
46
  },
46
47
  "keywords": [
@@ -79,9 +80,7 @@
79
80
  "@types/seedrandom": "^3.0.8",
80
81
  "@types/ws": "^8.5.10",
81
82
  "@webgpu/types": "0.1.65",
82
- "baseline-browser-mapping": "^2.9.14",
83
83
  "clang-format": "^1.8.0",
84
- "del-cli": "^5.1.0",
85
84
  "eslint": "9.35.0",
86
85
  "eslint-config-react-native-wcandillon": "5.0.1",
87
86
  "eslint-plugin-import": "2.32.0",
@@ -98,7 +97,6 @@
98
97
  "react-native-reanimated": "4.6.0",
99
98
  "react-native-web": "^0.21.2",
100
99
  "react-native-worklets": "0.12.2",
101
- "rimraf": "^5.0.7",
102
100
  "seedrandom": "^3.0.5",
103
101
  "semantic-release": "^25.0.9",
104
102
  "semantic-release-yarn": "^3.0.2",
@@ -107,8 +105,7 @@
107
105
  "typescript": "^5.2.2",
108
106
  "webgpu": "0.4.0",
109
107
  "wgpu-matrix": "^3.0.2",
110
- "ws": "^8.18.0",
111
- "yargs": "^17.7.2"
108
+ "ws": "^8.18.0"
112
109
  },
113
110
  "dependencies": {
114
111
  "react-native-webgpu-dawn": "157.1.0"
@@ -47,7 +47,17 @@ Pod::Spec.new do |s|
47
47
  s.license = package["license"]
48
48
  s.authors = package["author"]
49
49
 
50
- s.platforms = { :ios => min_ios_version_supported, :osx => "10.15", :visionos => "1.0" }
50
+ # React Native's CocoaPods autolinking drops any pod whose podspec does not
51
+ # declare the Podfile target's platform (#608), so every platform the Dawn
52
+ # xcframework ships a slice for is listed. react-native-tvos keeps the tvOS
53
+ # floor equal to the iOS one (its min_supported_versions helper). visionOS
54
+ # is not listed: react-native-webgpu-dawn ships no xros slice, so a visionOS
55
+ # target would autolink the pod and then fail to link it.
56
+ s.platforms = {
57
+ :ios => min_ios_version_supported,
58
+ :tvos => min_ios_version_supported,
59
+ :osx => "10.15",
60
+ }
51
61
  s.source = { :git => "https://github.com/wcandillon/react-native-webgpu.git", :tag => "#{s.version}" }
52
62
 
53
63
  # CocoaPods is the supported default. Package.swift (React Native 0.87+