diff --git a/packages/webgpu/android/CMakeLists.txt b/packages/webgpu/android/CMakeLists.txt index 758586514a..4bc2869df5 100644 --- a/packages/webgpu/android/CMakeLists.txt +++ b/packages/webgpu/android/CMakeLists.txt @@ -56,6 +56,7 @@ add_library(${PACKAGE_NAME} SHARED ../cpp/rnwgpu/api/GPUComputePipeline.cpp ../cpp/rnwgpu/api/GPUCanvasContext.cpp ../cpp/rnwgpu/DawnBlobCache.cpp + ../cpp/rnwgpu/GpuPurge.cpp ../cpp/rnwgpu/NativeBufferViewRegistry.cpp ../cpp/rnwgpu/AnimationFrames.cpp ../cpp/rnwgpu/RNWebGPUManager.cpp diff --git a/packages/webgpu/android/cpp/cpp-adapter.cpp b/packages/webgpu/android/cpp/cpp-adapter.cpp index 93a93042b6..03112b7200 100644 --- a/packages/webgpu/android/cpp/cpp-adapter.cpp +++ b/packages/webgpu/android/cpp/cpp-adapter.cpp @@ -25,6 +25,7 @@ #include "DawnBlobCache.h" #include "GPUCanvasContext.h" #include "GPUDevice.h" +#include "GpuPurge.h" #include "NativeBufferViewRegistry.h" #include "RNWebGPUManager.h" #include "WebGPURuntime.h" @@ -70,6 +71,21 @@ Java_com_webgpu_WebGPUModule_flushPipelineCaches(JNIEnv * /* env */, rnwgpu::GPUDevice::flushPipelineCaches(); } +// WebGPUModule's ComponentCallbacks2 (UI thread): what the system says about +// memory, as it says it. GpuPurge decides what calls for a purge. +extern "C" JNIEXPORT void JNICALL +Java_com_webgpu_WebGPUModule_onLowMemoryNative(JNIEnv * /* env */, + jclass /* clazz */) { + rnwgpu::GpuPurge::onLowMemory(); +} + +extern "C" JNIEXPORT void JNICALL +Java_com_webgpu_WebGPUModule_onTrimMemoryNative(JNIEnv * /* env */, + jclass /* clazz */, + jint level) { + rnwgpu::GpuPurge::onTrimMemory(level); +} + // WebGPUModule.onHostResume and onHostPause (UI thread): animation frames // follow the host activity, resumed or not. extern "C" JNIEXPORT void JNICALL diff --git a/packages/webgpu/android/src/main/java/com/webgpu/WebGPUModule.java b/packages/webgpu/android/src/main/java/com/webgpu/WebGPUModule.java index a4a8557c7f..e5d0c55f5d 100644 --- a/packages/webgpu/android/src/main/java/com/webgpu/WebGPUModule.java +++ b/packages/webgpu/android/src/main/java/com/webgpu/WebGPUModule.java @@ -1,5 +1,7 @@ package com.webgpu; +import android.content.ComponentCallbacks2; +import android.content.res.Configuration; import android.graphics.Bitmap; import android.hardware.HardwareBuffer; import android.os.Build; @@ -34,6 +36,25 @@ public class WebGPUModule extends NativeWebGPUModuleSpec implements LifecycleEve System.loadLibrary("react-native-webgpu"); // Load the C++ library } + // What the system says about memory goes to the native side as it comes, + // which decides when the GPU memory nothing uses goes back to the system + // (see GpuPurge). + private final ComponentCallbacks2 mComponentCallbacks = + new ComponentCallbacks2() { + @Override + public void onConfigurationChanged(Configuration newConfig) {} + + @Override + public void onLowMemory() { + onLowMemoryNative(); + } + + @Override + public void onTrimMemory(int level) { + onTrimMemoryNative(level); + } + }; + public WebGPUModule(ReactApplicationContext reactContext) { super(reactContext); // Initialize the C++ module @@ -41,11 +62,15 @@ public WebGPUModule(ReactApplicationContext reactContext) { // Animation frames follow the host activity: resumed, or not. setForegroundNative(reactContext.getLifecycleState() == LifecycleState.RESUMED); reactContext.addLifecycleEventListener(this); + reactContext.getApplicationContext().registerComponentCallbacks(mComponentCallbacks); } @Override public void invalidate() { getReactApplicationContext().removeLifecycleEventListener(this); + getReactApplicationContext() + .getApplicationContext() + .unregisterComponentCallbacks(mComponentCallbacks); super.invalidate(); } @@ -72,6 +97,12 @@ public void onHostDestroy() {} @DoNotStrip private native void flushPipelineCaches(); + @DoNotStrip + private static native void onLowMemoryNative(); + + @DoNotStrip + private static native void onTrimMemoryNative(int level); + /** * Whether the app is in the foreground: the host activity is resumed (see * AnimationFrameDispatcher::setForeground). An AChoreographer sends its diff --git a/packages/webgpu/apple/WebGPUModule.mm b/packages/webgpu/apple/WebGPUModule.mm index 4f75772294..2f7a3dfaf1 100644 --- a/packages/webgpu/apple/WebGPUModule.mm +++ b/packages/webgpu/apple/WebGPUModule.mm @@ -2,6 +2,7 @@ #include "ApplePlatformContext.h" #include "DawnBlobCache.h" #import "GPUCanvasContext.h" +#include "GpuPurge.h" #import "RNWGUIKit.h" #import @@ -22,6 +23,24 @@ @interface RCTBridge (JSIRuntime) - (void *)runtime; @end +#if !TARGET_OS_OSX +// A memory warning goes to the native side as it comes, which decides when the +// GPU memory nothing uses goes back to the system (see GpuPurge). Once for the +// process: devices outlive a React reload. +static void observeMemoryWarnings() { + static dispatch_once_t once; + dispatch_once(&once, ^{ + [[NSNotificationCenter defaultCenter] + addObserverForName:UIApplicationDidReceiveMemoryWarningNotification + object:nil + queue:nil + usingBlock:^(NSNotification *) { + rnwgpu::GpuPurge::onMemoryWarning(); + }]; + }); +} +#endif + @implementation WebGPUModule RCT_EXPORT_MODULE(WebGPUModule) @@ -149,6 +168,9 @@ - (void)invalidate { rnwgpu::DawnBlobCache::setDirectory( [caches stringByAppendingPathComponent:@"webgpu-dawn"].UTF8String); } +#if !TARGET_OS_OSX + observeMemoryWarnings(); +#endif webgpuManager = std::make_shared(runtime, jsInvoker, platformContext); return @true; diff --git a/packages/webgpu/cpp/rnwgpu/GpuPurge.cpp b/packages/webgpu/cpp/rnwgpu/GpuPurge.cpp new file mode 100644 index 0000000000..d041a7e9b8 --- /dev/null +++ b/packages/webgpu/cpp/rnwgpu/GpuPurge.cpp @@ -0,0 +1,86 @@ +#include "GpuPurge.h" + +#include +#include +#include + +#include "GPUDevice.h" + +namespace rnwgpu { + +namespace { + +struct State { + std::mutex mutex; + // Whether the purge thread is alive. + bool running = false; + // Whether a request came in since the thread last started a run. + bool requested = false; +}; + +// Never destroyed: the purge thread may still use it while the process exits. +State &getState() noexcept { + static auto *state = new State(); + return *state; +} + +} // namespace + +void GpuPurge::request() noexcept { + auto &state = getState(); + { + std::lock_guard lock(state.mutex); + state.requested = true; + if (state.running) { + return; + } + state.running = true; + } + try { + std::thread([] { runRequests(); }).detach(); + } catch (const std::system_error &) { + // No thread to be had: nothing is purged. + std::lock_guard lock(state.mutex); + state.running = false; + } +} + +void GpuPurge::onMemoryWarning() noexcept { request(); } + +void GpuPurge::onLowMemory() noexcept { request(); } + +void GpuPurge::onTrimMemory(int level) noexcept { + if (level >= kTrimMemoryUiHidden) { + request(); + } +} + +void GpuPurge::runRequests() noexcept { + auto &state = getState(); + for (;;) { + { + std::lock_guard lock(state.mutex); + if (!state.requested) { + state.running = false; + return; + } + state.requested = false; + } + run(); + } +} + +void GpuPurge::run() { + for (int pass = 0; pass < kMaxPasses; pass++) { + bool pending = GPUDevice::reduceMemoryUsage(); + if (pass < kRuntimeThreadPasses) { + pending |= GPUDevice::reduceMemoryUsageOnRuntimeThreads(); + } + if (!pending) { + return; + } + std::this_thread::sleep_for(kPassInterval); + } +} + +} // namespace rnwgpu diff --git a/packages/webgpu/cpp/rnwgpu/GpuPurge.h b/packages/webgpu/cpp/rnwgpu/GpuPurge.h new file mode 100644 index 0000000000..4dc80050ef --- /dev/null +++ b/packages/webgpu/cpp/rnwgpu/GpuPurge.h @@ -0,0 +1,66 @@ +#pragma once + +#include + +namespace rnwgpu { + +// purgeGpuResources(), which the system also brings about when it is short of +// memory and, on Android, when the app goes to the background: Dawn gives the +// GPU memory it keeps for reuse (the memory of destroyed textures and buffers, +// staging memory) back to the system, for every live device (see +// GPUDevice::reduceMemoryUsage). Nothing alive is affected. +// +// The platform modules only report what the system said (onMemoryWarning, +// onLowMemory, onTrimMemory): whether it calls for a purge is decided here. +// +// request() returns at once. The work runs on a thread of its own, started by +// a request and gone once done; a request made while it runs is served by one +// more run of the same thread, however many came in. +class GpuPurge { +public: + // purgeGpuResources() from JS. Any thread. + static void request() noexcept; + + // iOS, UIApplicationDidReceiveMemoryWarningNotification: the system is short + // of memory, and ends the apps that hold the most of it first. Any thread. + static void onMemoryWarning() noexcept; + + // Android, ComponentCallbacks.onLowMemory(): the whole system is short of + // memory. Any thread. + static void onLowMemory() noexcept; + + // Android, ComponentCallbacks2.onTrimMemory(): purges from + // kTrimMemoryUiHidden, which is each time the app goes to the background. + // Any thread. + static void onTrimMemory(int level) noexcept; + +private: + // One run asks Dawn again for as long as it says deletions wait for + // submitted work to complete, this many times at most and this far apart: + // about a second in all. + static constexpr int kMaxPasses = 10; + static constexpr std::chrono::milliseconds kPassInterval{100}; + + // The passes of a run that also ask the devices only the thread of their + // runtime may use (see GPUDevice::reduceMemoryUsageOnRuntimeThreads). What + // Dawn answers there is not waited for, hence a fixed number: the first lets + // the pending deletions go through, the next free what they leave. + static constexpr int kRuntimeThreadPasses = 3; + + // ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN: the app is no longer visible. It + // renders nothing there, and the system ends the processes in the background + // that hold the most memory first. The system sends it each time the app + // leaves the foreground, and it may be all it sends: TRIM_MEMORY_BACKGROUND + // did not come to an app left in the background until it was cached and + // frozen (a Samsung on Android 17). The levels below this one are for an app + // in the foreground, and are no longer sent since Android 14. + static constexpr int kTrimMemoryUiHidden = 20; + + // The purge thread: runs until no request is left. + static void runRequests() noexcept; + + // One run: the passes over the live devices. + static void run(); +}; + +} // namespace rnwgpu diff --git a/packages/webgpu/cpp/rnwgpu/api/GPUDevice.cpp b/packages/webgpu/cpp/rnwgpu/api/GPUDevice.cpp index f4464b1182..c35ced5389 100644 --- a/packages/webgpu/cpp/rnwgpu/api/GPUDevice.cpp +++ b/packages/webgpu/cpp/rnwgpu/api/GPUDevice.cpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include #include @@ -73,6 +74,18 @@ void flushDawnPipelineCache(const wgpu::Device &device, } } +// Has Dawn give the memory it keeps for reuse on a device back to the system. +// Returns whether deletions still wait for submitted work to complete. Dawn +// does nothing for a device that is lost or destroyed, which it checks with +// the device locked. Any thread that may use the device. +bool reduceDawnMemoryUsage(const wgpu::Device &device) { + // Not redundant with what ReduceMemoryUsage() does: it learns which work has + // completed but leaves what waits for that work to a tick, and an idle app + // does not tick. + device.Tick(); + return dawn::native::ReduceMemoryUsage(device.Get()); +} + } // namespace void GPUDevice::flushPipelineCache() { @@ -118,51 +131,38 @@ void GPUDevice::flushPipelineCacheIfDue() { flushPipelineCache(); } -void GPUDevice::flushPipelineCaches() { - // What flushing a device takes, copied out of its wrapper under the - // registry's mutex, rather than the wrapper itself: a strong reference to - // the wrapper released on this thread (the platform's UI thread) could be - // its last, and a wrapper, with its JSI members, must only go on its - // runtime's thread. - struct Flush { - wgpu::Device device; - std::shared_ptr> outgrown; - std::shared_ptr async; - std::weak_ptr wrapper; - }; - std::vector flushes; - { - std::lock_guard lock(getRegistryMutex()); - for (const auto &entry : getRegistry()) { - GPUDevice *device = entry.second; - // A wrapper on its way out (its last reference gone, its destructor - // about to unregister it) has nothing left to flush; nor has an - // imported device, whose owner keeps its cache. - if (device->_origin == Origin::Imported || - device->weak_from_this().expired()) { - continue; - } - flushes.push_back({device->_instance, device->_pipelineCacheOutgrown, - device->_async, device->weak_from_this()}); +std::vector GPUDevice::liveDevices() { + std::vector devices; + std::lock_guard lock(getRegistryMutex()); + for (const auto &entry : getRegistry()) { + GPUDevice *device = entry.second; + if (device->_origin == Origin::Imported || + device->weak_from_this().expired()) { + continue; } + devices.push_back({device->_instance, device->_pipelineCacheOutgrown, + device->_async, device->weak_from_this()}); } - for (const auto &flush : flushes) { + return devices; +} + +void GPUDevice::flushPipelineCaches() { + for (const auto &live : liveDevices()) { // Dawn locks a device that synchronizes itself around the flush, so this // thread can do it, and does: the runtime's thread may be busy, and a // runtime that polls its mailbox would hold the job until its next // operation, which may never come before the process is killed. - if (flush.device.HasFeature( - wgpu::FeatureName::ImplicitDeviceSynchronization)) { - flushDawnPipelineCache(flush.device, *flush.outgrown); + if (live.synchronizesItself()) { + flushDawnPipelineCache(live.device, *live.pipelineCacheOutgrown); continue; } - if (!flush.async) { + if (!live.async) { continue; } // A device used from its runtime's thread only is flushed there. Held // weakly: a device collected before its runtime gets to the job has // nothing left to flush, and the job must not keep it alive. - flush.async->post([weak = flush.wrapper](jsi::Runtime &) { + live.async->post([weak = live.wrapper](jsi::Runtime &) { if (auto device = weak.lock()) { device->flushPipelineCache(); } @@ -170,6 +170,33 @@ void GPUDevice::flushPipelineCaches() { } } +bool GPUDevice::reduceMemoryUsage() { + bool pending = false; + for (const auto &live : liveDevices()) { + if (live.synchronizesItself()) { + pending |= reduceDawnMemoryUsage(live.device); + } + } + return pending; +} + +bool GPUDevice::reduceMemoryUsageOnRuntimeThreads() { + bool asked = false; + for (const auto &live : liveDevices()) { + if (live.synchronizesItself() || !live.async) { + continue; + } + asked = true; + // Held weakly, as in flushPipelineCaches(). + live.async->post([weak = live.wrapper](jsi::Runtime &) { + if (auto device = weak.lock()) { + reduceDawnMemoryUsage(device->_instance); + } + }); + } + return asked; +} + void GPUDevice::notifyDeviceLost(wgpu::DeviceLostReason reason, std::string message) { std::vector toResolve; diff --git a/packages/webgpu/cpp/rnwgpu/api/GPUDevice.h b/packages/webgpu/cpp/rnwgpu/api/GPUDevice.h index 734f15adbf..bf3b268c10 100644 --- a/packages/webgpu/cpp/rnwgpu/api/GPUDevice.h +++ b/packages/webgpu/cpp/rnwgpu/api/GPUDevice.h @@ -109,15 +109,44 @@ class GPUDevice : public NativeObject { private: static std::unordered_map &getRegistry() { - static std::unordered_map registry; - return registry; + // Never destroyed: the purge thread (see GpuPurge) may still read it while + // the process exits. + static auto *registry = new std::unordered_map(); + return *registry; } static std::mutex &getRegistryMutex() { - static std::mutex mutex; - return mutex; + static auto *mutex = new std::mutex(); + return *mutex; } + // What a pass over the live devices (flushPipelineCaches, + // reduceMemoryUsage) takes from each wrapper, copied out under the + // registry's mutex rather than the wrapper itself: a strong reference to the + // wrapper released on the calling thread (the platform's UI thread, the + // purge thread) could be its last, and a wrapper, with its JSI members, must + // only go on its runtime's thread. + struct LiveDevice { + wgpu::Device device; + std::shared_ptr> pipelineCacheOutgrown; + std::shared_ptr async; + std::weak_ptr wrapper; + + // Whether Dawn locks the device around each call, so that any thread may + // use it (ImplicitDeviceSynchronization, the default). Only the thread of + // its runtime may otherwise. + bool synchronizesItself() const { + return device.HasFeature( + wgpu::FeatureName::ImplicitDeviceSynchronization); + } + }; + + // The devices made here that are still in use: not a wrapper on its way out + // (its last reference gone, its destructor about to unregister it), nor an + // imported device, which is its owner's to look after. Collected anew by + // each pass, so that no pass keeps a device alive for the next. Any thread. + static std::vector liveDevices(); + public: std::string getBrand() { return CLASS_NAME; } @@ -323,6 +352,22 @@ class GPUDevice : public NativeObject { // the last moment to write before the process may be killed. static void flushPipelineCaches(); + // One pass of Dawn's ReduceMemoryUsage() over the live devices that + // synchronize themselves (the default), on the calling thread: Dawn gives + // the GPU memory it keeps for reuse (the memory of destroyed textures and + // buffers, staging memory) back to the system. Nothing alive is affected. + // Returns whether Dawn still has deletions waiting for submitted work to + // complete, in which case another pass shortly frees more. An imported + // device is its owner's to purge. Any thread; GpuPurge decides when, and + // how many times. + static bool reduceMemoryUsage(); + + // The same pass for the live devices only the thread of their runtime may + // use: a job on that thread for each, which a runtime that polls its + // mailbox reaches with its next operation. Returns whether any was asked; + // what Dawn answers there is not waited for. Any thread. + static bool reduceMemoryUsageOnRuntimeThreads(); + private: friend class GPUAdapter; diff --git a/packages/webgpu/cpp/rnwgpu/api/RNWebGPU.h b/packages/webgpu/cpp/rnwgpu/api/RNWebGPU.h index 29428235d6..94a2fa2c93 100644 --- a/packages/webgpu/cpp/rnwgpu/api/RNWebGPU.h +++ b/packages/webgpu/cpp/rnwgpu/api/RNWebGPU.h @@ -19,6 +19,7 @@ #include "GPUDevice.h" #include "GPUSharedFenceState.h" #include "GPUTexture.h" +#include "GpuPurge.h" #include "ImageBitmap.h" #include "NativeBufferViewRegistry.h" #include "NativeFrameImport.h" @@ -558,6 +559,9 @@ class RNWebGPU : public NativeObject { registry.removeSurfaceInfoIfDetached(contextId); } + // See GpuPurge. + void purgeGpuResources() { GpuPurge::request(); } + static void definePrototype(jsi::Runtime &runtime, jsi::Object &prototype) { installGetter(runtime, prototype, "fabric", &RNWebGPU::getFabric); installGetter(runtime, prototype, "gpu", &RNWebGPU::getGPU); @@ -581,6 +585,8 @@ class RNWebGPU : public NativeObject { &RNWebGPU::createNativeBufferFromPointer); installMethodWithRuntime(runtime, prototype, "importDevice", &RNWebGPU::importDevice); + installMethod(runtime, prototype, "purgeGpuResources", + &RNWebGPU::purgeGpuResources); installMethod(runtime, prototype, "adoptTexture", &RNWebGPU::adoptTexture); installMethod(runtime, prototype, "createTestVideoPlayer", &RNWebGPU::createTestVideoPlayer); diff --git a/packages/webgpu/src/__tests__/PurgeGpuResources.spec.ts b/packages/webgpu/src/__tests__/PurgeGpuResources.spec.ts new file mode 100644 index 0000000000..e9af36e98d --- /dev/null +++ b/packages/webgpu/src/__tests__/PurgeGpuResources.spec.ts @@ -0,0 +1,76 @@ +import { client } from "./setup"; + +// Native only: the web has nothing to purge. +describe("purgeGpuResources", () => { + it("keeps what is alive, with destroyed resources and submitted work around", async () => { + if (client.OS === "web") { + return; + } + const result = await client.eval(({ device }) => { + const alive = device.createBuffer({ + size: 16, + usage: GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST, + }); + device.queue.writeBuffer(alive, 0, new Uint32Array([1, 2, 3, 4])); + for (let i = 0; i < 20; i++) { + const texture = device.createTexture({ + size: [256, 256], + format: "rgba8unorm", + usage: GPUTextureUsage.RENDER_ATTACHMENT, + }); + const encoder = device.createCommandEncoder(); + encoder + .beginRenderPass({ + colorAttachments: [ + { + view: texture.createView(), + clearValue: [1, 0, 0, 1], + loadOp: "clear", + storeOp: "store", + }, + ], + }) + .end(); + device.queue.submit([encoder.finish()]); + texture.destroy(); + RNWebGPU.purgeGpuResources(); + } + const readback = device.createBuffer({ + size: 16, + usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST, + }); + const encoder = device.createCommandEncoder(); + encoder.copyBufferToBuffer(alive, 0, readback, 0, 16); + device.queue.submit([encoder.finish()]); + return readback + .mapAsync(GPUMapMode.READ) + .then(() => Array.from(new Uint32Array(readback.getMappedRange()))); + }); + expect(result).toEqual([1, 2, 3, 4]); + }); + + it("accepts a destroyed device and one its runtime's thread owns", async () => { + if (client.OS === "web") { + return; + } + const result = await client.eval(({ gpu }) => { + const request = (implicitDeviceSynchronization: boolean) => + gpu + .requestAdapter() + .then((adapter) => + adapter!.requestDevice({ implicitDeviceSynchronization }), + ); + return Promise.all([request(true), request(false)]).then( + ([destroyed, unsynchronized]) => { + destroyed.destroy(); + RNWebGPU.purgeGpuResources(); + return unsynchronized.queue.onSubmittedWorkDone().then(() => { + unsynchronized.destroy(); + return true; + }); + }, + ); + }); + expect(result).toBe(true); + }); +}); diff --git a/packages/webgpu/src/index.tsx b/packages/webgpu/src/index.tsx index 64dcc568ae..8b07bf8f1f 100644 --- a/packages/webgpu/src/index.tsx +++ b/packages/webgpu/src/index.tsx @@ -113,6 +113,7 @@ declare global { // device from Skia.getNativeDevice()) into a GPUDevice. Requires the // exporter to link this process's single Dawn copy. importDevice: (pointer: bigint) => GPUDevice; + purgeGpuResources: () => void; // Wrap an externally created WGPUTexture pointer into a GPUTexture, // taking ownership of one reference (pair with producers that return a // +1 pointer, e.g. Skia.Image.MakeGPUTextureFromImage()). diff --git a/packages/webgpu/src/main/index.tsx b/packages/webgpu/src/main/index.tsx index 15ae1f65e1..742513df60 100644 --- a/packages/webgpu/src/main/index.tsx +++ b/packages/webgpu/src/main/index.tsx @@ -62,6 +62,7 @@ export * from "../WebGPUViewNativeComponent"; export * from "../hooks"; export * from "../GPUDeviceProvider"; export * from "../importDevice"; +export * from "../purgeGpuResources"; export * from "../video"; export * from "../formats"; diff --git a/packages/webgpu/src/main/index.web.tsx b/packages/webgpu/src/main/index.web.tsx index 243681f3d8..f4cf24d1f3 100644 --- a/packages/webgpu/src/main/index.web.tsx +++ b/packages/webgpu/src/main/index.web.tsx @@ -6,6 +6,7 @@ export * from "../WebGPUViewNativeComponent"; export * from "../hooks"; export * from "../GPUDeviceProvider"; export * from "../formats"; +export * from "../purgeGpuResources"; export * from "../video"; // We don't need to set all global properties on web, webgpu is already available globally diff --git a/packages/webgpu/src/mock.ts b/packages/webgpu/src/mock.ts index 00b893e94b..de562dff0d 100644 --- a/packages/webgpu/src/mock.ts +++ b/packages/webgpu/src/mock.ts @@ -146,6 +146,8 @@ export const useMainDevice = (): never => { throw new Error(`useMainDevice() ${NOT_AVAILABLE_UNDER_JEST}`); }; +export const purgeGpuResources = () => undefined; + export const importDevice = (_pointer: bigint): GPUDevice => { throw new Error(`importDevice() ${NOT_AVAILABLE_UNDER_JEST}`); }; diff --git a/packages/webgpu/src/purgeGpuResources.ts b/packages/webgpu/src/purgeGpuResources.ts new file mode 100644 index 0000000000..aec63ca37b --- /dev/null +++ b/packages/webgpu/src/purgeGpuResources.ts @@ -0,0 +1,21 @@ +/** + * Returns the GPU memory nothing uses to the system. Most apps should never + * call it: `destroy()` lets Dawn reuse the memory, and react-native-webgpu + * purges on its own when the system is short of memory and, on Android, each + * time the app goes to the background. + * + * It is meant for a one-off peak (a video export) followed by a long stretch + * that needs far less GPU memory. Not for a render loop, not after each + * `destroy()`, not on unmount: memory Dawn would have reused has to be + * requested from the system again. It does not free what was not destroyed. + * + * It returns right away and works in the background. It covers every device + * created through react-native-webgpu; an imported device is purged by its + * owner. Not part of the WebGPU spec, and does nothing on the Web. + */ +export const purgeGpuResources = (): void => { + if (typeof RNWebGPU === "undefined") { + return; + } + RNWebGPU.purgeGpuResources(); +};