From be17e5b44401efc9b63b5df6906467abf9bebb45 Mon Sep 17 00:00:00 2001 From: William Candillon Date: Tue, 24 Nov 2026 08:45:30 +0000 Subject: [PATCH 01/15] feat(graphite): trim the recorders of threads outside the render pool The JS thread and worklet runtimes record offscreen surfaces on recorders of their own, which nothing trimmed: their scratch textures stayed cached up to Graphite's budget for the life of the thread. They now trim what went unused for RNSkThreadPool::kIdleDelay after their submits, at most once per delay, and the JS thread does so once more after releasing a surface, when no submit may follow. --- packages/skia/cpp/api/JsiSkDispatcher.h | 22 +++++++++++ packages/skia/cpp/api/JsiSkSurface.h | 44 +++++++++++++++++++++ packages/skia/cpp/rnskia/RNDawnContext.h | 48 +++++++++++++++++++++++ packages/skia/cpp/rnskia/RNSkThreadPool.h | 13 ++++++ 4 files changed, 127 insertions(+) diff --git a/packages/skia/cpp/api/JsiSkDispatcher.h b/packages/skia/cpp/api/JsiSkDispatcher.h index 3e282c1158..41b924c09b 100644 --- a/packages/skia/cpp/api/JsiSkDispatcher.h +++ b/packages/skia/cpp/api/JsiSkDispatcher.h @@ -1,5 +1,6 @@ #pragma once +#include #include #include #include @@ -79,7 +80,28 @@ class Dispatcher { return count; } + /** + * Claims the trim scheduled for this thread once its surfaces went away + * (see JsiSkSurface::scheduleTrim): false when one is already pending, or + * when the thread turned out not to be the JS thread, which is the only + * one a trim can be scheduled on. + */ + bool claimTrim() { + return !_trimUnsupported.load(std::memory_order_relaxed) && + !_trimPending.exchange(true, std::memory_order_acq_rel); + } + + /** Lets the next release schedule a trim again (see claimTrim). */ + void releaseTrim() { _trimPending.store(false, std::memory_order_release); } + + /** The thread is not the JS thread: no trim is scheduled for it again. */ + void markTrimUnsupported() { + _trimUnsupported.store(true, std::memory_order_relaxed); + } + private: + std::atomic _trimPending{false}; + std::atomic _trimUnsupported{false}; std::thread::id _threadId; std::mutex _mutex; std::queue _queue; diff --git a/packages/skia/cpp/api/JsiSkSurface.h b/packages/skia/cpp/api/JsiSkSurface.h index 02aaf86b30..af2490a540 100644 --- a/packages/skia/cpp/api/JsiSkSurface.h +++ b/packages/skia/cpp/api/JsiSkSurface.h @@ -1,8 +1,10 @@ #pragma once #include +#include #include #include +#include #include #include @@ -217,7 +219,49 @@ class JsiSkSurface // another runtime: let the thread that created the surface destroy it. auto surface = getObjectUnchecked(); setObject(nullptr); + const bool graphite = surface != nullptr && surface->recorder() != nullptr; _dispatcher->release(std::move(surface)); + if (graphite) { + scheduleTrim(); + } + } + + /** + The texture of a released surface goes back to the recorder of its + thread, which keeps it for reuse. That thread trims what went unused + after its submits (see DawnContext::trimThreadIfDue), but the last + surface it releases is followed by none: the trim is scheduled on the + JS thread, once the texture is old enough to go. A surface of another + thread (a worklet runtime) has no such trim: the next submit there + serves. + */ + void scheduleTrim() { + if (!_dispatcher->claimTrim()) { + return; + } + std::weak_ptr weak = _dispatcher; + auto context = getContext(); + std::thread([weak, context]() { + std::this_thread::sleep_for(DawnContext::kThreadTrimDelay + + std::chrono::milliseconds(100)); + if (auto dispatcher = weak.lock()) { + // Released before the hop: it may be dropped (a reload). + dispatcher->releaseTrim(); + } + context->runOnJavascriptThread([weak](jsi::Runtime &) { + auto dispatcher = weak.lock(); + if (dispatcher == nullptr) { + return; + } + if (!dispatcher->isCurrentThread()) { + dispatcher->markTrimUnsupported(); + return; + } + // The surfaces the GC finalized elsewhere first. + dispatcher->processQueue(); + DawnContext::trimThreadRecorders(DawnContext::kThreadTrimDelay, false); + }); + }).detach(); } std::shared_ptr _dispatcher; diff --git a/packages/skia/cpp/rnskia/RNDawnContext.h b/packages/skia/cpp/rnskia/RNDawnContext.h index b7eef53bf2..8c0c4ffd39 100644 --- a/packages/skia/cpp/rnskia/RNDawnContext.h +++ b/packages/skia/cpp/rnskia/RNDawnContext.h @@ -26,6 +26,7 @@ #include "RNImageProvider.h" #include "RNSkGpuActivity.h" #include "RNSkPipelineWarmup.h" +#include "RNSkThreadPool.h" #include "rnwgpu/DawnBlobCache.h" #include "utils/RNSkLog.h" @@ -462,6 +463,50 @@ class DawnContext { bool submitRecording( skgpu::graphite::Recorder *recorder, skgpu::graphite::SyncToCpu syncToCpu = skgpu::graphite::SyncToCpu::kNo) { + const bool inserted = snapAndRun(recorder, syncToCpu); + if (recorder != nullptr && recorder == threadSlot().recorder.get()) { + trimThreadIfDue(); + } + return inserted; + } + + /** + How long a resource a thread outside the render pool cached went unused + before that thread lets go of it, and how often at most it checks (see + trimThreadIfDue): the pool's own delay (RNSkThreadPool::kIdleDelay). + */ + static constexpr std::chrono::milliseconds kThreadTrimDelay = + RNSkThreadPool::kIdleDelay; + + /** + Trims the recorders of the calling thread of what went unused for + kThreadTrimDelay, at most once per kThreadTrimDelay: what a thread outside + the render pool (the JS thread, a worklet runtime) does after its submits + (see submitRecording), since nothing else would. Its drawing recorder + otherwise keeps every scratch texture its offscreen surfaces let go of, + up to Graphite's budget (256 MB by default), for as long as the thread + lives. The render pool trims its threads itself, once idle (see + RNSkGraphiteProducer). Never makes a recorder. Any thread. + */ + static void trimThreadIfDue() { + if (RNSkThreadPool::isPoolThread()) { + return; + } + auto &slot = threadSlot(); + if (slot.recorder == nullptr) { + return; + } + const auto now = std::chrono::steady_clock::now(); + if (now - slot.lastTrim < kThreadTrimDelay) { + return; + } + slot.lastTrim = now; + trimThreadRecorders(kThreadTrimDelay, false); + } + +private: + bool snapAndRun(skgpu::graphite::Recorder *recorder, + skgpu::graphite::SyncToCpu syncToCpu) { if (recorder == nullptr) { return false; } @@ -494,6 +539,7 @@ class DawnContext { return inserted; } +public: /** Replays the recordings, in order, onto the target surface (a deferred canvas target) and submits them as one batch. A recording Graphite @@ -840,6 +886,8 @@ class DawnContext { struct ThreadRecorder { std::unique_ptr recorder; uint64_t generation = 0; + // The latest trim (see trimThreadIfDue). + std::chrono::steady_clock::time_point lastTrim{}; ~ThreadRecorder() { if (recorder == nullptr) { return; diff --git a/packages/skia/cpp/rnskia/RNSkThreadPool.h b/packages/skia/cpp/rnskia/RNSkThreadPool.h index a292636a3a..0c1e6cfae9 100644 --- a/packages/skia/cpp/rnskia/RNSkThreadPool.h +++ b/packages/skia/cpp/rnskia/RNSkThreadPool.h @@ -122,6 +122,13 @@ class RNSkThreadPool { RNSkThreadPool(const RNSkThreadPool &) = delete; RNSkThreadPool &operator=(const RNSkThreadPool &) = delete; + /** + Whether the calling thread is one of the pool's: those trim the GPU + resources they cache in their idle task (see RNSkGraphiteProducer), other + threads after their own submits (see DawnContext::trimThreadIfDue). + */ + static bool isPoolThread() { return poolThreadFlag(); } + /** The number of threads, hence of lanes. */ size_t size() const { return _workers.size(); } @@ -245,7 +252,13 @@ class RNSkThreadPool { return {_idleRequest, _idleRequestTime, _idleTask}; } + static bool &poolThreadFlag() { + static thread_local bool flag = false; + return flag; + } + void run(unsigned index) { + poolThreadFlag() = true; configureThread(index); auto &worker = *_workers[index]; RNSkIdleTaskSchedule schedule(kIdleDelay, Clock::now()); From 5d53d1e01b4444bb27d41c71bb7d43c7193e7fc5 Mon Sep 17 00:00:00 2001 From: William Candillon Date: Tue, 24 Nov 2026 09:03:55 +0000 Subject: [PATCH 02/15] feat(graphite): add Skia.freeGpuResources() in place of the JS-thread trim Freeing what a thread caches once it is done drawing is the caller's call: it knows when an export ends, and it works on worklet runtimes too, which the delayed JS-thread trim could not reach. The trim after submits stays, so that the cache does not grow while drawing. --- apps/docs/docs/animations/textures.md | 25 ++++++++++++++ packages/skia/cpp/api/JsiSkApi.h | 10 ++++++ packages/skia/cpp/api/JsiSkDispatcher.h | 22 ------------- packages/skia/cpp/api/JsiSkSurface.h | 44 ------------------------- packages/skia/src/skia/types/Skia.ts | 11 +++++++ packages/skia/src/skia/web/JsiSkia.ts | 2 ++ 6 files changed, 48 insertions(+), 66 deletions(-) diff --git a/apps/docs/docs/animations/textures.md b/apps/docs/docs/animations/textures.md index ba568a43bf..91896c54e3 100644 --- a/apps/docs/docs/animations/textures.md +++ b/apps/docs/docs/animations/textures.md @@ -196,4 +196,29 @@ Read the snapshot back with `makeRasterImage()` before drawing it in a canvas. T ::: +## Releasing GPU memory + +Disposing a surface does not hand its texture back to the system: Skia keeps it for the next surface of the same size made on that thread. +What goes unused is freed a few seconds later, the next time the thread draws. +When a thread is done drawing offscreen for a while, at the end of a video export for instance, `Skia.freeGpuResources()` frees what it caches right away. + +```tsx twoslash +import { Skia } from "react-native-skia"; + +const exportFrames = (count: number) => { + const surface = Skia.Surface.MakeOffscreen(1920, 1080)!; + for (let i = 0; i < count; i++) { + const canvas = surface.getCanvas(); + canvas.drawColor(Skia.Color("black")); + // ... draw and encode the frame + surface.flush(i === count - 1); + } + surface.dispose(); + // The last flush waited for the GPU: everything can go. + Skia.freeGpuResources(); +}; +``` + +It only frees what the calling thread caches: call it on the thread, or worklet runtime, that drew. + Textures can also be shared with WebGPU: see [WebGPU](/docs/webgpu). diff --git a/packages/skia/cpp/api/JsiSkApi.h b/packages/skia/cpp/api/JsiSkApi.h index 15e8892358..2ceb4852db 100644 --- a/packages/skia/cpp/api/JsiSkApi.h +++ b/packages/skia/cpp/api/JsiSkApi.h @@ -168,6 +168,14 @@ class JsiSkApi : public JsiSkNativeObject { JSI_HOST_FUNCTION(Color) { return JsiSkColor::createCtor()(runtime, thisValue, arguments, count); } + JSI_HOST_FUNCTION(freeGpuResources) { + // Everything the recorders of the calling thread cache without using it: + // scratch textures, the textures of released surfaces, atlas pages. + // What GPU work still in flight uses stays until a later trim. Never + // makes a recorder, never waits for the GPU (see trimThreadRecorders). + DawnContext::trimThreadRecorders(std::chrono::milliseconds(0), true); + return jsi::Value::undefined(); + } JSI_HOST_FUNCTION(getNativeDevice) { // Raw WGPUDevice pointer of the Graphite device, as a BigInt. Consumed by // react-native-webgpu's importDevice(), which AddRefs it; the pointer @@ -267,6 +275,8 @@ class JsiSkApi : public JsiSkNativeObject { } static void definePrototype(jsi::Runtime &runtime, jsi::Object &prototype) { + installHostMethod(runtime, prototype, "freeGpuResources", + &JsiSkApi::freeGpuResources); installHostMethod(runtime, prototype, "getNativeDevice", &JsiSkApi::getNativeDevice); installGetterWithRuntime(runtime, prototype, "gpu", &JsiSkApi::getGpu); diff --git a/packages/skia/cpp/api/JsiSkDispatcher.h b/packages/skia/cpp/api/JsiSkDispatcher.h index 41b924c09b..3e282c1158 100644 --- a/packages/skia/cpp/api/JsiSkDispatcher.h +++ b/packages/skia/cpp/api/JsiSkDispatcher.h @@ -1,6 +1,5 @@ #pragma once -#include #include #include #include @@ -80,28 +79,7 @@ class Dispatcher { return count; } - /** - * Claims the trim scheduled for this thread once its surfaces went away - * (see JsiSkSurface::scheduleTrim): false when one is already pending, or - * when the thread turned out not to be the JS thread, which is the only - * one a trim can be scheduled on. - */ - bool claimTrim() { - return !_trimUnsupported.load(std::memory_order_relaxed) && - !_trimPending.exchange(true, std::memory_order_acq_rel); - } - - /** Lets the next release schedule a trim again (see claimTrim). */ - void releaseTrim() { _trimPending.store(false, std::memory_order_release); } - - /** The thread is not the JS thread: no trim is scheduled for it again. */ - void markTrimUnsupported() { - _trimUnsupported.store(true, std::memory_order_relaxed); - } - private: - std::atomic _trimPending{false}; - std::atomic _trimUnsupported{false}; std::thread::id _threadId; std::mutex _mutex; std::queue _queue; diff --git a/packages/skia/cpp/api/JsiSkSurface.h b/packages/skia/cpp/api/JsiSkSurface.h index af2490a540..02aaf86b30 100644 --- a/packages/skia/cpp/api/JsiSkSurface.h +++ b/packages/skia/cpp/api/JsiSkSurface.h @@ -1,10 +1,8 @@ #pragma once #include -#include #include #include -#include #include #include @@ -219,49 +217,7 @@ class JsiSkSurface // another runtime: let the thread that created the surface destroy it. auto surface = getObjectUnchecked(); setObject(nullptr); - const bool graphite = surface != nullptr && surface->recorder() != nullptr; _dispatcher->release(std::move(surface)); - if (graphite) { - scheduleTrim(); - } - } - - /** - The texture of a released surface goes back to the recorder of its - thread, which keeps it for reuse. That thread trims what went unused - after its submits (see DawnContext::trimThreadIfDue), but the last - surface it releases is followed by none: the trim is scheduled on the - JS thread, once the texture is old enough to go. A surface of another - thread (a worklet runtime) has no such trim: the next submit there - serves. - */ - void scheduleTrim() { - if (!_dispatcher->claimTrim()) { - return; - } - std::weak_ptr weak = _dispatcher; - auto context = getContext(); - std::thread([weak, context]() { - std::this_thread::sleep_for(DawnContext::kThreadTrimDelay + - std::chrono::milliseconds(100)); - if (auto dispatcher = weak.lock()) { - // Released before the hop: it may be dropped (a reload). - dispatcher->releaseTrim(); - } - context->runOnJavascriptThread([weak](jsi::Runtime &) { - auto dispatcher = weak.lock(); - if (dispatcher == nullptr) { - return; - } - if (!dispatcher->isCurrentThread()) { - dispatcher->markTrimUnsupported(); - return; - } - // The surfaces the GC finalized elsewhere first. - dispatcher->processQueue(); - DawnContext::trimThreadRecorders(DawnContext::kThreadTrimDelay, false); - }); - }).detach(); } std::shared_ptr _dispatcher; diff --git a/packages/skia/src/skia/types/Skia.ts b/packages/skia/src/skia/types/Skia.ts index 6f9e392a50..64ed2184e8 100644 --- a/packages/skia/src/skia/types/Skia.ts +++ b/packages/skia/src/skia/types/Skia.ts @@ -178,6 +178,17 @@ export interface Skia { ParagraphBuilder: ParagraphBuilderFactory; Skottie: SkottieFactory; Recorder(): JsiRecorder; + /** + * Frees the GPU memory Skia caches, without using it, for the thread it is + * called on: the textures of released surfaces kept for reuse, scratch + * textures, and the pages of the glyph and path atlases. Call it once that + * thread is done drawing offscreen for a while, at the end of an export + * for instance. Textures the GPU is still working with are freed later: + * flush the last surface with `flush(true)` first to free everything. + * Unused resources are also freed on their own a few seconds after they + * were last used, the next time the thread draws. A no-op on the Web. + */ + freeGpuResources(): void; /** * Raw WGPUDevice pointer of Skia's Graphite device, as a BigInt. Pass it to * react-native-webgpu's importDevice() to get a GPUDevice sharing Skia's diff --git a/packages/skia/src/skia/web/JsiSkia.ts b/packages/skia/src/skia/web/JsiSkia.ts index edb9024cb0..3bf5f91245 100644 --- a/packages/skia/src/skia/web/JsiSkia.ts +++ b/packages/skia/src/skia/web/JsiSkia.ts @@ -140,6 +140,8 @@ export const JsiSkApi = (CanvasKit: CanvasKit): Skia => ({ Recorder: () => { return throwNotImplementedOnRNWeb(); }, + // CanvasKit manages the memory of its WebGL contexts itself. + freeGpuResources: () => {}, getNativeDevice: () => { return throwNotImplementedOnRNWeb(); }, From b76f2b42982c4ac3e280543f1ef3de9173bb1fce Mon Sep 17 00:00:00 2001 From: William Candillon Date: Tue, 24 Nov 2026 09:16:27 +0000 Subject: [PATCH 03/15] feat(graphite): rename freeGpuResources to purgeThreadGpuCache The name says what the call touches (the calling thread's cache, never what is in use), and the docs spell out what it frees, what it leaves, and when it is worth calling. --- apps/docs/docs/animations/textures.md | 28 +++++++++++++++++++-------- packages/skia/cpp/api/JsiSkApi.h | 6 +++--- packages/skia/src/skia/types/Skia.ts | 24 ++++++++++++++--------- packages/skia/src/skia/web/JsiSkia.ts | 2 +- 4 files changed, 39 insertions(+), 21 deletions(-) diff --git a/apps/docs/docs/animations/textures.md b/apps/docs/docs/animations/textures.md index 91896c54e3..067070a253 100644 --- a/apps/docs/docs/animations/textures.md +++ b/apps/docs/docs/animations/textures.md @@ -196,11 +196,25 @@ Read the snapshot back with `makeRasterImage()` before drawing it in a canvas. T ::: -## Releasing GPU memory +## GPU memory of offscreen surfaces -Disposing a surface does not hand its texture back to the system: Skia keeps it for the next surface of the same size made on that thread. -What goes unused is freed a few seconds later, the next time the thread draws. -When a thread is done drawing offscreen for a while, at the end of a video export for instance, `Skia.freeGpuResources()` frees what it caches right away. +Each thread that draws offscreen (the JS thread, a worklet runtime) has a GPU cache of its own. +When a surface is disposed, its texture is not handed back to the system: it goes to that cache, for the next surface of the same size made on the thread. +The cache also holds scratch textures and the glyph and path atlases. + +You don't need to manage this cache while drawing. +Each time a thread draws, Skia frees what its cache has not used for a few seconds, so memory follows what the thread actually uses. + +What stays is what the cache held at the thread's last draw: it is freed the next time the thread draws, or never if the thread no longer draws offscreen. +`Skia.purgeThreadGpuCache()` frees it right away: + +- It frees the textures of disposed surfaces, scratch textures, and the atlas pages (rebuilt on the next text or path draw). +- Surfaces, images, and pictures still alive are not affected. +- Textures the GPU is still working with are freed later: flush the last surface with `flush(true)` first to free everything. +- It only frees the cache of the thread it is called on: call it on the thread, or worklet runtime, that drew. +- It is a no-op on the Web. + +Call it once a thread is done drawing offscreen for a while, at the end of a video export for instance, not after every frame: the next frames would allocate their textures again. ```tsx twoslash import { Skia } from "react-native-skia"; @@ -211,14 +225,12 @@ const exportFrames = (count: number) => { const canvas = surface.getCanvas(); canvas.drawColor(Skia.Color("black")); // ... draw and encode the frame + // The last flush waits for the GPU, so that everything can be freed. surface.flush(i === count - 1); } surface.dispose(); - // The last flush waited for the GPU: everything can go. - Skia.freeGpuResources(); + Skia.purgeThreadGpuCache(); }; ``` -It only frees what the calling thread caches: call it on the thread, or worklet runtime, that drew. - Textures can also be shared with WebGPU: see [WebGPU](/docs/webgpu). diff --git a/packages/skia/cpp/api/JsiSkApi.h b/packages/skia/cpp/api/JsiSkApi.h index 2ceb4852db..0ec50daf97 100644 --- a/packages/skia/cpp/api/JsiSkApi.h +++ b/packages/skia/cpp/api/JsiSkApi.h @@ -168,7 +168,7 @@ class JsiSkApi : public JsiSkNativeObject { JSI_HOST_FUNCTION(Color) { return JsiSkColor::createCtor()(runtime, thisValue, arguments, count); } - JSI_HOST_FUNCTION(freeGpuResources) { + JSI_HOST_FUNCTION(purgeThreadGpuCache) { // Everything the recorders of the calling thread cache without using it: // scratch textures, the textures of released surfaces, atlas pages. // What GPU work still in flight uses stays until a later trim. Never @@ -275,8 +275,8 @@ class JsiSkApi : public JsiSkNativeObject { } static void definePrototype(jsi::Runtime &runtime, jsi::Object &prototype) { - installHostMethod(runtime, prototype, "freeGpuResources", - &JsiSkApi::freeGpuResources); + installHostMethod(runtime, prototype, "purgeThreadGpuCache", + &JsiSkApi::purgeThreadGpuCache); installHostMethod(runtime, prototype, "getNativeDevice", &JsiSkApi::getNativeDevice); installGetterWithRuntime(runtime, prototype, "gpu", &JsiSkApi::getGpu); diff --git a/packages/skia/src/skia/types/Skia.ts b/packages/skia/src/skia/types/Skia.ts index 64ed2184e8..4fe9b14e74 100644 --- a/packages/skia/src/skia/types/Skia.ts +++ b/packages/skia/src/skia/types/Skia.ts @@ -179,16 +179,22 @@ export interface Skia { Skottie: SkottieFactory; Recorder(): JsiRecorder; /** - * Frees the GPU memory Skia caches, without using it, for the thread it is - * called on: the textures of released surfaces kept for reuse, scratch - * textures, and the pages of the glyph and path atlases. Call it once that - * thread is done drawing offscreen for a while, at the end of an export - * for instance. Textures the GPU is still working with are freed later: - * flush the last surface with `flush(true)` first to free everything. - * Unused resources are also freed on their own a few seconds after they - * were last used, the next time the thread draws. A no-op on the Web. + * Frees the GPU memory Skia keeps cached for reuse on the calling thread, + * right away. Nothing in use is affected: surfaces, images and pictures + * that are still alive keep their content. + * + * What is freed: the textures of disposed surfaces, scratch textures, and + * the pages of the glyph and path atlases (rebuilt on the next text or + * path draw). Textures the GPU is still working with are freed by a later + * trim: flush the last surface with `flush(true)` first to free everything. + * + * Only the calling thread's cache is freed: call it on the thread, or + * worklet runtime, that drew. Skia already frees what went unused for a few + * seconds each time a thread draws, so this is only needed once a thread + * is done drawing offscreen for a while, at the end of an export for + * instance. A no-op on the Web. */ - freeGpuResources(): void; + purgeThreadGpuCache(): void; /** * Raw WGPUDevice pointer of Skia's Graphite device, as a BigInt. Pass it to * react-native-webgpu's importDevice() to get a GPUDevice sharing Skia's diff --git a/packages/skia/src/skia/web/JsiSkia.ts b/packages/skia/src/skia/web/JsiSkia.ts index 3bf5f91245..8246195f99 100644 --- a/packages/skia/src/skia/web/JsiSkia.ts +++ b/packages/skia/src/skia/web/JsiSkia.ts @@ -141,7 +141,7 @@ export const JsiSkApi = (CanvasKit: CanvasKit): Skia => ({ return throwNotImplementedOnRNWeb(); }, // CanvasKit manages the memory of its WebGL contexts itself. - freeGpuResources: () => {}, + purgeThreadGpuCache: () => {}, getNativeDevice: () => { return throwNotImplementedOnRNWeb(); }, From 631f6efd76d1ff488a0efbd476882b681a8efbf4 Mon Sep 17 00:00:00 2001 From: William Candillon Date: Tue, 24 Nov 2026 15:26:15 +0100 Subject: [PATCH 04/15] feat(graphite): one recorder per offscreen surface, add Skia.purgeGpuResources() A Graphite recorder has a single owner, but an offscreen surface used the recorder of the thread that made it: a surface made on the JS thread and drawn by a UI worklet shared its recorder with whatever the JS thread recorded or purged, and crashed in ResourceCache. Each offscreen surface now owns its recorder, with a budget scaled to its size, and JsiSkDispatcher is gone. Skia.purgeThreadGpuCache() becomes Skia.purgeGpuResources(): it trims the caller's recorders, then asks Dawn in the background to give its pooled heaps back to the system. It also runs on iOS memory warnings, and on Android onLowMemory and onTrimMemory from TRIM_MEMORY_BACKGROUND. Drawing a.asImage() into b now requires a.flush() first. --- apps/docs/docs/animations/textures.md | 36 +-- .../android/cpp/jni/JniPlatformContext.cpp | 6 + .../cpp/jni/include/JniPlatformContext.h | 3 + .../com/reactnative/skia/PlatformContext.java | 17 +- .../skia/apple/RNSkApplePlatformContext.mm | 6 + packages/skia/cpp/api/JsiSkApi.h | 12 +- packages/skia/cpp/api/JsiSkCanvas.h | 41 +-- packages/skia/cpp/api/JsiSkDispatcher.h | 88 ------- packages/skia/cpp/api/JsiSkSurface.h | 49 ++-- packages/skia/cpp/api/JsiSkSurfaceFactory.h | 26 +- packages/skia/cpp/rnskia/RNDawnContext.h | 244 ++++++++++++++++-- .../reanimated/__tests__/textures.spec.tsx | 1 + .../skia/src/external/reanimated/textures.tsx | 4 +- packages/skia/src/renderer/Offscreen.tsx | 1 + packages/skia/src/skia/types/Skia.ts | 22 +- packages/skia/src/skia/web/JsiSkia.ts | 2 +- 16 files changed, 344 insertions(+), 214 deletions(-) delete mode 100644 packages/skia/cpp/api/JsiSkDispatcher.h diff --git a/apps/docs/docs/animations/textures.md b/apps/docs/docs/animations/textures.md index 067070a253..45eb1a1661 100644 --- a/apps/docs/docs/animations/textures.md +++ b/apps/docs/docs/animations/textures.md @@ -198,39 +198,11 @@ Read the snapshot back with `makeRasterImage()` before drawing it in a canvas. T ## GPU memory of offscreen surfaces -Each thread that draws offscreen (the JS thread, a worklet runtime) has a GPU cache of its own. -When a surface is disposed, its texture is not handed back to the system: it goes to that cache, for the next surface of the same size made on the thread. -The cache also holds scratch textures and the glyph and path atlases. +Each offscreen surface has a GPU cache of its own, for the scratch textures and atlases its drawing needs, so it can be drawn into on another thread than the one that made it. +A surface must only be used by one thread at a time. -You don't need to manage this cache while drawing. -Each time a thread draws, Skia frees what its cache has not used for a few seconds, so memory follows what the thread actually uses. +Skia frees what the cache has not used for a few seconds as you draw into the surface. The rest goes with the surface: call `dispose()` once you are done with it. Keep a snapshot (`makeImageSnapshot()`) if you still need its content. -What stays is what the cache held at the thread's last draw: it is freed the next time the thread draws, or never if the thread no longer draws offscreen. -`Skia.purgeThreadGpuCache()` frees it right away: - -- It frees the textures of disposed surfaces, scratch textures, and the atlas pages (rebuilt on the next text or path draw). -- Surfaces, images, and pictures still alive are not affected. -- Textures the GPU is still working with are freed later: flush the last surface with `flush(true)` first to free everything. -- It only frees the cache of the thread it is called on: call it on the thread, or worklet runtime, that drew. -- It is a no-op on the Web. - -Call it once a thread is done drawing offscreen for a while, at the end of a video export for instance, not after every frame: the next frames would allocate their textures again. - -```tsx twoslash -import { Skia } from "react-native-skia"; - -const exportFrames = (count: number) => { - const surface = Skia.Surface.MakeOffscreen(1920, 1080)!; - for (let i = 0; i < count; i++) { - const canvas = surface.getCanvas(); - canvas.drawColor(Skia.Color("black")); - // ... draw and encode the frame - // The last flush waits for the GPU, so that everything can be freed. - surface.flush(i === count - 1); - } - surface.dispose(); - Skia.purgeThreadGpuCache(); -}; -``` +Disposed surfaces leave their memory to Skia, for the next ones. `Skia.purgeGpuResources()` hands what nothing uses back to the system, in the background: call it after disposing of many surfaces, at the end of an export for instance, not every frame. Textures can also be shared with WebGPU: see [WebGPU](/docs/webgpu). diff --git a/packages/skia/android/cpp/jni/JniPlatformContext.cpp b/packages/skia/android/cpp/jni/JniPlatformContext.cpp index f29f8d51ba..3e333358b5 100644 --- a/packages/skia/android/cpp/jni/JniPlatformContext.cpp +++ b/packages/skia/android/cpp/jni/JniPlatformContext.cpp @@ -37,6 +37,8 @@ void JniPlatformContext::registerNatives() { JniPlatformContext::runMainThreadTasks), makeNativeMethod("setForegroundNative", JniPlatformContext::setForegroundNative), + makeNativeMethod("purgeGpuResourcesNative", + JniPlatformContext::purgeGpuResourcesNative), makeNativeMethod("setCacheDirectoryNative", JniPlatformContext::setCacheDirectoryNative), makeNativeMethod("setPixelDensityNative", @@ -97,6 +99,10 @@ void JniPlatformContext::setForegroundNative(jni::alias_ref, DawnContext::setForeground(foreground == JNI_TRUE); } +void JniPlatformContext::purgeGpuResourcesNative(jni::alias_ref) { + DawnContext::purgeGpuResources(); +} + void JniPlatformContext::setCacheDirectoryNative( jni::alias_ref, jni::alias_ref directory) { if (directory) { diff --git a/packages/skia/android/cpp/jni/include/JniPlatformContext.h b/packages/skia/android/cpp/jni/include/JniPlatformContext.h index 45fcdf54b1..59b4e84766 100644 --- a/packages/skia/android/cpp/jni/include/JniPlatformContext.h +++ b/packages/skia/android/cpp/jni/include/JniPlatformContext.h @@ -33,6 +33,9 @@ class JniPlatformContext : public jni::HybridClass { // and outlives it. static void setForegroundNative(jni::alias_ref, jboolean foreground); + // The system is low on memory (see DawnContext::purgeGpuResources). + static void purgeGpuResourcesNative(jni::alias_ref); + static void setCacheDirectoryNative(jni::alias_ref, jni::alias_ref directory); diff --git a/packages/skia/android/src/main/java/com/reactnative/skia/PlatformContext.java b/packages/skia/android/src/main/java/com/reactnative/skia/PlatformContext.java index a671b4bef6..e20cca3e20 100644 --- a/packages/skia/android/src/main/java/com/reactnative/skia/PlatformContext.java +++ b/packages/skia/android/src/main/java/com/reactnative/skia/PlatformContext.java @@ -1,6 +1,6 @@ package com.reactnative.skia; -import android.content.ComponentCallbacks; +import android.content.ComponentCallbacks2; import android.content.res.Configuration; import android.os.Handler; import android.os.Looper; @@ -36,7 +36,7 @@ public class PlatformContext implements LifecycleEventListener { // The display density can change while the app runs (display size // setting, foldables): the native side follows it. - private final ComponentCallbacks mComponentCallbacks = new ComponentCallbacks() { + private final ComponentCallbacks2 mComponentCallbacks = new ComponentCallbacks2() { @Override public void onConfigurationChanged(Configuration newConfig) { updatePixelDensity(); @@ -44,6 +44,16 @@ public void onConfigurationChanged(Configuration newConfig) { @Override public void onLowMemory() { + purgeGpuResourcesNative(); + } + + @Override + public void onTrimMemory(int level) { + // Android 14 and later never call onLowMemory(), and of the trim + // levels only send UI_HIDDEN (any app switch) and BACKGROUND. + if (level >= TRIM_MEMORY_BACKGROUND) { + purgeGpuResourcesNative(); + } } }; @@ -172,6 +182,9 @@ public void run() { // Whether the app is in the foreground (DawnContext::setForeground). private static native void setForegroundNative(boolean foreground); + // Frees the GPU memory nothing uses (DawnContext::purgeGpuResources). + private static native void purgeGpuResourcesNative(); + // Where Dawn's blob cache keeps its entries (DawnContext::setCacheDirectory). private static native void setCacheDirectoryNative(String directory); } diff --git a/packages/skia/apple/RNSkApplePlatformContext.mm b/packages/skia/apple/RNSkApplePlatformContext.mm index a622c1b19d..f797b260d0 100644 --- a/packages/skia/apple/RNSkApplePlatformContext.mm +++ b/packages/skia/apple/RNSkApplePlatformContext.mm @@ -183,6 +183,12 @@ usingBlock:^(NSNotification *) { DawnContext::setForeground(true); }]; + [center addObserverForName:UIApplicationDidReceiveMemoryWarningNotification + object:nil + queue:nil + usingBlock:^(NSNotification *) { + DawnContext::purgeGpuResources(); + }]; }); #endif // !TARGET_OS_OSX } diff --git a/packages/skia/cpp/api/JsiSkApi.h b/packages/skia/cpp/api/JsiSkApi.h index 0ec50daf97..eeaeba3cb2 100644 --- a/packages/skia/cpp/api/JsiSkApi.h +++ b/packages/skia/cpp/api/JsiSkApi.h @@ -168,12 +168,10 @@ class JsiSkApi : public JsiSkNativeObject { JSI_HOST_FUNCTION(Color) { return JsiSkColor::createCtor()(runtime, thisValue, arguments, count); } - JSI_HOST_FUNCTION(purgeThreadGpuCache) { - // Everything the recorders of the calling thread cache without using it: - // scratch textures, the textures of released surfaces, atlas pages. - // What GPU work still in flight uses stays until a later trim. Never - // makes a recorder, never waits for the GPU (see trimThreadRecorders). + JSI_HOST_FUNCTION(purgeGpuResources) { + // The recorders of this thread, which only it may touch, then Dawn. DawnContext::trimThreadRecorders(std::chrono::milliseconds(0), true); + DawnContext::purgeGpuResources(); return jsi::Value::undefined(); } JSI_HOST_FUNCTION(getNativeDevice) { @@ -275,8 +273,8 @@ class JsiSkApi : public JsiSkNativeObject { } static void definePrototype(jsi::Runtime &runtime, jsi::Object &prototype) { - installHostMethod(runtime, prototype, "purgeThreadGpuCache", - &JsiSkApi::purgeThreadGpuCache); + installHostMethod(runtime, prototype, "purgeGpuResources", + &JsiSkApi::purgeGpuResources); installHostMethod(runtime, prototype, "getNativeDevice", &JsiSkApi::getNativeDevice); installGetterWithRuntime(runtime, prototype, "gpu", &JsiSkApi::getGpu); diff --git a/packages/skia/cpp/api/JsiSkCanvas.h b/packages/skia/cpp/api/JsiSkCanvas.h index b2ed39f021..e2cd9f9b6f 100644 --- a/packages/skia/cpp/api/JsiSkCanvas.h +++ b/packages/skia/cpp/api/JsiSkCanvas.h @@ -8,7 +8,6 @@ #include "CustomBlendModes.h" #include "JsiSkConverters.h" -#include "JsiSkDispatcher.h" #include "JsiSkFont.h" #include "JsiSkImage.h" #include "JsiSkImageInfo.h" @@ -50,6 +49,19 @@ namespace RNSkia { namespace jsi = facebook::jsi; +/** + * A surface with the recorder it was made on, destroyed in that order: the + * surface deregisters itself from its recorder. + */ +struct SurfaceAndRecorder { + SurfaceAndRecorder(std::shared_ptr recorder, + sk_sp surface) + : recorder(std::move(recorder)), surface(std::move(surface)) {} + // Destroyed last. + std::shared_ptr recorder; + sk_sp surface; +}; + class JsiSkCanvas : public JsiSkNativeObject { public: static constexpr const char *CLASS_NAME = "Canvas"; @@ -514,8 +526,8 @@ class JsiSkCanvas : public JsiSkNativeObject { } if (_surface) { auto snapshot = _surface->makeImageSnapshot(); - if (auto *recorder = _surface->recorder()) { - DawnContext::getInstance().submitRecording(recorder); + if (_recorder) { + DawnContext::getInstance().submitSurface(*_recorder); } return JsiSkImage::readPixelsAsync( runtime, getContext(), std::move(snapshot), *info, srcX, srcY); @@ -616,31 +628,28 @@ class JsiSkCanvas : public JsiSkNativeObject { } // Associates the canvas with its owning surface, keeping it alive as long - // as the canvas. This lets readPixels fall back to a surface snapshot on - // Graphite, which has no synchronous canvas readback. The dispatcher is the - // one of the thread the surface was created on. + // as the canvas, along with the recorder of the surface. This lets readPixels + // fall back to a surface snapshot on Graphite, which has no synchronous + // canvas readback. void setSurface(sk_sp surface, - std::shared_ptr dispatcher) { + std::shared_ptr recorder) { _surface = std::move(surface); - _dispatcher = std::move(dispatcher); + _recorder = std::move(recorder); } // Called by the owner of the SkCanvas (JsiSkSurface, JsiSkPictureRecorder, // JsiSkGraphiteContext) once that canvas is gone, and by the destructor: - // forgets the pointer and lets go of the surface. The canvas may hold the - // last reference to its surface, and the GC may finalize it on any thread: - // a Graphite surface has to be destroyed on the thread of its recorder (see - // Dispatcher). + // forgets the pointer and lets go of the surface and its recorder. void detach() { _canvas = nullptr; - if (_dispatcher) { - _dispatcher->release(std::move(_surface)); - } + // Declared so that the surface goes before its recorder. + auto released = + SurfaceAndRecorder(std::move(_recorder), std::move(_surface)); } private: SkCanvas *_canvas = nullptr; sk_sp _surface; - std::shared_ptr _dispatcher; + std::shared_ptr _recorder; }; } // namespace RNSkia diff --git a/packages/skia/cpp/api/JsiSkDispatcher.h b/packages/skia/cpp/api/JsiSkDispatcher.h deleted file mode 100644 index 3e282c1158..0000000000 --- a/packages/skia/cpp/api/JsiSkDispatcher.h +++ /dev/null @@ -1,88 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include - -namespace RNSkia { - -/** - * A queue of operations bound to the thread that created it. - * - * Destroying a Graphite surface flushes it into its recorder and deregisters - * it from it, and a recorder is single-threaded: an SkSurface has to be - * destroyed on the thread it was created on. The JS garbage collector may - * finalize the object holding it on any thread, so the finalizer hands the - * surface to the dispatcher of the creating thread instead, and that thread - * destroys it the next time it works with a surface (see JsiSkSurface). - * - * Graphite images and pictures need none of this: a Graphite resource may be - * released from any thread, it returns to its recorder's cache through a - * thread-safe queue. - */ -class Dispatcher { -public: - using Operation = std::function; - - /** The dispatcher of the current thread, created on first use. */ - static std::shared_ptr getDispatcher() { - static thread_local auto dispatcher = std::make_shared(); - return dispatcher; - } - - Dispatcher() : _threadId(std::this_thread::get_id()) {} - - /** Whether the caller runs on the dispatcher's thread. */ - bool isCurrentThread() const { - return std::this_thread::get_id() == _threadId; - } - - /** - * Lets go of `object` on the dispatcher's thread: right away when called - * from it, otherwise when that thread next calls processQueue(). Pass the - * last reference for the object to be destroyed there. - */ - template void release(T object) { - if (!object || isCurrentThread()) { - return; - } - run([object = std::move(object)]() {}); - } - - /** Queues an operation to run on the dispatcher's thread. */ - void run(Operation op) { - std::lock_guard lock(_mutex); - _queue.push(std::move(op)); - } - - /** - * Runs the queued operations. A no-op on any thread but the dispatcher's. - * Returns the number of operations run. - */ - size_t processQueue() { - if (!isCurrentThread()) { - return 0; - } - std::queue operations; - { - std::lock_guard lock(_mutex); - operations.swap(_queue); - } - size_t count = operations.size(); - while (!operations.empty()) { - operations.front()(); - operations.pop(); - } - return count; - } - -private: - std::thread::id _threadId; - std::mutex _mutex; - std::queue _queue; -}; - -} // namespace RNSkia diff --git a/packages/skia/cpp/api/JsiSkSurface.h b/packages/skia/cpp/api/JsiSkSurface.h index 02aaf86b30..6ef46471fd 100644 --- a/packages/skia/cpp/api/JsiSkSurface.h +++ b/packages/skia/cpp/api/JsiSkSurface.h @@ -8,7 +8,6 @@ #include #include "JsiSkConverters.h" -#include "JsiSkDispatcher.h" #include "JsiSkNativeObjects.h" #include "JsiSkCanvas.h" @@ -34,15 +33,11 @@ class JsiSkSurface static constexpr const char *CLASS_NAME = "Surface"; JsiSkSurface(std::shared_ptr context, - sk_sp surface) + sk_sp surface, + std::shared_ptr recorder = nullptr) : JsiSkWrappingSkPtrNativeObject( std::move(context), std::move(surface)), - _dispatcher(Dispatcher::getDispatcher()) { - // The surface belongs to the recorder of this thread, which is also the - // thread that destroys the surfaces finalized elsewhere (see - // releaseResources). - _dispatcher->processQueue(); - } + _recorder(std::move(recorder)) {} ~JsiSkSurface() override { // Collected by the GC: a canvas that JS still holds keeps the surface @@ -68,13 +63,12 @@ class JsiSkSurface // back through a snapshot on Graphite (which lacks synchronous canvas // readback), and so that it outlives a surface wrapper the GC collected // first. - _canvas->setSurface(surface, _dispatcher); + _canvas->setSurface(surface, _recorder); } return _canvas; } void flush(JsiOptional syncParam) { - _dispatcher->processQueue(); auto surface = getObject(); // When `sync` is true, block until the GPU has finished executing the // submitted work. Required before a consumer on a different command queue @@ -84,10 +78,10 @@ class JsiSkSurface // A raster surface (e.g. Skia.Surface.Make) has no Graphite recorder; // only Graphite-backed surfaces need to snap and submit a recording. One // made on a GPU device lost since submits nothing (see DawnContext). - if (auto *recorder = surface->recorder()) { - DawnContext::getInstance().submitRecording( - recorder, sync ? skgpu::graphite::SyncToCpu::kYes - : skgpu::graphite::SyncToCpu::kNo); + if (_recorder) { + DawnContext::getInstance().submitSurface( + *_recorder, sync ? skgpu::graphite::SyncToCpu::kYes + : skgpu::graphite::SyncToCpu::kNo); } } @@ -95,7 +89,6 @@ class JsiSkSurface // drawing it shows what the surface holds by then (flush the surface // first). A raster surface has no texture to share: its snapshot instead. std::shared_ptr asImage() { - _dispatcher->processQueue(); auto surface = getObject(); auto sharesTexture = surface->recorder() != nullptr; auto image = sharesTexture ? SkSurfaces::AsImage(surface) @@ -110,7 +103,6 @@ class JsiSkSurface } JSI_HOST_FUNCTION(makeImageSnapshot) { - _dispatcher->processQueue(); auto surface = getObject(); sk_sp image; if (count > 0 && arguments[0].isObject()) { @@ -122,8 +114,8 @@ class JsiSkSurface } // A raster surface (e.g. Skia.Surface.Make) has no Graphite recorder; its // snapshot is already a valid CPU image, so skip the recording submit. - if (auto *recorder = surface->recorder()) { - DawnContext::getInstance().submitRecording(recorder); + if (_recorder) { + DawnContext::getInstance().submitSurface(*_recorder); } if (count > 1 && arguments[1].isObject()) { auto jsiImage = getJsiObject(runtime, arguments[1]); @@ -181,6 +173,12 @@ class JsiSkSurface estimated = safeAdd(estimated, pixelBytes / 2); // depth-stencil buffers } + // The recorder of the surface: the buffers it draws with (measured at + // about 2 MB on Adreno). + if (_recorder) { + estimated = safeAdd(estimated, 2 * 1024 * 1024); + } + // Add a small overhead buffer for bookkeeping allocations. estimated = safeAdd(estimated, 128 * 1024); @@ -211,16 +209,17 @@ class JsiSkSurface private: void releaseSurface() { - // Destroying a Graphite surface flushes it into its recorder and - // deregisters it from it, and a recorder is single-threaded. The GC may - // finalize this object on any thread, and dispose() may be called from - // another runtime: let the thread that created the surface destroy it. - auto surface = getObjectUnchecked(); + // Destroying a Graphite surface deregisters it from its recorder, which is + // the surface's alone (see DawnContext::SurfaceRecorder): whichever thread + // lets go of both last destroys them, the GC's included. Nothing else can + // be using them then. + auto released = + SurfaceAndRecorder(std::move(_recorder), getObjectUnchecked()); setObject(nullptr); - _dispatcher->release(std::move(surface)); } - std::shared_ptr _dispatcher; + // The recorder of the surface, for it alone; nullptr for a raster surface. + std::shared_ptr _recorder; std::shared_ptr _canvas; }; diff --git a/packages/skia/cpp/api/JsiSkSurfaceFactory.h b/packages/skia/cpp/api/JsiSkSurfaceFactory.h index c04ed614de..64794deb7c 100644 --- a/packages/skia/cpp/api/JsiSkSurfaceFactory.h +++ b/packages/skia/cpp/api/JsiSkSurfaceFactory.h @@ -54,14 +54,15 @@ class JsiSkSurfaceFactory : public JsiSkNativeObject { } } } - auto context = getContext(); + // A recorder of its own: the surface may be drawn into on another thread + // than this one (see DawnContext::SurfaceRecorder). + auto &dawn = DawnContext::getInstance(); + auto recorder = dawn.makeSurfaceRecorder(width, height); auto surface = - context->makeOffscreenSurface(width, height, useP3ColorSpace); - if (surface == nullptr) { - return jsi::Value::null(); - } - return makeJsiObject(runtime, std::make_shared( - getContext(), std::move(surface))); + dawn.MakeOffscreen(width, height, useP3ColorSpace, recorder.get()); + return makeJsiObject( + runtime, std::make_shared( + getContext(), std::move(surface), std::move(recorder))); } // Pointer-based texture interop with react-native-webgpu, the surface @@ -78,13 +79,18 @@ class JsiSkSurfaceFactory : public JsiSkNativeObject { // the surface exists. wgpu::Texture texture = gpuTextureFromValue(runtime, arguments[0], "MakeFromGPUTexture"); - auto surface = DawnContext::getInstance().MakeSurfaceFromTexture(texture); + auto &dawn = DawnContext::getInstance(); + auto recorder = + dawn.makeSurfaceRecorder(static_cast(texture.GetWidth()), + static_cast(texture.GetHeight())); + auto surface = dawn.MakeSurfaceFromTexture(texture, *recorder); if (surface == nullptr) { throw std::runtime_error( "MakeFromGPUTexture: failed to wrap the texture"); } - return makeJsiObject(runtime, std::make_shared( - getContext(), std::move(surface))); + return makeJsiObject( + runtime, std::make_shared( + getContext(), std::move(surface), std::move(recorder))); } size_t getMemoryPressure() override { return 2048; } diff --git a/packages/skia/cpp/rnskia/RNDawnContext.h b/packages/skia/cpp/rnskia/RNDawnContext.h index 8c0c4ffd39..f13a90fcf0 100644 --- a/packages/skia/cpp/rnskia/RNDawnContext.h +++ b/packages/skia/cpp/rnskia/RNDawnContext.h @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -214,6 +215,10 @@ class DawnContext { /** Sets isForeground(); the platform calls it from its main thread. */ static void setForeground(bool foreground) noexcept { foregroundFlag().store(foreground, std::memory_order_release); + if (foreground && + purgeOnForeground().exchange(false, std::memory_order_acq_rel)) { + purgeGpuResources(); + } } /** @@ -392,6 +397,64 @@ class DawnContext { return currentRecorder(threadSlot()); } + /** + A recorder of its own for an offscreen surface JS made (see + MakeOffscreen): a surface may be drawn into on another thread than the one + that made it, which would race with whatever that thread records, or + trims, on its own recorder. Used by one thread at a time, as the surface + is. Must outlive the surface (see JsiSkSurface). One made for a device + lost since submits nothing. + */ + class SurfaceRecorder { + public: + SurfaceRecorder(std::unique_ptr recorder, + uint64_t generation) + : _recorder(std::move(recorder)), _generation(generation) {} + + skgpu::graphite::Recorder *get() const { return _recorder.get(); } + + private: + friend class DawnContext; + std::unique_ptr _recorder; + uint64_t _generation; + // The latest trim (see submitSurface). + std::chrono::steady_clock::time_point _lastTrim = + std::chrono::steady_clock::now(); + }; + + /** See SurfaceRecorder. Throws when no recorder can be made. Any thread. */ + std::shared_ptr makeSurfaceRecorder(int width, int height) { + std::lock_guard lock(_mutex); + auto recorder = makeRecorderLocked( + /* forUploads= */ false, surfaceBudget(width, height)); + if (recorder == nullptr) { + throw std::runtime_error("Failed to create graphite context"); + } + return std::make_shared( + std::move(recorder), _current.load(std::memory_order_acquire)->id); + } + + /** + Snaps what was recorded into the surface of the recorder and runs it on + the GPU (see submitRecording), then, at most once per kThreadTrimDelay, + frees what the recorder cached and did not use for that long. Called by + the thread using the surface. + */ + bool submitSurface( + SurfaceRecorder &surface, + skgpu::graphite::SyncToCpu syncToCpu = skgpu::graphite::SyncToCpu::kNo) { + const bool inserted = + snapAndRun(surface.get(), syncToCpu, surface._generation); + const auto now = std::chrono::steady_clock::now(); + if (now - surface._lastTrim >= kThreadTrimDelay) { + surface._lastTrim = now; + surface.get()->performDeferredCleanup(kThreadTrimDelay); + } + // What the drawing uploaded is the upload recorder's of this thread. + trimThreadIfDue(); + return inserted; + } + /** A thread's recorder with the generation it was made for. */ struct RecorderRef { skgpu::graphite::Recorder *recorder = nullptr; @@ -425,15 +488,16 @@ class DawnContext { */ static void trimThreadRecorders(std::chrono::milliseconds unusedFor, bool everything) { - auto *instance = tryGetInstance(); - if (instance == nullptr) { - return; - } + // Looked at first: the GPU is not probed for a thread that has nothing. auto &drawing = threadSlot(); auto &uploads = uploadSlot(); if (drawing.recorder == nullptr && uploads.recorder == nullptr) { return; } + auto *instance = tryGetInstance(); + if (instance == nullptr) { + return; + } instance->checkFinishedWork(); if (drawing.recorder != nullptr) { if (everything) { @@ -451,9 +515,42 @@ class DawnContext { instance->checkFinishedWork(); } + /** + Hands the GPU memory nothing uses back to the system: Dawn keeps the + memory of disposed surfaces and images for reuse otherwise. What is alive + keeps its content and its caches. Returns at once; a background thread + does the work, for as long as Dawn says deletions are pending and then + once more after the render threads trimmed their own recorders. Requests + made meanwhile are served by the same thread. Nothing happens before the + GPU is first used, nor, on iOS, where GPU work is refused in the + background (see isForeground). Any thread. + */ + static void purgeGpuResources() noexcept { + auto *instance = probedInstance().load(std::memory_order_acquire); + if (instance == nullptr) { + return; + } + auto &purge = purgeState(); + { + std::lock_guard lock(purge.mutex); + purge.requested = true; + if (purge.running) { + return; + } + purge.running = true; + } + try { + std::thread([instance]() { instance->runPurges(); }).detach(); + } catch (const std::exception &e) { + RNSkLogger::logToConsole("Purging GPU resources failed: %s", e.what()); + std::lock_guard lock(purge.mutex); + purge.running = false; + } + } + /** Snaps what the recorder recorded and runs it on the GPU. `recorder` is a - thread's (see getRecorder), also behind the surfaces made on it; any + thread's (see getRecorder), not a surface's (see submitSurface); any other submits nothing. A recording made for a lost device (see generation()) is dropped: nothing can run it, and the device in use would refuse its resources. Called on the recorder's thread. Returns whether @@ -483,7 +580,7 @@ class DawnContext { kThreadTrimDelay, at most once per kThreadTrimDelay: what a thread outside the render pool (the JS thread, a worklet runtime) does after its submits (see submitRecording), since nothing else would. Its drawing recorder - otherwise keeps every scratch texture its offscreen surfaces let go of, + otherwise keeps every scratch texture its snapshots and uploads let go of, up to Graphite's budget (256 MB by default), for as long as the thread lives. The render pool trims its threads itself, once idle (see RNSkGraphiteProducer). Never makes a recorder. Any thread. @@ -493,7 +590,7 @@ class DawnContext { return; } auto &slot = threadSlot(); - if (slot.recorder == nullptr) { + if (slot.recorder == nullptr && uploadSlot().recorder == nullptr) { return; } const auto now = std::chrono::steady_clock::now(); @@ -505,8 +602,26 @@ class DawnContext { } private: + /** + The budget of the recorder of a surface of that size: its layers and blurs + take textures of its size, up to several at once. Graphite's default, made + for a thread's whole content, is the most it gets. + */ + static size_t surfaceBudget(int width, int height) { + constexpr uint64_t kMin = 32 * 1024 * 1024; + // 64 bits: the product overflows a 32-bit size_t. + const auto bytes = static_cast(std::max(width, 0)) * + static_cast(std::max(height, 0)) * 4; + return static_cast(std::clamp( + bytes * 8, kMin, + skgpu::graphite::RecorderOptions::kDefaultRecorderBudget)); + } + + // `generation` is the one the recorder was made for; looked up, for a + // thread's recorder, when absent. bool snapAndRun(skgpu::graphite::Recorder *recorder, - skgpu::graphite::SyncToCpu syncToCpu) { + skgpu::graphite::SyncToCpu syncToCpu, + std::optional generation = std::nullopt) { if (recorder == nullptr) { return false; } @@ -519,7 +634,7 @@ class DawnContext { } std::lock_guard lock(_mutex); auto *current = _current.load(std::memory_order_acquire); - if (generationOf(recorder) != current->id || + if (generation.value_or(generationOf(recorder)) != current->id || current->lost.load(std::memory_order_acquire)) { return false; } @@ -628,9 +743,11 @@ class DawnContext { return upload(image, mipmapped).texture; } - // Create offscreen surface + // Create an offscreen surface, on the recorder of this thread unless given + // one of its own (see SurfaceRecorder). sk_sp MakeOffscreen(int width, int height, - bool useP3ColorSpace = false) { + bool useP3ColorSpace = false, + SurfaceRecorder *recorder = nullptr) { sk_sp colorSpace = useP3ColorSpace ? SkColorSpace::MakeRGB(SkNamedTransferFn::kSRGB, SkNamedGamut::kDisplayP3) @@ -638,7 +755,8 @@ class DawnContext { SkImageInfo info = SkImageInfo::Make(width, height, DawnUtils::PreferedColorType, kPremul_SkAlphaType, colorSpace); - sk_sp surface = SkSurfaces::RenderTarget(getRecorder(), info); + sk_sp surface = SkSurfaces::RenderTarget( + recorder != nullptr ? recorder->get() : getRecorder(), info); if (!surface) { throw std::runtime_error("Failed to create offscreen Skia surface."); @@ -721,7 +839,9 @@ class DawnContext { // The texture must have RenderAttachment usage; give it TextureBinding too // to sample it from WebGPU (e.g. as a three.js texture) after each flush. // The surface retains the texture for its lifetime. - sk_sp MakeSurfaceFromTexture(wgpu::Texture texture) { + // `recorder` is the surface's own (see SurfaceRecorder). + sk_sp MakeSurfaceFromTexture(wgpu::Texture texture, + SurfaceRecorder &recorder) { if (!texture) { return nullptr; } @@ -740,7 +860,7 @@ class DawnContext { // The color type is derived from the texture format. return SkSurfaces::WrapBackendTexture( - getRecorder(), backendTexture, + recorder.get(), backendTexture, nullptr, // colorspace nullptr, // surfaceProps [](void *context) { @@ -837,6 +957,8 @@ class DawnContext { or for one destroyed already. Any thread. */ void destroyRetiredDevice(uint64_t generation) { + // Before the context lock, as in reduceMemory(). + std::lock_guard destroyLock(_destroyMutex); std::lock_guard lock(_mutex); for (auto *retired : _retired) { if (retired->id == generation && !retired->deviceDestroyed) { @@ -925,6 +1047,13 @@ class DawnContext { return foreground; } + // The context once probed, for what must not probe the GPU itself (see + // purgeGpuResources). + static std::atomic &probedInstance() noexcept { + static std::atomic instance{nullptr}; + return instance; + } + static const Probe &probe() noexcept { // Attempted once: a device without a usable GPU does not get one by // asking again, and the attempt enumerates drivers. The context is never @@ -935,6 +1064,7 @@ class DawnContext { auto *probe = new Probe(); try { probe->instance = new DawnContext(); + probedInstance().store(probe->instance, std::memory_order_release); probe->info.available = true; probe->info.adapter = DawnUtils::describeAdapter( probe->instance->getWGPUDevice().GetAdapter()); @@ -1135,8 +1265,10 @@ class DawnContext { A recorder for the device in use; `forUploads` for the upload recorder of a thread (see upload()). Called with the context lock held. */ - std::unique_ptr - makeRecorderLocked(bool forUploads = false) { + std::unique_ptr makeRecorderLocked( + bool forUploads = false, + size_t budget = + skgpu::graphite::RecorderOptions::kDefaultRecorderBudget) { auto *current = _current.load(std::memory_order_acquire); if (forUploads) { // Skia's default image provider, and no budget: the textures it makes @@ -1149,6 +1281,7 @@ class DawnContext { return current->context->makeRecorder(options); } skgpu::graphite::RecorderOptions options; + options.fGpuBudgetInBytes = budget; // The provider uploads through upload() (see ImageProvider), and serves // the recorder textures of the device in use only. The context is never // destroyed, so the capture is safe. @@ -1176,7 +1309,7 @@ class DawnContext { */ ImageProvider::Upload upload(const sk_sp &image, bool mipmapped) { // A recorder of its own: snapping the recorder of this thread would also - // submit what the offscreen surfaces of this thread recorded so far. It + // submit what was recorded on it so far. It // only uploads, so it keeps Skia's default image provider rather than // the image cache, which uploads through here. auto &slot = uploadSlot(); @@ -1241,6 +1374,80 @@ class DawnContext { return slot; } + // A purge that could not run while the app was in the background. + static std::atomic &purgeOnForeground() noexcept { + static std::atomic flag{false}; + return flag; + } + + struct PurgeState { + std::mutex mutex; + bool running = false; + bool requested = false; + }; + + static PurgeState &purgeState() noexcept { + static auto *state = new PurgeState(); + return *state; + } + + // The purge thread (see purgeGpuResources). + void runPurges() noexcept { + auto &purge = purgeState(); + for (;;) { + { + std::lock_guard lock(purge.mutex); + if (!purge.requested) { + purge.running = false; + return; + } + purge.requested = false; + } + RNSkThreadPool::getInstance().requestIdleTask(); + reduceMemory(); + // The render threads trim their recorders kIdleDelay after being asked. + std::this_thread::sleep_for(RNSkThreadPool::kIdleDelay + + std::chrono::milliseconds(500)); + reduceMemory(); + } + } + + // Asks Dawn to free what it holds for reuse, and again while it says + // deletions are still pending on submitted work. + void reduceMemory() noexcept { + constexpr int kMaxPasses = 10; + for (int pass = 0; pass < kMaxPasses; pass++) { +#if defined(__APPLE__) + if (!isForeground()) { + // Asked for again once the app is back (see setForeground). + purgeOnForeground().store(true, std::memory_order_release); + return; + } +#endif + { + // Keeps destroyRetiredDevice() from destroying the device under Dawn; + // not held while waiting below. + std::lock_guard destroyLock(_destroyMutex); + wgpu::Device device; + { + std::lock_guard lock(_mutex); + auto *current = _current.load(std::memory_order_acquire); + if (current->lost.load(std::memory_order_acquire)) { + return; + } + tick(); + current->context->checkAsyncWorkCompletion(); + device = current->backendContext.fDevice; + } + // Outside the context lock, which frames need. + if (!dawn::native::ReduceMemoryUsage(device.Get())) { + return; + } + } + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + } + } + /** The recorder of a thread that ended (see ThreadRecorder). */ void forgetRecorder(const skgpu::graphite::Recorder *recorder) noexcept { std::lock_guard lock(_mutex); @@ -1383,6 +1590,9 @@ class DawnContext { // every view (isDeviceLost, isCurrent), hence atomic. std::atomic _current{nullptr}; std::vector _retired; + // Held while Dawn is asked to free memory of a device (see reduceMemory) + // and while one is destroyed. Taken before _mutex. + std::mutex _destroyMutex; uint64_t _lastGenerationId = 0; // Guards every Context operation, and the replacement of the device. std::mutex _mutex; diff --git a/packages/skia/src/external/reanimated/__tests__/textures.spec.tsx b/packages/skia/src/external/reanimated/__tests__/textures.spec.tsx index 516d944942..eb859c27bb 100644 --- a/packages/skia/src/external/reanimated/__tests__/textures.spec.tsx +++ b/packages/skia/src/external/reanimated/__tests__/textures.spec.tsx @@ -25,6 +25,7 @@ const mockSurface = { getCanvas: () => mockCanvas, flush: jest.fn(), makeImageSnapshot: () => mockSnapshot, + dispose: jest.fn(), }; const mockMakeOffscreen = jest.fn((_width: number, _height: number) => { return mockSurface; diff --git a/packages/skia/src/external/reanimated/textures.tsx b/packages/skia/src/external/reanimated/textures.tsx index b940dbdf0c..dcb4b210f5 100644 --- a/packages/skia/src/external/reanimated/textures.tsx +++ b/packages/skia/src/external/reanimated/textures.tsx @@ -34,7 +34,9 @@ const renderPicture = (picture: SkPicture, size: SkSize) => { const canvas = surface.getCanvas(); canvas.drawPicture(picture); surface.flush(); - return surface.makeImageSnapshot(); + const image = surface.makeImageSnapshot(); + surface.dispose(); + return image; }; const createTexture = ( diff --git a/packages/skia/src/renderer/Offscreen.tsx b/packages/skia/src/renderer/Offscreen.tsx index 5f5d812eef..5169e0b42d 100644 --- a/packages/skia/src/renderer/Offscreen.tsx +++ b/packages/skia/src/renderer/Offscreen.tsx @@ -48,5 +48,6 @@ export const drawAsImageFromPicture = ( canvas.drawPicture(picture); surface.flush(); const image = surface.makeImageSnapshot(); + surface.dispose(); return image.makeRasterImage(); }; diff --git a/packages/skia/src/skia/types/Skia.ts b/packages/skia/src/skia/types/Skia.ts index 4fe9b14e74..c87f933c75 100644 --- a/packages/skia/src/skia/types/Skia.ts +++ b/packages/skia/src/skia/types/Skia.ts @@ -179,22 +179,14 @@ export interface Skia { Skottie: SkottieFactory; Recorder(): JsiRecorder; /** - * Frees the GPU memory Skia keeps cached for reuse on the calling thread, - * right away. Nothing in use is affected: surfaces, images and pictures - * that are still alive keep their content. - * - * What is freed: the textures of disposed surfaces, scratch textures, and - * the pages of the glyph and path atlases (rebuilt on the next text or - * path draw). Textures the GPU is still working with are freed by a later - * trim: flush the last surface with `flush(true)` first to free everything. - * - * Only the calling thread's cache is freed: call it on the thread, or - * worklet runtime, that drew. Skia already frees what went unused for a few - * seconds each time a thread draws, so this is only needed once a thread - * is done drawing offscreen for a while, at the end of an export for - * instance. A no-op on the Web. + * Hands the GPU memory nothing uses back to the system. Skia keeps the + * memory of disposed surfaces and images for reuse otherwise: call it after + * disposing of many of them, at the end of an export for instance, not + * every frame. What is alive is not affected. Returns right away; the + * memory is freed in the background, or once the app is active again on + * iOS. A no-op on the Web. */ - purgeThreadGpuCache(): void; + purgeGpuResources(): void; /** * Raw WGPUDevice pointer of Skia's Graphite device, as a BigInt. Pass it to * react-native-webgpu's importDevice() to get a GPUDevice sharing Skia's diff --git a/packages/skia/src/skia/web/JsiSkia.ts b/packages/skia/src/skia/web/JsiSkia.ts index 8246195f99..e3e3cc0bd6 100644 --- a/packages/skia/src/skia/web/JsiSkia.ts +++ b/packages/skia/src/skia/web/JsiSkia.ts @@ -141,7 +141,7 @@ export const JsiSkApi = (CanvasKit: CanvasKit): Skia => ({ return throwNotImplementedOnRNWeb(); }, // CanvasKit manages the memory of its WebGL contexts itself. - purgeThreadGpuCache: () => {}, + purgeGpuResources: () => {}, getNativeDevice: () => { return throwNotImplementedOnRNWeb(); }, From 778ca6bacce1a93c8de15a81719f312e9f35e2d8 Mon Sep 17 00:00:00 2001 From: William Candillon Date: Tue, 24 Nov 2026 16:15:05 +0100 Subject: [PATCH 05/15] fix(graphite): address the review of offscreen surfaces and GPU purges - dispose() submits what was drawn into the surface and not flushed - a purge checks again for a device JS destroyed meanwhile; Dawn patch for the window left (ships with the next binaries) - a purge deferred in the background is no longer missed on return - document flushing a surface before drawing its asImage() elsewhere --- apps/docs/docs/animations/textures.md | 2 + packages/skia/cpp/api/JsiSkCanvas.h | 3 ++ packages/skia/cpp/api/JsiSkSurface.h | 5 +++ packages/skia/cpp/rnskia/RNDawnContext.h | 40 ++++++++++++++++--- .../reduce-memory-usage-lost-device.patch | 22 ++++++++++ .../renderer/__tests__/e2e/Surfaces.spec.tsx | 31 ++++++++++++++ .../skia/src/skia/types/Surface/Surface.ts | 3 +- 7 files changed, 100 insertions(+), 6 deletions(-) create mode 100644 packages/skia/scripts/dawn-patches/reduce-memory-usage-lost-device.patch diff --git a/apps/docs/docs/animations/textures.md b/apps/docs/docs/animations/textures.md index 45eb1a1661..41f56f7769 100644 --- a/apps/docs/docs/animations/textures.md +++ b/apps/docs/docs/animations/textures.md @@ -187,6 +187,8 @@ const Demo = () => { }; ``` +Flush the surface before drawing its image into another surface too: each surface submits its own drawing only, so flushing the second does not flush the first, and the order of the flushes is the order on the GPU. + Never draw the image onto its own surface: use a second surface for a feedback loop. :::info diff --git a/packages/skia/cpp/api/JsiSkCanvas.h b/packages/skia/cpp/api/JsiSkCanvas.h index e2cd9f9b6f..7f88c14a7b 100644 --- a/packages/skia/cpp/api/JsiSkCanvas.h +++ b/packages/skia/cpp/api/JsiSkCanvas.h @@ -624,6 +624,9 @@ class JsiSkCanvas : public JsiSkNativeObject { throw std::runtime_error("Attempted to use a canvas whose surface was " "disposed or whose recording has finished."); } + if (_recorder) { + _recorder->markPending(); + } return _canvas; } diff --git a/packages/skia/cpp/api/JsiSkSurface.h b/packages/skia/cpp/api/JsiSkSurface.h index 6ef46471fd..50227df25b 100644 --- a/packages/skia/cpp/api/JsiSkSurface.h +++ b/packages/skia/cpp/api/JsiSkSurface.h @@ -198,6 +198,11 @@ class JsiSkSurface protected: void releaseResources() override { + // What was drawn and not flushed still reaches the texture, which may + // outlive the surface (Surface.MakeFromGPUTexture, asImage()). + if (_recorder) { + DawnContext::getInstance().submitPendingSurface(*_recorder); + } // dispose(): the canvas lets go of its reference too, so that the texture // is freed now rather than once the canvas is collected (#4275). Drawing // on the canvas throws from here on. diff --git a/packages/skia/cpp/rnskia/RNDawnContext.h b/packages/skia/cpp/rnskia/RNDawnContext.h index f13a90fcf0..a20ddcd7d4 100644 --- a/packages/skia/cpp/rnskia/RNDawnContext.h +++ b/packages/skia/cpp/rnskia/RNDawnContext.h @@ -214,9 +214,9 @@ class DawnContext { /** Sets isForeground(); the platform calls it from its main thread. */ static void setForeground(bool foreground) noexcept { - foregroundFlag().store(foreground, std::memory_order_release); - if (foreground && - purgeOnForeground().exchange(false, std::memory_order_acq_rel)) { + // Sequentially consistent, with purgeOnForeground: see reduceMemory(). + foregroundFlag().store(foreground); + if (foreground && purgeOnForeground().exchange(false)) { purgeGpuResources(); } } @@ -413,8 +413,14 @@ class DawnContext { skgpu::graphite::Recorder *get() const { return _recorder.get(); } + /** The surface is about to be drawn into (see submitPendingSurface). */ + void markPending() { _pending = true; } + private: friend class DawnContext; + // Whether something may be recorded and not submitted: a new surface is + // yet to be cleared. + bool _pending = true; std::unique_ptr _recorder; uint64_t _generation; // The latest trim (see submitSurface). @@ -443,6 +449,7 @@ class DawnContext { bool submitSurface( SurfaceRecorder &surface, skgpu::graphite::SyncToCpu syncToCpu = skgpu::graphite::SyncToCpu::kNo) { + surface._pending = false; const bool inserted = snapAndRun(surface.get(), syncToCpu, surface._generation); const auto now = std::chrono::steady_clock::now(); @@ -455,6 +462,17 @@ class DawnContext { return inserted; } + /** + Submits what was drawn into the surface since its last submit, if anything: + its recorder is about to go, and what it recorded with it. Called by the + thread using the surface. + */ + void submitPendingSurface(SurfaceRecorder &surface) { + if (surface._pending) { + submitSurface(surface); + } + } + /** A thread's recorder with the generation it was made for. */ struct RecorderRef { skgpu::graphite::Recorder *recorder = nullptr; @@ -1420,8 +1438,12 @@ class DawnContext { #if defined(__APPLE__) if (!isForeground()) { // Asked for again once the app is back (see setForeground). - purgeOnForeground().store(true, std::memory_order_release); - return; + purgeOnForeground().store(true); + // The app may have come back in between, before it could see the + // request: whichever of the two takes the request serves it. + if (!foregroundFlag().load() || !purgeOnForeground().exchange(false)) { + return; + } } #endif { @@ -1437,6 +1459,14 @@ class DawnContext { } tick(); current->context->checkAsyncWorkCompletion(); + // Both may have waited for a device.destroy() from JS (the device is + // shared with react-native-webgpu) to finish. One that starts after + // this is caught by Dawn, in binaries built with + // dawn-patches/reduce-memory-usage-lost-device.patch + // (react-native-webgpu-dawn 158.0.0 is not). + if (current->lost.load(std::memory_order_acquire)) { + return; + } device = current->backendContext.fDevice; } // Outside the context lock, which frames need. diff --git a/packages/skia/scripts/dawn-patches/reduce-memory-usage-lost-device.patch b/packages/skia/scripts/dawn-patches/reduce-memory-usage-lost-device.patch new file mode 100644 index 0000000000..44dd00e0fc --- /dev/null +++ b/packages/skia/scripts/dawn-patches/reduce-memory-usage-lost-device.patch @@ -0,0 +1,22 @@ +[native] Do nothing in ReduceMemoryUsage on a lost device + +Destroy() frees the dynamic uploader, the memory block allocator and the +internal pipeline store, which ReduceMemoryUsage() then dereferences. The +caller cannot check for it: the device may be destroyed by another thread +right after. Both run under the device guard, so the check belongs here. + +Drop this patch when Dawn checks the state of the device itself. + +--- +diff --git a/src/dawn/native/Device.cpp b/src/dawn/native/Device.cpp +--- a/src/dawn/native/Device.cpp ++++ b/src/dawn/native/Device.cpp +@@ -2702,5 +2702,8 @@ + + bool DeviceBase::ReduceMemoryUsage() { + DAWN_ASSERT(IsLockedByCurrentThreadIfNeeded()); ++ if (IsLost()) { ++ return false; ++ } + if (ConsumedError(GetQueue()->CheckPassedSerials())) { + return false; diff --git a/packages/skia/src/renderer/__tests__/e2e/Surfaces.spec.tsx b/packages/skia/src/renderer/__tests__/e2e/Surfaces.spec.tsx index 9be0ade5f6..03c75c2578 100644 --- a/packages/skia/src/renderer/__tests__/e2e/Surfaces.spec.tsx +++ b/packages/skia/src/renderer/__tests__/e2e/Surfaces.spec.tsx @@ -1,3 +1,5 @@ +import { itRunsE2eOnly } from "../../../__tests__/setup"; +import { AlphaType, ColorType } from "../../../skia/types"; import { surface } from "../setup"; describe("Surfaces", () => { @@ -37,6 +39,35 @@ describe("Surfaces", () => { expect(result).toBe(true); }); + itRunsE2eOnly( + "submits what was not flushed when the surface is disposed", + async () => { + const result = await surface.eval( + (Skia, ctx) => { + const source = Skia.Surface.MakeOffscreen(16, 16)!; + const image = source.asImage(); + // Flushed once, so that the draw below is all there is to submit. + source.flush(); + source.getCanvas().drawColor(Skia.Color("cyan")); + source.dispose(); + using target = Skia.Surface.MakeOffscreen(16, 16)!; + target.getCanvas().drawImage(image, 0, 0); + return target + .getCanvas() + .readPixels(0, 0, { + width: 16, + height: 16, + colorType: ctx.colorType, + alphaType: ctx.alphaType, + }) + .then((pixels) => (pixels ? Array.from(pixels.slice(0, 4)) : null)); + }, + { colorType: ColorType.RGBA_8888, alphaType: AlphaType.Unpremul } + ); + expect(result).toEqual([0, 255, 255, 255]); + } + ); + it("disposing the surface detaches its canvas", async () => { // CanvasKit frees the canvas along with the surface: nothing to observe // on node. diff --git a/packages/skia/src/skia/types/Surface/Surface.ts b/packages/skia/src/skia/types/Surface/Surface.ts index 533f8b26d3..275f316848 100644 --- a/packages/skia/src/skia/types/Surface/Surface.ts +++ b/packages/skia/src/skia/types/Surface/Surface.ts @@ -29,7 +29,8 @@ export interface SkSurface extends SkJSIInstance<"Surface"> { * Returns an image sharing the texture of the surface, without a copy: a * canvas drawing it shows what the surface holds by the time the drawing * reaches the GPU. Call `flush()` on the surface after drawing into it and - * before the frame that samples the image, and never draw the image onto + * before the frame that samples the image, or before drawing the image into + * another surface: flushing that one does not flush this one. Never draw the image onto * its own surface (use a second surface for a feedback loop). * `makeImageSnapshot()` makes a copy instead. * From 0900205a41fbe8c33621361a047767536d4feee1 Mon Sep 17 00:00:00 2001 From: William Candillon Date: Tue, 24 Nov 2026 17:24:23 +0100 Subject: [PATCH 06/15] refactor(graphite): surface recorder and GPU purge out of DawnContext RNDawnContext.h keeps small primitives only: makeRecorder(budget, &generation), submitRecording(recorder, generation, sync), one pass of reduceMemoryUsage(), peekInstance() and waitForForeground(). - RNSkSurfaceRecorder.h: the recorder an offscreen surface owns, with flush(), flushIfDirty() and markDirty(). - RNSkGpuPurge.h: Skia.purgeGpuResources() and the platform's memory warnings, on a thread of its own. On iOS, a purge asked for in the background now waits for the foreground on a condition variable, instead of being asked for again by setForeground(). --- .../android/cpp/jni/JniPlatformContext.cpp | 3 +- .../cpp/jni/include/JniPlatformContext.h | 2 +- .../com/reactnative/skia/PlatformContext.java | 2 +- .../skia/apple/RNSkApplePlatformContext.mm | 3 +- packages/skia/cpp/api/JsiSkApi.h | 3 +- packages/skia/cpp/api/JsiSkCanvas.h | 13 +- packages/skia/cpp/api/JsiSkSurface.h | 16 +- packages/skia/cpp/api/JsiSkSurfaceFactory.h | 18 +- packages/skia/cpp/rnskia/RNDawnContext.h | 420 ++++++------------ packages/skia/cpp/rnskia/RNSkGpuPurge.h | 109 +++++ .../skia/cpp/rnskia/RNSkSurfaceRecorder.h | 115 +++++ 11 files changed, 402 insertions(+), 302 deletions(-) create mode 100644 packages/skia/cpp/rnskia/RNSkGpuPurge.h create mode 100644 packages/skia/cpp/rnskia/RNSkSurfaceRecorder.h diff --git a/packages/skia/android/cpp/jni/JniPlatformContext.cpp b/packages/skia/android/cpp/jni/JniPlatformContext.cpp index 3e333358b5..7599048621 100644 --- a/packages/skia/android/cpp/jni/JniPlatformContext.cpp +++ b/packages/skia/android/cpp/jni/JniPlatformContext.cpp @@ -20,6 +20,7 @@ #include "JniPresentThread.h" #include "RNDawnContext.h" +#include "RNSkGpuPurge.h" #include "RNSkPresentThread.h" namespace RNSkia { @@ -100,7 +101,7 @@ void JniPlatformContext::setForegroundNative(jni::alias_ref, } void JniPlatformContext::purgeGpuResourcesNative(jni::alias_ref) { - DawnContext::purgeGpuResources(); + RNSkGpuPurge::request(); } void JniPlatformContext::setCacheDirectoryNative( diff --git a/packages/skia/android/cpp/jni/include/JniPlatformContext.h b/packages/skia/android/cpp/jni/include/JniPlatformContext.h index 59b4e84766..568ce4aa9b 100644 --- a/packages/skia/android/cpp/jni/include/JniPlatformContext.h +++ b/packages/skia/android/cpp/jni/include/JniPlatformContext.h @@ -33,7 +33,7 @@ class JniPlatformContext : public jni::HybridClass { // and outlives it. static void setForegroundNative(jni::alias_ref, jboolean foreground); - // The system is low on memory (see DawnContext::purgeGpuResources). + // The system is low on memory (see RNSkGpuPurge). static void purgeGpuResourcesNative(jni::alias_ref); static void setCacheDirectoryNative(jni::alias_ref, diff --git a/packages/skia/android/src/main/java/com/reactnative/skia/PlatformContext.java b/packages/skia/android/src/main/java/com/reactnative/skia/PlatformContext.java index e20cca3e20..0269a41df7 100644 --- a/packages/skia/android/src/main/java/com/reactnative/skia/PlatformContext.java +++ b/packages/skia/android/src/main/java/com/reactnative/skia/PlatformContext.java @@ -182,7 +182,7 @@ public void run() { // Whether the app is in the foreground (DawnContext::setForeground). private static native void setForegroundNative(boolean foreground); - // Frees the GPU memory nothing uses (DawnContext::purgeGpuResources). + // Frees the GPU memory nothing uses (RNSkGpuPurge). private static native void purgeGpuResourcesNative(); // Where Dawn's blob cache keeps its entries (DawnContext::setCacheDirectory). diff --git a/packages/skia/apple/RNSkApplePlatformContext.mm b/packages/skia/apple/RNSkApplePlatformContext.mm index f797b260d0..37249ccdca 100644 --- a/packages/skia/apple/RNSkApplePlatformContext.mm +++ b/packages/skia/apple/RNSkApplePlatformContext.mm @@ -6,6 +6,7 @@ #include #include "RNDawnContext.h" +#include "RNSkGpuPurge.h" #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdocumentation" @@ -187,7 +188,7 @@ object:nil queue:nil usingBlock:^(NSNotification *) { - DawnContext::purgeGpuResources(); + RNSkGpuPurge::request(); }]; }); #endif // !TARGET_OS_OSX diff --git a/packages/skia/cpp/api/JsiSkApi.h b/packages/skia/cpp/api/JsiSkApi.h index eeaeba3cb2..58427d1bbc 100644 --- a/packages/skia/cpp/api/JsiSkApi.h +++ b/packages/skia/cpp/api/JsiSkApi.h @@ -14,6 +14,7 @@ #include "rnskia/RNSkRuntimeScheduler.h" #include "rnskia/RNDawnContext.h" +#include "rnskia/RNSkGpuPurge.h" #include "JsiSkAnimatedImage.h" #include "JsiSkAnimatedImageFactory.h" @@ -171,7 +172,7 @@ class JsiSkApi : public JsiSkNativeObject { JSI_HOST_FUNCTION(purgeGpuResources) { // The recorders of this thread, which only it may touch, then Dawn. DawnContext::trimThreadRecorders(std::chrono::milliseconds(0), true); - DawnContext::purgeGpuResources(); + RNSkGpuPurge::request(); return jsi::Value::undefined(); } JSI_HOST_FUNCTION(getNativeDevice) { diff --git a/packages/skia/cpp/api/JsiSkCanvas.h b/packages/skia/cpp/api/JsiSkCanvas.h index 7f88c14a7b..2010a30117 100644 --- a/packages/skia/cpp/api/JsiSkCanvas.h +++ b/packages/skia/cpp/api/JsiSkCanvas.h @@ -28,6 +28,7 @@ #include "rnskia/RNDawnContext.h" #include "rnskia/RNSkAtlas.h" +#include "rnskia/RNSkSurfaceRecorder.h" #include @@ -54,11 +55,11 @@ namespace jsi = facebook::jsi; * surface deregisters itself from its recorder. */ struct SurfaceAndRecorder { - SurfaceAndRecorder(std::shared_ptr recorder, + SurfaceAndRecorder(std::shared_ptr recorder, sk_sp surface) : recorder(std::move(recorder)), surface(std::move(surface)) {} // Destroyed last. - std::shared_ptr recorder; + std::shared_ptr recorder; sk_sp surface; }; @@ -527,7 +528,7 @@ class JsiSkCanvas : public JsiSkNativeObject { if (_surface) { auto snapshot = _surface->makeImageSnapshot(); if (_recorder) { - DawnContext::getInstance().submitSurface(*_recorder); + _recorder->flush(); } return JsiSkImage::readPixelsAsync( runtime, getContext(), std::move(snapshot), *info, srcX, srcY); @@ -625,7 +626,7 @@ class JsiSkCanvas : public JsiSkNativeObject { "disposed or whose recording has finished."); } if (_recorder) { - _recorder->markPending(); + _recorder->markDirty(); } return _canvas; } @@ -635,7 +636,7 @@ class JsiSkCanvas : public JsiSkNativeObject { // fall back to a surface snapshot on Graphite, which has no synchronous // canvas readback. void setSurface(sk_sp surface, - std::shared_ptr recorder) { + std::shared_ptr recorder) { _surface = std::move(surface); _recorder = std::move(recorder); } @@ -653,6 +654,6 @@ class JsiSkCanvas : public JsiSkNativeObject { private: SkCanvas *_canvas = nullptr; sk_sp _surface; - std::shared_ptr _recorder; + std::shared_ptr _recorder; }; } // namespace RNSkia diff --git a/packages/skia/cpp/api/JsiSkSurface.h b/packages/skia/cpp/api/JsiSkSurface.h index 50227df25b..62cfd13b6e 100644 --- a/packages/skia/cpp/api/JsiSkSurface.h +++ b/packages/skia/cpp/api/JsiSkSurface.h @@ -14,6 +14,7 @@ #include "JsiSkImage.h" #include "rnskia/RNDawnContext.h" +#include "rnskia/RNSkSurfaceRecorder.h" #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdocumentation" @@ -34,7 +35,7 @@ class JsiSkSurface JsiSkSurface(std::shared_ptr context, sk_sp surface, - std::shared_ptr recorder = nullptr) + std::shared_ptr recorder = nullptr) : JsiSkWrappingSkPtrNativeObject( std::move(context), std::move(surface)), _recorder(std::move(recorder)) {} @@ -79,9 +80,8 @@ class JsiSkSurface // only Graphite-backed surfaces need to snap and submit a recording. One // made on a GPU device lost since submits nothing (see DawnContext). if (_recorder) { - DawnContext::getInstance().submitSurface( - *_recorder, sync ? skgpu::graphite::SyncToCpu::kYes - : skgpu::graphite::SyncToCpu::kNo); + _recorder->flush(sync ? skgpu::graphite::SyncToCpu::kYes + : skgpu::graphite::SyncToCpu::kNo); } } @@ -115,7 +115,7 @@ class JsiSkSurface // A raster surface (e.g. Skia.Surface.Make) has no Graphite recorder; its // snapshot is already a valid CPU image, so skip the recording submit. if (_recorder) { - DawnContext::getInstance().submitSurface(*_recorder); + _recorder->flush(); } if (count > 1 && arguments[1].isObject()) { auto jsiImage = getJsiObject(runtime, arguments[1]); @@ -201,7 +201,7 @@ class JsiSkSurface // What was drawn and not flushed still reaches the texture, which may // outlive the surface (Surface.MakeFromGPUTexture, asImage()). if (_recorder) { - DawnContext::getInstance().submitPendingSurface(*_recorder); + _recorder->flushIfDirty(); } // dispose(): the canvas lets go of its reference too, so that the texture // is freed now rather than once the canvas is collected (#4275). Drawing @@ -215,7 +215,7 @@ class JsiSkSurface private: void releaseSurface() { // Destroying a Graphite surface deregisters it from its recorder, which is - // the surface's alone (see DawnContext::SurfaceRecorder): whichever thread + // the surface's alone (see RNSkSurfaceRecorder): whichever thread // lets go of both last destroys them, the GC's included. Nothing else can // be using them then. auto released = @@ -224,7 +224,7 @@ class JsiSkSurface } // The recorder of the surface, for it alone; nullptr for a raster surface. - std::shared_ptr _recorder; + std::shared_ptr _recorder; std::shared_ptr _canvas; }; diff --git a/packages/skia/cpp/api/JsiSkSurfaceFactory.h b/packages/skia/cpp/api/JsiSkSurfaceFactory.h index 64794deb7c..b370a57659 100644 --- a/packages/skia/cpp/api/JsiSkSurfaceFactory.h +++ b/packages/skia/cpp/api/JsiSkSurfaceFactory.h @@ -12,6 +12,7 @@ #include "JsiSkSurface.h" #include "rnskia/RNDawnContext.h" +#include "rnskia/RNSkSurfaceRecorder.h" #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdocumentation" @@ -55,11 +56,10 @@ class JsiSkSurfaceFactory : public JsiSkNativeObject { } } // A recorder of its own: the surface may be drawn into on another thread - // than this one (see DawnContext::SurfaceRecorder). - auto &dawn = DawnContext::getInstance(); - auto recorder = dawn.makeSurfaceRecorder(width, height); - auto surface = - dawn.MakeOffscreen(width, height, useP3ColorSpace, recorder.get()); + // than this one (see RNSkSurfaceRecorder). + auto recorder = RNSkSurfaceRecorder::Make(width, height); + auto surface = DawnContext::getInstance().MakeOffscreen( + width, height, useP3ColorSpace, recorder->get()); return makeJsiObject( runtime, std::make_shared( getContext(), std::move(surface), std::move(recorder))); @@ -79,11 +79,11 @@ class JsiSkSurfaceFactory : public JsiSkNativeObject { // the surface exists. wgpu::Texture texture = gpuTextureFromValue(runtime, arguments[0], "MakeFromGPUTexture"); - auto &dawn = DawnContext::getInstance(); auto recorder = - dawn.makeSurfaceRecorder(static_cast(texture.GetWidth()), - static_cast(texture.GetHeight())); - auto surface = dawn.MakeSurfaceFromTexture(texture, *recorder); + RNSkSurfaceRecorder::Make(static_cast(texture.GetWidth()), + static_cast(texture.GetHeight())); + auto surface = DawnContext::getInstance().MakeSurfaceFromTexture( + texture, recorder->get()); if (surface == nullptr) { throw std::runtime_error( "MakeFromGPUTexture: failed to wrap the texture"); diff --git a/packages/skia/cpp/rnskia/RNDawnContext.h b/packages/skia/cpp/rnskia/RNDawnContext.h index a20ddcd7d4..b9e6b297d4 100644 --- a/packages/skia/cpp/rnskia/RNDawnContext.h +++ b/packages/skia/cpp/rnskia/RNDawnContext.h @@ -119,6 +119,15 @@ class DawnContext { /** The context, or nullptr when the GPU is unavailable. Never throws. */ static DawnContext *tryGetInstance() noexcept { return probe().instance; } + /** + The context if the GPU was probed already, nullptr otherwise. Unlike + tryGetInstance() it never probes: for what must not start the GPU itself + (a memory warning, see RNSkGpuPurge). Any thread. + */ + static DawnContext *peekInstance() noexcept { + return probedInstance().load(std::memory_order_acquire); + } + /** Probes the GPU if not done yet and describes it. While the device in use is lost (see isDeviceLost), unavailable, with the loss as the error. @@ -214,11 +223,23 @@ class DawnContext { /** Sets isForeground(); the platform calls it from its main thread. */ static void setForeground(bool foreground) noexcept { - // Sequentially consistent, with purgeOnForeground: see reduceMemory(). - foregroundFlag().store(foreground); - if (foreground && purgeOnForeground().exchange(false)) { - purgeGpuResources(); + auto &waiters = foregroundWaiters(); + { + // Under the lock, so that waitForForeground() cannot miss it. + std::lock_guard lock(waiters.mutex); + foregroundFlag().store(foreground, std::memory_order_release); } + waiters.condition.notify_all(); + } + + /** + Blocks until isForeground(). For a background thread whose GPU work can + wait (see RNSkGpuPurge): iOS refuses GPU work in the background. + */ + static void waitForForeground() { + auto &waiters = foregroundWaiters(); + std::unique_lock lock(waiters.mutex); + waiters.condition.wait(lock, []() { return isForeground(); }); } /** @@ -388,89 +409,30 @@ class DawnContext { } /** - The recorder of the calling thread, for the device in use: a thread - whose recorder was made for a lost device gets a new one, and the old one - stays alive for the surfaces made on it (which draw nothing from then on). - Throws when no recorder can be made. - */ - skgpu::graphite::Recorder *getRecorder() { - return currentRecorder(threadSlot()); - } - - /** - A recorder of its own for an offscreen surface JS made (see - MakeOffscreen): a surface may be drawn into on another thread than the one - that made it, which would race with whatever that thread records, or - trims, on its own recorder. Used by one thread at a time, as the surface - is. Must outlive the surface (see JsiSkSurface). One made for a device - lost since submits nothing. + A recorder of its own, as makeRecorder(), for an offscreen surface (see + RNSkSurfaceRecorder): with a GPU budget of its own, and `generation` + receives the generation it was made for, to submit its recordings with + (see submitRecording). Throws when no recorder can be made. Any thread. */ - class SurfaceRecorder { - public: - SurfaceRecorder(std::unique_ptr recorder, - uint64_t generation) - : _recorder(std::move(recorder)), _generation(generation) {} - - skgpu::graphite::Recorder *get() const { return _recorder.get(); } - - /** The surface is about to be drawn into (see submitPendingSurface). */ - void markPending() { _pending = true; } - - private: - friend class DawnContext; - // Whether something may be recorded and not submitted: a new surface is - // yet to be cleared. - bool _pending = true; - std::unique_ptr _recorder; - uint64_t _generation; - // The latest trim (see submitSurface). - std::chrono::steady_clock::time_point _lastTrim = - std::chrono::steady_clock::now(); - }; - - /** See SurfaceRecorder. Throws when no recorder can be made. Any thread. */ - std::shared_ptr makeSurfaceRecorder(int width, int height) { + std::unique_ptr + makeRecorder(size_t budget, uint64_t *generation) { std::lock_guard lock(_mutex); - auto recorder = makeRecorderLocked( - /* forUploads= */ false, surfaceBudget(width, height)); + auto recorder = makeRecorderLocked(/* forUploads= */ false, budget); if (recorder == nullptr) { throw std::runtime_error("Failed to create graphite context"); } - return std::make_shared( - std::move(recorder), _current.load(std::memory_order_acquire)->id); - } - - /** - Snaps what was recorded into the surface of the recorder and runs it on - the GPU (see submitRecording), then, at most once per kThreadTrimDelay, - frees what the recorder cached and did not use for that long. Called by - the thread using the surface. - */ - bool submitSurface( - SurfaceRecorder &surface, - skgpu::graphite::SyncToCpu syncToCpu = skgpu::graphite::SyncToCpu::kNo) { - surface._pending = false; - const bool inserted = - snapAndRun(surface.get(), syncToCpu, surface._generation); - const auto now = std::chrono::steady_clock::now(); - if (now - surface._lastTrim >= kThreadTrimDelay) { - surface._lastTrim = now; - surface.get()->performDeferredCleanup(kThreadTrimDelay); - } - // What the drawing uploaded is the upload recorder's of this thread. - trimThreadIfDue(); - return inserted; + *generation = _current.load(std::memory_order_acquire)->id; + return recorder; } /** - Submits what was drawn into the surface since its last submit, if anything: - its recorder is about to go, and what it recorded with it. Called by the - thread using the surface. + The recorder of the calling thread, for the device in use: a thread + whose recorder was made for a lost device gets a new one, and the old one + stays alive for the surfaces made on it (which draw nothing from then on). + Throws when no recorder can be made. */ - void submitPendingSurface(SurfaceRecorder &surface) { - if (surface._pending) { - submitSurface(surface); - } + skgpu::graphite::Recorder *getRecorder() { + return currentRecorder(threadSlot()); } /** A thread's recorder with the generation it was made for. */ @@ -533,52 +495,19 @@ class DawnContext { instance->checkFinishedWork(); } - /** - Hands the GPU memory nothing uses back to the system: Dawn keeps the - memory of disposed surfaces and images for reuse otherwise. What is alive - keeps its content and its caches. Returns at once; a background thread - does the work, for as long as Dawn says deletions are pending and then - once more after the render threads trimmed their own recorders. Requests - made meanwhile are served by the same thread. Nothing happens before the - GPU is first used, nor, on iOS, where GPU work is refused in the - background (see isForeground). Any thread. - */ - static void purgeGpuResources() noexcept { - auto *instance = probedInstance().load(std::memory_order_acquire); - if (instance == nullptr) { - return; - } - auto &purge = purgeState(); - { - std::lock_guard lock(purge.mutex); - purge.requested = true; - if (purge.running) { - return; - } - purge.running = true; - } - try { - std::thread([instance]() { instance->runPurges(); }).detach(); - } catch (const std::exception &e) { - RNSkLogger::logToConsole("Purging GPU resources failed: %s", e.what()); - std::lock_guard lock(purge.mutex); - purge.running = false; - } - } - /** Snaps what the recorder recorded and runs it on the GPU. `recorder` is a - thread's (see getRecorder), not a surface's (see submitSurface); any - other submits nothing. A recording made for a lost device (see - generation()) is dropped: nothing can run it, and the device in use would - refuse its resources. Called on the recorder's thread. Returns whether - the recording runs: false when there was nothing to run, when it was - dropped, or when Graphite rejected it (which is logged). + thread's (see getRecorder); any other submits nothing. A recording made + for a lost device (see generation()) is dropped: nothing can run it, and + the device in use would refuse its resources. Called on the recorder's + thread. Returns whether the recording runs: false when there was nothing + to run, when it was dropped, or when Graphite rejected it (which is + logged). */ bool submitRecording( skgpu::graphite::Recorder *recorder, skgpu::graphite::SyncToCpu syncToCpu = skgpu::graphite::SyncToCpu::kNo) { - const bool inserted = snapAndRun(recorder, syncToCpu); + const bool inserted = submitRecording(recorder, std::nullopt, syncToCpu); if (recorder != nullptr && recorder == threadSlot().recorder.get()) { trimThreadIfDue(); } @@ -586,60 +515,14 @@ class DawnContext { } /** - How long a resource a thread outside the render pool cached went unused - before that thread lets go of it, and how often at most it checks (see - trimThreadIfDue): the pool's own delay (RNSkThreadPool::kIdleDelay). - */ - static constexpr std::chrono::milliseconds kThreadTrimDelay = - RNSkThreadPool::kIdleDelay; - - /** - Trims the recorders of the calling thread of what went unused for - kThreadTrimDelay, at most once per kThreadTrimDelay: what a thread outside - the render pool (the JS thread, a worklet runtime) does after its submits - (see submitRecording), since nothing else would. Its drawing recorder - otherwise keeps every scratch texture its snapshots and uploads let go of, - up to Graphite's budget (256 MB by default), for as long as the thread - lives. The render pool trims its threads itself, once idle (see - RNSkGraphiteProducer). Never makes a recorder. Any thread. - */ - static void trimThreadIfDue() { - if (RNSkThreadPool::isPoolThread()) { - return; - } - auto &slot = threadSlot(); - if (slot.recorder == nullptr && uploadSlot().recorder == nullptr) { - return; - } - const auto now = std::chrono::steady_clock::now(); - if (now - slot.lastTrim < kThreadTrimDelay) { - return; - } - slot.lastTrim = now; - trimThreadRecorders(kThreadTrimDelay, false); - } - -private: - /** - The budget of the recorder of a surface of that size: its layers and blurs - take textures of its size, up to several at once. Graphite's default, made - for a thread's whole content, is the most it gets. + Same, for a recorder made for `generation`: one of its own, which the + context does not track (see makeRecorder). Without a generation, a + thread's, looked up. Never trims: an offscreen surface does that for its + own recorder (see RNSkSurfaceRecorder). */ - static size_t surfaceBudget(int width, int height) { - constexpr uint64_t kMin = 32 * 1024 * 1024; - // 64 bits: the product overflows a 32-bit size_t. - const auto bytes = static_cast(std::max(width, 0)) * - static_cast(std::max(height, 0)) * 4; - return static_cast(std::clamp( - bytes * 8, kMin, - skgpu::graphite::RecorderOptions::kDefaultRecorderBudget)); - } - - // `generation` is the one the recorder was made for; looked up, for a - // thread's recorder, when absent. - bool snapAndRun(skgpu::graphite::Recorder *recorder, - skgpu::graphite::SyncToCpu syncToCpu, - std::optional generation = std::nullopt) { + bool submitRecording(skgpu::graphite::Recorder *recorder, + std::optional generation, + skgpu::graphite::SyncToCpu syncToCpu) { if (recorder == nullptr) { return false; } @@ -672,7 +555,38 @@ class DawnContext { return inserted; } -public: + /** + The throttle of trimThreadIfDue(), and how long a resource went unused + before it goes: the delay of the render pool's idle task + (RNSkThreadPool::kIdleDelay). + */ + static constexpr std::chrono::milliseconds kThreadTrimDelay = + RNSkThreadPool::kIdleDelay; + + /** + trimThreadRecorders(), throttled to once per kThreadTrimDelay: called + after a submit by a thread outside the render pool (the JS thread, a + worklet runtime), which has no idle task to trim it. Its drawing recorder + otherwise keeps every scratch texture, up to Graphite's budget (256 MB by + default), for as long as the thread lives. Nothing happens on a render + thread (see RNSkGraphiteProducer). Never makes a recorder. Any thread. + */ + static void trimThreadIfDue() { + if (RNSkThreadPool::isPoolThread()) { + return; + } + auto &slot = threadSlot(); + if (slot.recorder == nullptr && uploadSlot().recorder == nullptr) { + return; + } + const auto now = std::chrono::steady_clock::now(); + if (now - slot.lastTrim < kThreadTrimDelay) { + return; + } + slot.lastTrim = now; + trimThreadRecorders(kThreadTrimDelay, false); + } + /** Replays the recordings, in order, onto the target surface (a deferred canvas target) and submits them as one batch. A recording Graphite @@ -762,10 +676,10 @@ class DawnContext { } // Create an offscreen surface, on the recorder of this thread unless given - // one of its own (see SurfaceRecorder). - sk_sp MakeOffscreen(int width, int height, - bool useP3ColorSpace = false, - SurfaceRecorder *recorder = nullptr) { + // one of its own (see RNSkSurfaceRecorder). + sk_sp + MakeOffscreen(int width, int height, bool useP3ColorSpace = false, + skgpu::graphite::Recorder *recorder = nullptr) { sk_sp colorSpace = useP3ColorSpace ? SkColorSpace::MakeRGB(SkNamedTransferFn::kSRGB, SkNamedGamut::kDisplayP3) @@ -774,7 +688,7 @@ class DawnContext { SkImageInfo::Make(width, height, DawnUtils::PreferedColorType, kPremul_SkAlphaType, colorSpace); sk_sp surface = SkSurfaces::RenderTarget( - recorder != nullptr ? recorder->get() : getRecorder(), info); + recorder != nullptr ? recorder : getRecorder(), info); if (!surface) { throw std::runtime_error("Failed to create offscreen Skia surface."); @@ -857,9 +771,9 @@ class DawnContext { // The texture must have RenderAttachment usage; give it TextureBinding too // to sample it from WebGPU (e.g. as a three.js texture) after each flush. // The surface retains the texture for its lifetime. - // `recorder` is the surface's own (see SurfaceRecorder). + // `recorder` is the surface's own (see RNSkSurfaceRecorder). sk_sp MakeSurfaceFromTexture(wgpu::Texture texture, - SurfaceRecorder &recorder) { + skgpu::graphite::Recorder *recorder) { if (!texture) { return nullptr; } @@ -878,7 +792,7 @@ class DawnContext { // The color type is derived from the texture format. return SkSurfaces::WrapBackendTexture( - recorder.get(), backendTexture, + recorder, backendTexture, nullptr, // colorspace nullptr, // surfaceProps [](void *context) { @@ -975,7 +889,7 @@ class DawnContext { or for one destroyed already. Any thread. */ void destroyRetiredDevice(uint64_t generation) { - // Before the context lock, as in reduceMemory(). + // Before the context lock, as in reduceMemoryUsage(). std::lock_guard destroyLock(_destroyMutex); std::lock_guard lock(_mutex); for (auto *retired : _retired) { @@ -987,6 +901,39 @@ class DawnContext { } } + /** + One pass of Dawn's ReduceMemoryUsage() on the device in use: Dawn gives + the memory it keeps for reuse (of disposed surfaces and images) back to + the system. Returns whether Dawn still has deletions pending on submitted + work, in which case another pass shortly frees more. Nothing happens + while the device is lost. Any thread; RNSkGpuPurge decides when. + */ + bool reduceMemoryUsage() noexcept { + // Keeps destroyRetiredDevice() from destroying the device under Dawn. + std::lock_guard destroyLock(_destroyMutex); + wgpu::Device device; + { + std::lock_guard lock(_mutex); + auto *current = _current.load(std::memory_order_acquire); + if (current->lost.load(std::memory_order_acquire)) { + return false; + } + tick(); + current->context->checkAsyncWorkCompletion(); + // Both may have waited for a device.destroy() from JS (the device is + // shared with react-native-webgpu) to finish. One that starts after + // this is caught by Dawn, in binaries built with + // dawn-patches/reduce-memory-usage-lost-device.patch + // (react-native-webgpu-dawn 158.0.0 is not). + if (current->lost.load(std::memory_order_acquire)) { + return false; + } + device = current->backendContext.fDevice; + } + // Outside the context lock, which frames need. + return dawn::native::ReduceMemoryUsage(device.Get()); + } + private: struct Probe { DawnContext *instance = nullptr; @@ -1065,8 +1012,19 @@ class DawnContext { return foreground; } - // The context once probed, for what must not probe the GPU itself (see - // purgeGpuResources). + // The threads waiting for the foreground (see waitForForeground). Never + // destroyed, as the flag. + struct ForegroundWaiters { + std::mutex mutex; + std::condition_variable condition; + }; + + static ForegroundWaiters &foregroundWaiters() noexcept { + static auto *waiters = new ForegroundWaiters(); + return *waiters; + } + + // See peekInstance. static std::atomic &probedInstance() noexcept { static std::atomic instance{nullptr}; return instance; @@ -1327,9 +1285,9 @@ class DawnContext { */ ImageProvider::Upload upload(const sk_sp &image, bool mipmapped) { // A recorder of its own: snapping the recorder of this thread would also - // submit what was recorded on it so far. It - // only uploads, so it keeps Skia's default image provider rather than - // the image cache, which uploads through here. + // submit what was recorded on it so far. It only uploads, so it keeps + // Skia's default image provider rather than the image cache, which + // uploads through here. auto &slot = uploadSlot(); auto *recorder = currentRecorder(slot, /* forUploads= */ true); ImageProvider::Upload result; @@ -1392,92 +1350,6 @@ class DawnContext { return slot; } - // A purge that could not run while the app was in the background. - static std::atomic &purgeOnForeground() noexcept { - static std::atomic flag{false}; - return flag; - } - - struct PurgeState { - std::mutex mutex; - bool running = false; - bool requested = false; - }; - - static PurgeState &purgeState() noexcept { - static auto *state = new PurgeState(); - return *state; - } - - // The purge thread (see purgeGpuResources). - void runPurges() noexcept { - auto &purge = purgeState(); - for (;;) { - { - std::lock_guard lock(purge.mutex); - if (!purge.requested) { - purge.running = false; - return; - } - purge.requested = false; - } - RNSkThreadPool::getInstance().requestIdleTask(); - reduceMemory(); - // The render threads trim their recorders kIdleDelay after being asked. - std::this_thread::sleep_for(RNSkThreadPool::kIdleDelay + - std::chrono::milliseconds(500)); - reduceMemory(); - } - } - - // Asks Dawn to free what it holds for reuse, and again while it says - // deletions are still pending on submitted work. - void reduceMemory() noexcept { - constexpr int kMaxPasses = 10; - for (int pass = 0; pass < kMaxPasses; pass++) { -#if defined(__APPLE__) - if (!isForeground()) { - // Asked for again once the app is back (see setForeground). - purgeOnForeground().store(true); - // The app may have come back in between, before it could see the - // request: whichever of the two takes the request serves it. - if (!foregroundFlag().load() || !purgeOnForeground().exchange(false)) { - return; - } - } -#endif - { - // Keeps destroyRetiredDevice() from destroying the device under Dawn; - // not held while waiting below. - std::lock_guard destroyLock(_destroyMutex); - wgpu::Device device; - { - std::lock_guard lock(_mutex); - auto *current = _current.load(std::memory_order_acquire); - if (current->lost.load(std::memory_order_acquire)) { - return; - } - tick(); - current->context->checkAsyncWorkCompletion(); - // Both may have waited for a device.destroy() from JS (the device is - // shared with react-native-webgpu) to finish. One that starts after - // this is caught by Dawn, in binaries built with - // dawn-patches/reduce-memory-usage-lost-device.patch - // (react-native-webgpu-dawn 158.0.0 is not). - if (current->lost.load(std::memory_order_acquire)) { - return; - } - device = current->backendContext.fDevice; - } - // Outside the context lock, which frames need. - if (!dawn::native::ReduceMemoryUsage(device.Get())) { - return; - } - } - std::this_thread::sleep_for(std::chrono::milliseconds(100)); - } - } - /** The recorder of a thread that ended (see ThreadRecorder). */ void forgetRecorder(const skgpu::graphite::Recorder *recorder) noexcept { std::lock_guard lock(_mutex); @@ -1620,8 +1492,8 @@ class DawnContext { // every view (isDeviceLost, isCurrent), hence atomic. std::atomic _current{nullptr}; std::vector _retired; - // Held while Dawn is asked to free memory of a device (see reduceMemory) - // and while one is destroyed. Taken before _mutex. + // Held while Dawn is asked to free memory of a device (see + // reduceMemoryUsage) and while one is destroyed. Taken before _mutex. std::mutex _destroyMutex; uint64_t _lastGenerationId = 0; // Guards every Context operation, and the replacement of the device. diff --git a/packages/skia/cpp/rnskia/RNSkGpuPurge.h b/packages/skia/cpp/rnskia/RNSkGpuPurge.h new file mode 100644 index 0000000000..4f8aaa592c --- /dev/null +++ b/packages/skia/cpp/rnskia/RNSkGpuPurge.h @@ -0,0 +1,109 @@ +#pragma once + +#include +#include +#include +#include + +#include "RNDawnContext.h" +#include "RNSkThreadPool.h" +#include "utils/RNSkLog.h" + +namespace RNSkia { + +/** + * Skia.purgeGpuResources(), which the platform also asks for when memory + * runs low: gives the GPU memory nothing uses back to the system. Dawn keeps + * the memory of disposed surfaces and images for reuse otherwise. What is + * alive keeps its content and its caches. + * + * 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. + * + * One run: + * 1. asks the render threads to trim their recorders (their idle task); + * 2. has Dawn free what it can now (DawnContext::reduceMemoryUsage); + * 3. does that once more after the render threads trimmed. + */ +class RNSkGpuPurge { +public: + /** Any thread. Nothing happens before the GPU is first used. */ + static void request() noexcept { + auto *context = DawnContext::peekInstance(); + if (context == nullptr) { + return; + } + auto &state = getState(); + { + std::lock_guard lock(state.mutex); + state.requested = true; + if (state.running) { + return; + } + state.running = true; + } + try { + std::thread([context]() { runRequests(context); }).detach(); + } catch (const std::exception &e) { + RNSkLogger::logToConsole("Purging GPU resources failed: %s", e.what()); + std::lock_guard lock(state.mutex); + state.running = false; + } + } + +private: + 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: a request may come while the process exits. + static State &getState() noexcept { + static auto *state = new State(); + return *state; + } + + // The purge thread: runs until no request is left. + static void runRequests(DawnContext *context) noexcept { + auto &state = getState(); + for (;;) { + { + std::lock_guard lock(state.mutex); + if (!state.requested) { + state.running = false; + return; + } + state.requested = false; + } + RNSkThreadPool::getInstance().requestIdleTask(); + reduceMemoryUsage(context); + // The render threads run their idle task kIdleDelay after the request. + std::this_thread::sleep_for(RNSkThreadPool::kIdleDelay + + std::chrono::milliseconds(500)); + reduceMemoryUsage(context); + } + } + + // Dawn frees what it can, again for as long as it says deletions are + // pending on submitted work. + static void reduceMemoryUsage(DawnContext *context) noexcept { + constexpr int kMaxPasses = 10; + for (int pass = 0; pass < kMaxPasses; pass++) { +#if defined(__APPLE__) + // iOS refuses GPU work in the background: the purge goes on once the + // app is back. + DawnContext::waitForForeground(); +#endif + if (!context->reduceMemoryUsage()) { + return; + } + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + } + } +}; + +} // namespace RNSkia diff --git a/packages/skia/cpp/rnskia/RNSkSurfaceRecorder.h b/packages/skia/cpp/rnskia/RNSkSurfaceRecorder.h new file mode 100644 index 0000000000..1f7e6647e4 --- /dev/null +++ b/packages/skia/cpp/rnskia/RNSkSurfaceRecorder.h @@ -0,0 +1,115 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +#include "RNDawnContext.h" + +#include "include/gpu/graphite/GraphiteTypes.h" +#include "include/gpu/graphite/Recorder.h" + +namespace RNSkia { + +/** + * The Graphite recorder of one offscreen surface JS made + * (Skia.Surface.MakeOffscreen, MakeFromGPUTexture). + * + * A recorder has a single owner. A surface that borrowed the recorder of the + * thread that made it (DawnContext::getRecorder) would race with that thread + * as soon as another one draws into it, a worklet for instance. So each + * surface owns its recorder, and whichever thread uses the surface uses the + * recorder: one thread at a time, as for the surface itself. + * + * The recorder must outlive the surface (see SurfaceAndRecorder). One made + * for a GPU device lost since submits nothing (see DawnContext::generation). + */ +class RNSkSurfaceRecorder { +public: + /** + The recorder of a surface of that size, for the GPU device in use. Throws + when none can be made. Any thread. + */ + static std::shared_ptr Make(int width, int height) { + uint64_t generation = 0; + auto recorder = DawnContext::getInstance().makeRecorder( + budgetFor(width, height), &generation); + return std::shared_ptr( + new RNSkSurfaceRecorder(std::move(recorder), generation)); + } + + skgpu::graphite::Recorder *get() const { return _recorder.get(); } + + /** Something is about to be drawn into the surface (see flushIfDirty). */ + void markDirty() { _dirty = true; } + + /** + surface.flush(): snaps what was drawn into the surface and submits it to + the GPU. Returns whether it runs (see DawnContext::submitRecording). + Called by the thread using the surface. + */ + bool flush( + skgpu::graphite::SyncToCpu syncToCpu = skgpu::graphite::SyncToCpu::kNo) { + _dirty = false; + const bool submitted = DawnContext::getInstance().submitRecording( + _recorder.get(), _generation, syncToCpu); + // Throttled: the scratch textures the recorder cached and did not use + // for a while go. + const auto now = std::chrono::steady_clock::now(); + if (now - _lastCleanup >= DawnContext::kThreadTrimDelay) { + _lastCleanup = now; + _recorder->performDeferredCleanup(DawnContext::kThreadTrimDelay); + } + // The images the drawing uploaded went through the upload recorder of + // this thread, not this one. + DawnContext::trimThreadIfDue(); + return submitted; + } + + /** + flush(), unless nothing was drawn since the last one. For a surface about + to go: what is not submitted by then is lost with the recorder, and the + texture may outlive both (asImage(), MakeFromGPUTexture). + */ + void flushIfDirty() { + if (_dirty) { + flush(); + } + } + +private: + RNSkSurfaceRecorder(std::unique_ptr recorder, + uint64_t generation) + : _recorder(std::move(recorder)), _generation(generation) {} + + /** + The GPU budget of the recorder: what it may keep cached for reuse. The + layers and blurs of a surface take textures of its size, several at once, + hence 8 times its pixels, and no less than 32 MB. Graphite's default (256 + MB, made for a thread's whole content) is the most it gets. + */ + static size_t budgetFor(int width, int height) { + constexpr uint64_t kMin = 32 * 1024 * 1024; + // 64 bits: the product overflows a 32-bit size_t. + const auto bytes = static_cast(std::max(width, 0)) * + static_cast(std::max(height, 0)) * 4; + return static_cast(std::clamp( + bytes * 8, kMin, + skgpu::graphite::RecorderOptions::kDefaultRecorderBudget)); + } + + std::unique_ptr _recorder; + // The GPU device the recorder was made for (see DawnContext::generation). + uint64_t _generation; + // Whether something was drawn and not submitted. A new surface is dirty: + // its initial clear is yet to be submitted. + bool _dirty = true; + // The latest cleanup (see flush). + std::chrono::steady_clock::time_point _lastCleanup = + std::chrono::steady_clock::now(); +}; + +} // namespace RNSkia From 509fef283955561bc2b68b750662f6eabace064b Mon Sep 17 00:00:00 2001 From: William Candillon Date: Wed, 25 Nov 2026 07:57:31 +0100 Subject: [PATCH 07/15] test(graphite): e2e for purgeGpuResources, narrow its documentation --- apps/docs/docs/animations/textures.md | 24 +++++++- .../__tests__/e2e/PurgeGpuResources.spec.tsx | 55 +++++++++++++++++++ packages/skia/src/skia/types/Skia.ts | 17 ++++-- 3 files changed, 89 insertions(+), 7 deletions(-) create mode 100644 packages/skia/src/renderer/__tests__/e2e/PurgeGpuResources.spec.tsx diff --git a/apps/docs/docs/animations/textures.md b/apps/docs/docs/animations/textures.md index 41f56f7769..027a6f0749 100644 --- a/apps/docs/docs/animations/textures.md +++ b/apps/docs/docs/animations/textures.md @@ -205,6 +205,28 @@ A surface must only be used by one thread at a time. Skia frees what the cache has not used for a few seconds as you draw into the surface. The rest goes with the surface: call `dispose()` once you are done with it. Keep a snapshot (`makeImageSnapshot()`) if you still need its content. -Disposed surfaces leave their memory to Skia, for the next ones. `Skia.purgeGpuResources()` hands what nothing uses back to the system, in the background: call it after disposing of many surfaces, at the end of an export for instance, not every frame. +Disposed surfaces leave their memory to Skia, for the next ones. + +### Purging GPU memory + +**Most apps should never call `Skia.purgeGpuResources()`.** Dispose of the surfaces and images you are done with, and Skia reuses their memory. When the system runs short of memory, React Native Skia purges on its own: on an iOS memory warning, and on Android on `onLowMemory()` and on `onTrimMemory()` from `TRIM_MEMORY_BACKGROUND`. + +The one case for calling it is a one-off peak followed by a long stretch that needs far less GPU memory, while the app stays in the foreground. For example, a video export just finished and the app is back to a light screen: + +```tsx +// The export is over, and no other one follows +exportSurfaces.forEach((surface) => surface.dispose()); +Skia.purgeGpuResources(); +``` + +Do not call it: + +- in a render loop, or after each `dispose()`; +- when a component unmounts or on navigation: the next screen usually wants that memory back; +- to fix a leak or an out-of-memory error: it only returns memory that nothing uses, so a surface you have not disposed of stays. + +Purging too often makes an app slower: memory that Skia would have reused has to be requested from the system again. + +It returns right away and works in the background (on iOS, once the app is active). On the Web it does nothing: the browser manages GPU memory there. In a native app, Skia's GPU memory counts towards your app's, and the system can end the app for using too much of it. Textures can also be shared with WebGPU: see [WebGPU](/docs/webgpu). diff --git a/packages/skia/src/renderer/__tests__/e2e/PurgeGpuResources.spec.tsx b/packages/skia/src/renderer/__tests__/e2e/PurgeGpuResources.spec.tsx new file mode 100644 index 0000000000..0b901ac2a2 --- /dev/null +++ b/packages/skia/src/renderer/__tests__/e2e/PurgeGpuResources.spec.tsx @@ -0,0 +1,55 @@ +import { itRunsE2eOnly } from "../../../__tests__/setup"; +import { AlphaType, ColorType } from "../../../skia/types"; +import { surface } from "../setup"; + +// Whether memory goes back to the system cannot be seen from here: these check +// that purging leaves what is alive usable. +describe("purgeGpuResources", () => { + itRunsE2eOnly( + "keeps a surface and its image while others are disposed and purged", + async () => { + const result = await surface.eval( + (Skia, ctx) => { + const info = { + width: 16, + height: 16, + colorType: ctx.colorType, + alphaType: ctx.alphaType, + }; + const alive = Skia.Surface.MakeOffscreen(16, 16)!; + alive.getCanvas().drawColor(Skia.Color("cyan")); + alive.flush(); + const image = alive.makeImageSnapshot(); + const paint = Skia.Paint(); + paint.setColor(Skia.Color("red")); + paint.setMaskFilter(Skia.MaskFilter.MakeBlur(0, 8, true)); + for (let i = 0; i < 20; i++) { + const scratch = Skia.Surface.MakeOffscreen(256, 256)!; + scratch.getCanvas().drawCircle(128, 128, 64, paint); + scratch.flush(); + scratch.dispose(); + Skia.purgeGpuResources(); + } + // Both the image and the surface are still drawn with. + const target = Skia.Surface.MakeOffscreen(16, 16)!; + target.getCanvas().drawImage(image, 0, 0); + target.flush(); + const first = target.getCanvas().readPixels(0, 0, info); + alive.getCanvas().drawColor(Skia.Color("lime")); + alive.flush(); + const second = alive.getCanvas().readPixels(0, 0, info); + return Promise.all([first, second]).then((all) => + all.map((pixels) => + pixels ? Array.from(pixels.slice(0, 4)) : null + ) + ); + }, + { colorType: ColorType.RGBA_8888, alphaType: AlphaType.Unpremul } + ); + expect(result).toEqual([ + [0, 255, 255, 255], + [0, 255, 0, 255], + ]); + } + ); +}); diff --git a/packages/skia/src/skia/types/Skia.ts b/packages/skia/src/skia/types/Skia.ts index c87f933c75..0c7e4fb708 100644 --- a/packages/skia/src/skia/types/Skia.ts +++ b/packages/skia/src/skia/types/Skia.ts @@ -179,12 +179,17 @@ export interface Skia { Skottie: SkottieFactory; Recorder(): JsiRecorder; /** - * Hands the GPU memory nothing uses back to the system. Skia keeps the - * memory of disposed surfaces and images for reuse otherwise: call it after - * disposing of many of them, at the end of an export for instance, not - * every frame. What is alive is not affected. Returns right away; the - * memory is freed in the background, or once the app is active again on - * iOS. A no-op on the Web. + * Returns the GPU memory nothing uses to the system. Most apps should never + * call it: Skia reuses the memory of what you dispose of, and purges on its + * own when the system is short of memory. + * + * 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 `dispose()`, not on unmount: memory Skia would have reused has to be + * requested from the system again. What is alive is not affected. + * + * Returns right away; the memory is freed in the background, or once the + * app is active again on iOS. A no-op on the Web. */ purgeGpuResources(): void; /** From dc2b48152d01dda05e7ea23d3488d9ff289f616f Mon Sep 17 00:00:00 2001 From: William Candillon Date: Wed, 25 Nov 2026 08:07:39 +0100 Subject: [PATCH 08/15] chore(graphite): drop the ReduceMemoryUsage Dawn patch The pinned Dawn (1716e88cc9) checks for a lost device itself. --- packages/skia/cpp/rnskia/RNDawnContext.h | 4 +--- .../reduce-memory-usage-lost-device.patch | 22 ------------------- 2 files changed, 1 insertion(+), 25 deletions(-) delete mode 100644 packages/skia/scripts/dawn-patches/reduce-memory-usage-lost-device.patch diff --git a/packages/skia/cpp/rnskia/RNDawnContext.h b/packages/skia/cpp/rnskia/RNDawnContext.h index b9e6b297d4..fcab2ed54d 100644 --- a/packages/skia/cpp/rnskia/RNDawnContext.h +++ b/packages/skia/cpp/rnskia/RNDawnContext.h @@ -922,9 +922,7 @@ class DawnContext { current->context->checkAsyncWorkCompletion(); // Both may have waited for a device.destroy() from JS (the device is // shared with react-native-webgpu) to finish. One that starts after - // this is caught by Dawn, in binaries built with - // dawn-patches/reduce-memory-usage-lost-device.patch - // (react-native-webgpu-dawn 158.0.0 is not). + // this is caught by Dawn's ReduceMemoryUsage(). if (current->lost.load(std::memory_order_acquire)) { return false; } diff --git a/packages/skia/scripts/dawn-patches/reduce-memory-usage-lost-device.patch b/packages/skia/scripts/dawn-patches/reduce-memory-usage-lost-device.patch deleted file mode 100644 index 44dd00e0fc..0000000000 --- a/packages/skia/scripts/dawn-patches/reduce-memory-usage-lost-device.patch +++ /dev/null @@ -1,22 +0,0 @@ -[native] Do nothing in ReduceMemoryUsage on a lost device - -Destroy() frees the dynamic uploader, the memory block allocator and the -internal pipeline store, which ReduceMemoryUsage() then dereferences. The -caller cannot check for it: the device may be destroyed by another thread -right after. Both run under the device guard, so the check belongs here. - -Drop this patch when Dawn checks the state of the device itself. - ---- -diff --git a/src/dawn/native/Device.cpp b/src/dawn/native/Device.cpp ---- a/src/dawn/native/Device.cpp -+++ b/src/dawn/native/Device.cpp -@@ -2702,5 +2702,8 @@ - - bool DeviceBase::ReduceMemoryUsage() { - DAWN_ASSERT(IsLockedByCurrentThreadIfNeeded()); -+ if (IsLost()) { -+ return false; -+ } - if (ConsumedError(GetQueue()->CheckPassedSerials())) { - return false; From 0ecca4ab0566b51121be3234e3a3ac5440021782 Mon Sep 17 00:00:00 2001 From: William Candillon Date: Wed, 25 Nov 2026 10:10:44 +0100 Subject: [PATCH 09/15] refactor(graphite): split trimThreadRecorders, report memory events to RNSkGpuPurge - trimThreadRecorders(unusedFor, everything) was two operations behind a boolean. trimThreadRecorders(unusedFor) is the routine, by age; purgeThreadRecorders() frees all the recorders of a thread can let go of (an idle render thread, Skia.purgeGpuResources()). - The platform reports what the system said (onMemoryWarning, onLowMemory, onTrimMemory) and RNSkGpuPurge decides what calls for a purge, as GpuPurge does in react-native-webgpu. The threshold is no longer in Java. - The pass count and the delays of a purge, the trim level, and the age a busy render thread trims at are named constants. - The surface recorder calls its throttle a trim, as the thread recorders do. No change in behavior. --- .../android/cpp/jni/JniPlatformContext.cpp | 15 ++- .../cpp/jni/include/JniPlatformContext.h | 6 +- .../com/reactnative/skia/PlatformContext.java | 19 ++-- .../skia/apple/RNSkApplePlatformContext.mm | 2 +- packages/skia/cpp/api/JsiSkApi.h | 2 +- packages/skia/cpp/rnskia/RNDawnContext.h | 94 +++++++++++-------- packages/skia/cpp/rnskia/RNSkGpuPurge.h | 93 ++++++++++++++---- .../skia/cpp/rnskia/RNSkGraphiteProducer.cpp | 29 ++++-- .../skia/cpp/rnskia/RNSkSurfaceRecorder.h | 12 +-- 9 files changed, 184 insertions(+), 88 deletions(-) diff --git a/packages/skia/android/cpp/jni/JniPlatformContext.cpp b/packages/skia/android/cpp/jni/JniPlatformContext.cpp index 7599048621..d778a097bf 100644 --- a/packages/skia/android/cpp/jni/JniPlatformContext.cpp +++ b/packages/skia/android/cpp/jni/JniPlatformContext.cpp @@ -38,8 +38,10 @@ void JniPlatformContext::registerNatives() { JniPlatformContext::runMainThreadTasks), makeNativeMethod("setForegroundNative", JniPlatformContext::setForegroundNative), - makeNativeMethod("purgeGpuResourcesNative", - JniPlatformContext::purgeGpuResourcesNative), + makeNativeMethod("onLowMemoryNative", + JniPlatformContext::onLowMemoryNative), + makeNativeMethod("onTrimMemoryNative", + JniPlatformContext::onTrimMemoryNative), makeNativeMethod("setCacheDirectoryNative", JniPlatformContext::setCacheDirectoryNative), makeNativeMethod("setPixelDensityNative", @@ -100,8 +102,13 @@ void JniPlatformContext::setForegroundNative(jni::alias_ref, DawnContext::setForeground(foreground == JNI_TRUE); } -void JniPlatformContext::purgeGpuResourcesNative(jni::alias_ref) { - RNSkGpuPurge::request(); +void JniPlatformContext::onLowMemoryNative(jni::alias_ref) { + RNSkGpuPurge::onLowMemory(); +} + +void JniPlatformContext::onTrimMemoryNative(jni::alias_ref, + jint level) { + RNSkGpuPurge::onTrimMemory(level); } void JniPlatformContext::setCacheDirectoryNative( diff --git a/packages/skia/android/cpp/jni/include/JniPlatformContext.h b/packages/skia/android/cpp/jni/include/JniPlatformContext.h index 568ce4aa9b..714ed05837 100644 --- a/packages/skia/android/cpp/jni/include/JniPlatformContext.h +++ b/packages/skia/android/cpp/jni/include/JniPlatformContext.h @@ -33,8 +33,10 @@ class JniPlatformContext : public jni::HybridClass { // and outlives it. static void setForegroundNative(jni::alias_ref, jboolean foreground); - // The system is low on memory (see RNSkGpuPurge). - static void purgeGpuResourcesNative(jni::alias_ref); + // What the system says about memory, as it says it: RNSkGpuPurge decides + // what calls for a purge. + static void onLowMemoryNative(jni::alias_ref); + static void onTrimMemoryNative(jni::alias_ref, jint level); static void setCacheDirectoryNative(jni::alias_ref, jni::alias_ref directory); diff --git a/packages/skia/android/src/main/java/com/reactnative/skia/PlatformContext.java b/packages/skia/android/src/main/java/com/reactnative/skia/PlatformContext.java index 0269a41df7..1b9fbf6132 100644 --- a/packages/skia/android/src/main/java/com/reactnative/skia/PlatformContext.java +++ b/packages/skia/android/src/main/java/com/reactnative/skia/PlatformContext.java @@ -35,7 +35,9 @@ public class PlatformContext implements LifecycleEventListener { private static ParcelFileDescriptor sMainThreadWakeup; // The display density can change while the app runs (display size - // setting, foldables): the native side follows it. + // setting, foldables): the native side follows it. 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 (RNSkGpuPurge). private final ComponentCallbacks2 mComponentCallbacks = new ComponentCallbacks2() { @Override public void onConfigurationChanged(Configuration newConfig) { @@ -44,16 +46,12 @@ public void onConfigurationChanged(Configuration newConfig) { @Override public void onLowMemory() { - purgeGpuResourcesNative(); + onLowMemoryNative(); } @Override public void onTrimMemory(int level) { - // Android 14 and later never call onLowMemory(), and of the trim - // levels only send UI_HIDDEN (any app switch) and BACKGROUND. - if (level >= TRIM_MEMORY_BACKGROUND) { - purgeGpuResourcesNative(); - } + onTrimMemoryNative(level); } }; @@ -182,8 +180,11 @@ public void run() { // Whether the app is in the foreground (DawnContext::setForeground). private static native void setForegroundNative(boolean foreground); - // Frees the GPU memory nothing uses (RNSkGpuPurge). - private static native void purgeGpuResourcesNative(); + // What the system says about memory (RNSkGpuPurge::onLowMemory, + // RNSkGpuPurge::onTrimMemory). + private static native void onLowMemoryNative(); + + private static native void onTrimMemoryNative(int level); // Where Dawn's blob cache keeps its entries (DawnContext::setCacheDirectory). private static native void setCacheDirectoryNative(String directory); diff --git a/packages/skia/apple/RNSkApplePlatformContext.mm b/packages/skia/apple/RNSkApplePlatformContext.mm index 37249ccdca..ddd68de26e 100644 --- a/packages/skia/apple/RNSkApplePlatformContext.mm +++ b/packages/skia/apple/RNSkApplePlatformContext.mm @@ -188,7 +188,7 @@ object:nil queue:nil usingBlock:^(NSNotification *) { - RNSkGpuPurge::request(); + RNSkGpuPurge::onMemoryWarning(); }]; }); #endif // !TARGET_OS_OSX diff --git a/packages/skia/cpp/api/JsiSkApi.h b/packages/skia/cpp/api/JsiSkApi.h index 58427d1bbc..b44bf5739f 100644 --- a/packages/skia/cpp/api/JsiSkApi.h +++ b/packages/skia/cpp/api/JsiSkApi.h @@ -171,7 +171,7 @@ class JsiSkApi : public JsiSkNativeObject { } JSI_HOST_FUNCTION(purgeGpuResources) { // The recorders of this thread, which only it may touch, then Dawn. - DawnContext::trimThreadRecorders(std::chrono::milliseconds(0), true); + DawnContext::purgeThreadRecorders(); RNSkGpuPurge::request(); return jsi::Value::undefined(); } diff --git a/packages/skia/cpp/rnskia/RNDawnContext.h b/packages/skia/cpp/rnskia/RNDawnContext.h index fcab2ed54d..544456822a 100644 --- a/packages/skia/cpp/rnskia/RNDawnContext.h +++ b/packages/skia/cpp/rnskia/RNDawnContext.h @@ -454,45 +454,32 @@ class DawnContext { } /** - Frees the GPU memory the recorders of the calling thread hold without - using it, on that thread (a recorder belongs to the thread it records - on): what went unused for `unusedFor`, or, with `everything`, all they - can let go of, the pages of their atlases included. `everything` is for a - thread that records nothing for now (a render thread once idle, see - RNSkGraphiteProducer): the atlases lose no content by it, as Graphite - empties them at every snap when recordings may be inserted in any order. - The upload recorder lets go of everything either way: what it made - belongs to the image cache (see makeRecorderLocked). The GPU work that - finished releases its resources first, and Dawn runs the deletions it - deferred after. Never makes a recorder. Any thread. + Trims the recorders of the calling thread, on that thread (a recorder + belongs to the thread it records on): frees the GPU memory they hold and + did not use for `unusedFor`. The routine of a thread that keeps recording + (see trimThreadIfDue, RNSkGraphiteProducer). The upload recorder lets go + of everything either way: what it made belongs to the image cache (see + makeRecorderLocked). The GPU work that finished releases its resources + first, and Dawn runs the deletions it deferred after. Never makes a + recorder. Any thread. */ - static void trimThreadRecorders(std::chrono::milliseconds unusedFor, - bool everything) { - // Looked at first: the GPU is not probed for a thread that has nothing. - auto &drawing = threadSlot(); - auto &uploads = uploadSlot(); - if (drawing.recorder == nullptr && uploads.recorder == nullptr) { - return; - } - auto *instance = tryGetInstance(); - if (instance == nullptr) { - return; - } - instance->checkFinishedWork(); - if (drawing.recorder != nullptr) { - if (everything) { - drawing.recorder->freeGpuResources(); - } else { - drawing.recorder->performDeferredCleanup(unusedFor); - } - } - if (uploads.recorder != nullptr) { - // Not performDeferredCleanup(0): a resource it takes back from the - // return queue counts as used at that moment, so it would keep every - // texture the image cache let go of since the last call. - uploads.recorder->freeGpuResources(); - } - instance->checkFinishedWork(); + static void trimThreadRecorders(std::chrono::milliseconds unusedFor) { + freeFromThreadRecorders([unusedFor](skgpu::graphite::Recorder &drawing) { + drawing.performDeferredCleanup(unusedFor); + }); + } + + /** + Purges the recorders of the calling thread: frees all they can let go of, + the pages of their atlases included. For a thread that records nothing + for now (a render thread once idle, see RNSkGraphiteProducer) and for + Skia.purgeGpuResources() (see RNSkGpuPurge). The atlases lose no content + by it, as Graphite empties them at every snap when recordings may be + inserted in any order. Otherwise as trimThreadRecorders(). + */ + static void purgeThreadRecorders() { + freeFromThreadRecorders( + [](skgpu::graphite::Recorder &drawing) { drawing.freeGpuResources(); }); } /** @@ -584,7 +571,7 @@ class DawnContext { return; } slot.lastTrim = now; - trimThreadRecorders(kThreadTrimDelay, false); + trimThreadRecorders(kThreadTrimDelay); } /** @@ -1348,6 +1335,35 @@ class DawnContext { return slot; } + /** + What trimThreadRecorders() and purgeThreadRecorders() share: `freeDrawing` + frees what the drawing recorder of the calling thread is to let go of. + */ + template + static void freeFromThreadRecorders(FreeDrawing &&freeDrawing) { + // Looked at first: the GPU is not probed for a thread that has nothing. + auto &drawing = threadSlot(); + auto &uploads = uploadSlot(); + if (drawing.recorder == nullptr && uploads.recorder == nullptr) { + return; + } + auto *instance = tryGetInstance(); + if (instance == nullptr) { + return; + } + instance->checkFinishedWork(); + if (drawing.recorder != nullptr) { + freeDrawing(*drawing.recorder); + } + if (uploads.recorder != nullptr) { + // Not performDeferredCleanup(0): a resource it takes back from the + // return queue counts as used at that moment, so it would keep every + // texture the image cache let go of since the last call. + uploads.recorder->freeGpuResources(); + } + instance->checkFinishedWork(); + } + /** The recorder of a thread that ended (see ThreadRecorder). */ void forgetRecorder(const skgpu::graphite::Recorder *recorder) noexcept { std::lock_guard lock(_mutex); diff --git a/packages/skia/cpp/rnskia/RNSkGpuPurge.h b/packages/skia/cpp/rnskia/RNSkGpuPurge.h index 4f8aaa592c..e165d69a35 100644 --- a/packages/skia/cpp/rnskia/RNSkGpuPurge.h +++ b/packages/skia/cpp/rnskia/RNSkGpuPurge.h @@ -12,23 +12,30 @@ namespace RNSkia { /** - * Skia.purgeGpuResources(), which the platform also asks for when memory - * runs low: gives the GPU memory nothing uses back to the system. Dawn keeps - * the memory of disposed surfaces and images for reuse otherwise. What is - * alive keeps its content and its caches. + * Skia.purgeGpuResources(), which the system also brings about when it is + * short of memory: gives the GPU memory nothing uses back to the system. + * Dawn keeps the memory of disposed surfaces and images for reuse otherwise. + * What is alive keeps its content and its caches. + * + * The platform only reports 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. * * One run: - * 1. asks the render threads to trim their recorders (their idle task); + * 1. asks the render threads to free what their recorders hold (their + * idle task, see RNSkGraphiteProducer); * 2. has Dawn free what it can now (DawnContext::reduceMemoryUsage); - * 3. does that once more after the render threads trimmed. + * 3. does that once more after the render threads did. */ class RNSkGpuPurge { public: - /** Any thread. Nothing happens before the GPU is first used. */ + /** + Skia.purgeGpuResources(), after the caller purged its own recorders. Any + thread. Nothing happens before the GPU is first used. + */ static void request() noexcept { auto *context = DawnContext::peekInstance(); if (context == nullptr) { @@ -52,7 +59,55 @@ class RNSkGpuPurge { } } + /** + 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 { request(); } + + /** + Android, ComponentCallbacks.onLowMemory(): the whole system is short of + memory. Any thread. + */ + static void onLowMemory() noexcept { request(); } + + /** + Android, ComponentCallbacks2.onTrimMemory(): purges from + kTrimMemoryBackground. Any thread. + */ + static void onTrimMemory(int level) noexcept { + if (level >= kTrimMemoryBackground) { + request(); + } + } + private: + /** + A round of passes asks Dawn again for as long as it says deletions are + pending on submitted work, 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}; + + /** + How long a run waits for the render threads between its two rounds of + passes: they run their idle task RNSkThreadPool::kIdleDelay after the + request, and what they free reaches Dawn shortly after. + */ + static constexpr std::chrono::milliseconds kRenderThreadsDelay = + std::chrono::milliseconds(RNSkThreadPool::kIdleDelay) + + std::chrono::milliseconds(500); + + /** + ComponentCallbacks2.TRIM_MEMORY_BACKGROUND: the process is in the + background, among those the system ends for their memory. The level + below, TRIM_MEMORY_UI_HIDDEN, comes with every app switch, where the app + is often back at once and wants that memory again. Since Android 14 these + two are the only levels sent. + */ + static constexpr int kTrimMemoryBackground = 40; + struct State { std::mutex mutex; // Whether the purge thread is alive. @@ -79,19 +134,21 @@ class RNSkGpuPurge { } state.requested = false; } - RNSkThreadPool::getInstance().requestIdleTask(); - reduceMemoryUsage(context); - // The render threads run their idle task kIdleDelay after the request. - std::this_thread::sleep_for(RNSkThreadPool::kIdleDelay + - std::chrono::milliseconds(500)); - reduceMemoryUsage(context); + run(context); } } - // Dawn frees what it can, again for as long as it says deletions are - // pending on submitted work. - static void reduceMemoryUsage(DawnContext *context) noexcept { - constexpr int kMaxPasses = 10; + // One run (see the class). + static void run(DawnContext *context) noexcept { + RNSkThreadPool::getInstance().requestIdleTask(); + runPasses(context); + std::this_thread::sleep_for(kRenderThreadsDelay); + runPasses(context); + } + + // One round of passes: Dawn frees what it can, again for as long as it + // says deletions are pending on submitted work. + static void runPasses(DawnContext *context) noexcept { for (int pass = 0; pass < kMaxPasses; pass++) { #if defined(__APPLE__) // iOS refuses GPU work in the background: the purge goes on once the @@ -101,7 +158,7 @@ class RNSkGpuPurge { if (!context->reduceMemoryUsage()) { return; } - std::this_thread::sleep_for(std::chrono::milliseconds(100)); + std::this_thread::sleep_for(kPassInterval); } } }; diff --git a/packages/skia/cpp/rnskia/RNSkGraphiteProducer.cpp b/packages/skia/cpp/rnskia/RNSkGraphiteProducer.cpp index b5e5941291..1040dcdacd 100644 --- a/packages/skia/cpp/rnskia/RNSkGraphiteProducer.cpp +++ b/packages/skia/cpp/rnskia/RNSkGraphiteProducer.cpp @@ -3,6 +3,7 @@ #include "RNSkGraphiteProducer.h" #include +#include #include #include #include @@ -23,19 +24,31 @@ namespace RNSkia { namespace { /** - The render thread pool, set up on first use to trim the recorders of its - threads once GPU resources went away (see DawnContext::trimThreadRecorders): - a view torn down with its content, or textures the image cache let go of. - A thread that ran no job for RNSkThreadPool::kIdleDelay lets go of all it - can; one still recording, of what went unused that long. + What a render thread that still records lets go of in its idle task: what its + recorders did not use for this long. What went away with the request for the + task is older than that by the time the task runs (RNSkThreadPool::kIdleDelay + after the request), what the views still drawing use is not. + */ +constexpr std::chrono::milliseconds kBusyThreadTrimAge = + RNSkThreadPool::kIdleDelay / 2; + +/** + The render thread pool, set up on first use to free what the recorders of its + threads hold once GPU resources went away: a view torn down with its content, + or textures the image cache let go of. A thread that ran no job for + RNSkThreadPool::kIdleDelay purges its recorders (see + DawnContext::purgeThreadRecorders); one still recording trims them (see + DawnContext::trimThreadRecorders). */ RNSkThreadPool &renderPool() { static RNSkThreadPool &pool = []() -> RNSkThreadPool & { auto &threads = RNSkThreadPool::getInstance(); threads.setIdleTask([](bool idle) { - // What went away with the request is older than this by the time the - // task runs, what the views still drawing use is not. - DawnContext::trimThreadRecorders(RNSkThreadPool::kIdleDelay / 2, idle); + if (idle) { + DawnContext::purgeThreadRecorders(); + } else { + DawnContext::trimThreadRecorders(kBusyThreadTrimAge); + } }); ImageProvider::setReleaseListener( []() { RNSkThreadPool::getInstance().requestIdleTask(); }); diff --git a/packages/skia/cpp/rnskia/RNSkSurfaceRecorder.h b/packages/skia/cpp/rnskia/RNSkSurfaceRecorder.h index 1f7e6647e4..ff28f44836 100644 --- a/packages/skia/cpp/rnskia/RNSkSurfaceRecorder.h +++ b/packages/skia/cpp/rnskia/RNSkSurfaceRecorder.h @@ -56,11 +56,11 @@ class RNSkSurfaceRecorder { _dirty = false; const bool submitted = DawnContext::getInstance().submitRecording( _recorder.get(), _generation, syncToCpu); - // Throttled: the scratch textures the recorder cached and did not use - // for a while go. + // Trimmed, throttled: the scratch textures the recorder cached and did + // not use for a while go. const auto now = std::chrono::steady_clock::now(); - if (now - _lastCleanup >= DawnContext::kThreadTrimDelay) { - _lastCleanup = now; + if (now - _lastTrim >= DawnContext::kThreadTrimDelay) { + _lastTrim = now; _recorder->performDeferredCleanup(DawnContext::kThreadTrimDelay); } // The images the drawing uploaded went through the upload recorder of @@ -107,8 +107,8 @@ class RNSkSurfaceRecorder { // Whether something was drawn and not submitted. A new surface is dirty: // its initial clear is yet to be submitted. bool _dirty = true; - // The latest cleanup (see flush). - std::chrono::steady_clock::time_point _lastCleanup = + // The latest trim (see flush). + std::chrono::steady_clock::time_point _lastTrim = std::chrono::steady_clock::now(); }; From 7e98fb5156fcf1cb9403a13533aa36275d9d81e1 Mon Sep 17 00:00:00 2001 From: William Candillon Date: Wed, 25 Nov 2026 10:10:46 +0100 Subject: [PATCH 10/15] feat(graphite): purge when the app goes to the background on Android On a Galaxy S25 Edge (Android 17) the system only sends TRIM_MEMORY_UI_HIDDEN when the app leaves the foreground. TRIM_MEMORY_BACKGROUND never came, with the app cached and frozen for a minute (measured in wcandillon/react-native-webgpu#649), so the purge never ran on its own. From TRIM_MEMORY_UI_HIDDEN, going home with 100 disposed 512x512 surfaces gives 260 MB back within 3 s. Chrome, Flutter on iOS and Android's own renderer also free their GPU caches when the app is hidden. --- apps/docs/docs/animations/textures.md | 2 +- packages/skia/cpp/rnskia/RNSkGpuPurge.h | 27 +++++++++++++++---------- packages/skia/src/skia/types/Skia.ts | 3 ++- 3 files changed, 19 insertions(+), 13 deletions(-) diff --git a/apps/docs/docs/animations/textures.md b/apps/docs/docs/animations/textures.md index 027a6f0749..901de2bb9f 100644 --- a/apps/docs/docs/animations/textures.md +++ b/apps/docs/docs/animations/textures.md @@ -209,7 +209,7 @@ Disposed surfaces leave their memory to Skia, for the next ones. ### Purging GPU memory -**Most apps should never call `Skia.purgeGpuResources()`.** Dispose of the surfaces and images you are done with, and Skia reuses their memory. When the system runs short of memory, React Native Skia purges on its own: on an iOS memory warning, and on Android on `onLowMemory()` and on `onTrimMemory()` from `TRIM_MEMORY_BACKGROUND`. +**Most apps should never call `Skia.purgeGpuResources()`.** Dispose of the surfaces and images you are done with, and Skia reuses their memory. React Native Skia purges on its own: on iOS on a memory warning, and on Android each time the app goes to the background (`onTrimMemory()` from `TRIM_MEMORY_UI_HIDDEN`) and on `onLowMemory()`. The one case for calling it is a one-off peak followed by a long stretch that needs far less GPU memory, while the app stays in the foreground. For example, a video export just finished and the app is back to a light screen: diff --git a/packages/skia/cpp/rnskia/RNSkGpuPurge.h b/packages/skia/cpp/rnskia/RNSkGpuPurge.h index e165d69a35..3e81e3cc4d 100644 --- a/packages/skia/cpp/rnskia/RNSkGpuPurge.h +++ b/packages/skia/cpp/rnskia/RNSkGpuPurge.h @@ -13,9 +13,10 @@ namespace RNSkia { /** * Skia.purgeGpuResources(), which the system also brings about when it is - * short of memory: gives the GPU memory nothing uses back to the system. - * Dawn keeps the memory of disposed surfaces and images for reuse otherwise. - * What is alive keeps its content and its caches. + * short of memory and, on Android, when the app goes to the background: + * gives the GPU memory nothing uses back to the system. Dawn keeps the + * memory of disposed surfaces and images for reuse otherwise. What is alive + * keeps its content and its caches. * * The platform only reports what the system said (onMemoryWarning, * onLowMemory, onTrimMemory): whether it calls for a purge is decided here. @@ -73,10 +74,11 @@ class RNSkGpuPurge { /** Android, ComponentCallbacks2.onTrimMemory(): purges from - kTrimMemoryBackground. Any thread. + kTrimMemoryUiHidden, which is each time the app goes to the background. + Any thread. */ static void onTrimMemory(int level) noexcept { - if (level >= kTrimMemoryBackground) { + if (level >= kTrimMemoryUiHidden) { request(); } } @@ -100,13 +102,16 @@ class RNSkGpuPurge { std::chrono::milliseconds(500); /** - ComponentCallbacks2.TRIM_MEMORY_BACKGROUND: the process is in the - background, among those the system ends for their memory. The level - below, TRIM_MEMORY_UI_HIDDEN, comes with every app switch, where the app - is often back at once and wants that memory again. Since Android 14 these - two are the only levels sent. + ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN: the app is no longer visible. + It draws 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 kTrimMemoryBackground = 40; + static constexpr int kTrimMemoryUiHidden = 20; struct State { std::mutex mutex; diff --git a/packages/skia/src/skia/types/Skia.ts b/packages/skia/src/skia/types/Skia.ts index 0c7e4fb708..ff7cee39f6 100644 --- a/packages/skia/src/skia/types/Skia.ts +++ b/packages/skia/src/skia/types/Skia.ts @@ -181,7 +181,8 @@ export interface Skia { /** * Returns the GPU memory nothing uses to the system. Most apps should never * call it: Skia reuses the memory of what you dispose of, and purges on its - * own when the system is short of memory. + * 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 From ff00a8d3385ba8bc0157ff5554ecda323615e422 Mon Sep 17 00:00:00 2001 From: William Candillon Date: Wed, 25 Nov 2026 10:28:04 +0100 Subject: [PATCH 11/15] docs(graphite): keep main's sentence in submitRecording until main is merged main rewords the end of the sentence this branch had reflowed (#4531), and the two changes conflict. With the original lines back, GitHub can merge main into the branch; the commit after the merge puts this branch's wording back. --- packages/skia/cpp/rnskia/RNDawnContext.h | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/packages/skia/cpp/rnskia/RNDawnContext.h b/packages/skia/cpp/rnskia/RNDawnContext.h index 544456822a..07db3ac68c 100644 --- a/packages/skia/cpp/rnskia/RNDawnContext.h +++ b/packages/skia/cpp/rnskia/RNDawnContext.h @@ -484,12 +484,12 @@ class DawnContext { /** Snaps what the recorder recorded and runs it on the GPU. `recorder` is a - thread's (see getRecorder); any other submits nothing. A recording made - for a lost device (see generation()) is dropped: nothing can run it, and - the device in use would refuse its resources. Called on the recorder's - thread. Returns whether the recording runs: false when there was nothing - to run, when it was dropped, or when Graphite rejected it (which is - logged). + thread's (see getRecorder), also behind the surfaces made on it; any + other submits nothing. A recording made for a lost device (see + generation()) is dropped: nothing can run it, and the device in use would + refuse its resources. Called on the recorder's thread. Returns whether + the recording runs: false when there was nothing to run, when it was + dropped, or when Graphite rejected it (which is logged). */ bool submitRecording( skgpu::graphite::Recorder *recorder, From 61abc14525293683ded07871d620400a31f38650 Mon Sep 17 00:00:00 2001 From: William Candillon Date: Wed, 25 Nov 2026 10:28:24 +0100 Subject: [PATCH 12/15] docs(graphite): submitRecording no longer serves the surfaces of a thread Each offscreen surface has its own recorder on this branch, so the clause that came back for the merge of main goes again. The end of the sentence is main's (#4531). --- packages/skia/cpp/rnskia/RNDawnContext.h | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/packages/skia/cpp/rnskia/RNDawnContext.h b/packages/skia/cpp/rnskia/RNDawnContext.h index 0c20983caf..7bdac2b292 100644 --- a/packages/skia/cpp/rnskia/RNDawnContext.h +++ b/packages/skia/cpp/rnskia/RNDawnContext.h @@ -484,13 +484,12 @@ class DawnContext { /** Snaps what the recorder recorded and runs it on the GPU. `recorder` is a - thread's (see getRecorder), also behind the surfaces made on it; any - other submits nothing. A recording made for a lost device (see - generation()) is dropped: nothing can run it, and the device in use would - refuse its resources. Called on the recorder's thread. Returns whether - the recording runs: false when there was nothing to run, when it was - dropped, or when Graphite could not snap, insert or submit it (which is - logged). + thread's (see getRecorder); any other submits nothing. A recording made + for a lost device (see generation()) is dropped: nothing can run it, and + the device in use would refuse its resources. Called on the recorder's + thread. Returns whether the recording runs: false when there was nothing + to run, when it was dropped, or when Graphite could not snap, insert or + submit it (which is logged). */ bool submitRecording( skgpu::graphite::Recorder *recorder, From 84ded8955e444eb4ba6c310684b28c33c653906c Mon Sep 17 00:00:00 2001 From: William Candillon Date: Wed, 25 Nov 2026 10:28:26 +0100 Subject: [PATCH 13/15] docs(graphite): do not document Skia.purgeGpuResources() on the docs site It is meant for one rare case, and the purge now runs on its own when the app is hidden or the system is short of memory. The function stays, and its doc comment says when to call it and when not to. --- apps/docs/docs/animations/textures.md | 22 ---------------------- 1 file changed, 22 deletions(-) diff --git a/apps/docs/docs/animations/textures.md b/apps/docs/docs/animations/textures.md index 901de2bb9f..8a047ce4a2 100644 --- a/apps/docs/docs/animations/textures.md +++ b/apps/docs/docs/animations/textures.md @@ -207,26 +207,4 @@ Skia frees what the cache has not used for a few seconds as you draw into the su Disposed surfaces leave their memory to Skia, for the next ones. -### Purging GPU memory - -**Most apps should never call `Skia.purgeGpuResources()`.** Dispose of the surfaces and images you are done with, and Skia reuses their memory. React Native Skia purges on its own: on iOS on a memory warning, and on Android each time the app goes to the background (`onTrimMemory()` from `TRIM_MEMORY_UI_HIDDEN`) and on `onLowMemory()`. - -The one case for calling it is a one-off peak followed by a long stretch that needs far less GPU memory, while the app stays in the foreground. For example, a video export just finished and the app is back to a light screen: - -```tsx -// The export is over, and no other one follows -exportSurfaces.forEach((surface) => surface.dispose()); -Skia.purgeGpuResources(); -``` - -Do not call it: - -- in a render loop, or after each `dispose()`; -- when a component unmounts or on navigation: the next screen usually wants that memory back; -- to fix a leak or an out-of-memory error: it only returns memory that nothing uses, so a surface you have not disposed of stays. - -Purging too often makes an app slower: memory that Skia would have reused has to be requested from the system again. - -It returns right away and works in the background (on iOS, once the app is active). On the Web it does nothing: the browser manages GPU memory there. In a native app, Skia's GPU memory counts towards your app's, and the system can end the app for using too much of it. - Textures can also be shared with WebGPU: see [WebGPU](/docs/webgpu). From 8aed4a38874de22623fc57d862f7e9b948685e86 Mon Sep 17 00:00:00 2001 From: William Candillon Date: Wed, 25 Nov 2026 10:53:24 +0100 Subject: [PATCH 14/15] refactor(graphite): group the trim functions of DawnContext ahead of merging main kThreadTrimDelay and trimThreadIfDue() move next to trimThreadRecorders() and purgeThreadRecorders(): main adds submitRecordingAsync() (#4532) where they were. Two lines also change place for the time of the merge, so that GitHub can make it without a conflict: JsiSkSurface.h gets RNSkSurfaceRecorder.h through JsiSkCanvas.h, and the imports of Surfaces.spec.tsx are in another order. The commit after the merge puts them back. --- packages/skia/cpp/api/JsiSkSurface.h | 2 +- packages/skia/cpp/rnskia/RNDawnContext.h | 64 +++++++++---------- .../renderer/__tests__/e2e/Surfaces.spec.tsx | 2 +- 3 files changed, 34 insertions(+), 34 deletions(-) diff --git a/packages/skia/cpp/api/JsiSkSurface.h b/packages/skia/cpp/api/JsiSkSurface.h index 7eca065375..1deab77ed4 100644 --- a/packages/skia/cpp/api/JsiSkSurface.h +++ b/packages/skia/cpp/api/JsiSkSurface.h @@ -14,7 +14,7 @@ #include "JsiSkImage.h" #include "rnskia/RNDawnContext.h" -#include "rnskia/RNSkSurfaceRecorder.h" +#include "rnskia/RNSkAsync.h" #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdocumentation" diff --git a/packages/skia/cpp/rnskia/RNDawnContext.h b/packages/skia/cpp/rnskia/RNDawnContext.h index 7bdac2b292..e1a11dbe69 100644 --- a/packages/skia/cpp/rnskia/RNDawnContext.h +++ b/packages/skia/cpp/rnskia/RNDawnContext.h @@ -482,6 +482,38 @@ class DawnContext { [](skgpu::graphite::Recorder &drawing) { drawing.freeGpuResources(); }); } + /** + The throttle of trimThreadIfDue(), and how long a resource went unused + before it goes: the delay of the render pool's idle task + (RNSkThreadPool::kIdleDelay). + */ + static constexpr std::chrono::milliseconds kThreadTrimDelay = + RNSkThreadPool::kIdleDelay; + + /** + trimThreadRecorders(), throttled to once per kThreadTrimDelay: called + after a submit by a thread outside the render pool (the JS thread, a + worklet runtime), which has no idle task to trim it. Its drawing recorder + otherwise keeps every scratch texture, up to Graphite's budget (256 MB by + default), for as long as the thread lives. Nothing happens on a render + thread (see RNSkGraphiteProducer). Never makes a recorder. Any thread. + */ + static void trimThreadIfDue() { + if (RNSkThreadPool::isPoolThread()) { + return; + } + auto &slot = threadSlot(); + if (slot.recorder == nullptr && uploadSlot().recorder == nullptr) { + return; + } + const auto now = std::chrono::steady_clock::now(); + if (now - slot.lastTrim < kThreadTrimDelay) { + return; + } + slot.lastTrim = now; + trimThreadRecorders(kThreadTrimDelay); + } + /** Snaps what the recorder recorded and runs it on the GPU. `recorder` is a thread's (see getRecorder); any other submits nothing. A recording made @@ -549,38 +581,6 @@ class DawnContext { return inserted && submitted; } - /** - The throttle of trimThreadIfDue(), and how long a resource went unused - before it goes: the delay of the render pool's idle task - (RNSkThreadPool::kIdleDelay). - */ - static constexpr std::chrono::milliseconds kThreadTrimDelay = - RNSkThreadPool::kIdleDelay; - - /** - trimThreadRecorders(), throttled to once per kThreadTrimDelay: called - after a submit by a thread outside the render pool (the JS thread, a - worklet runtime), which has no idle task to trim it. Its drawing recorder - otherwise keeps every scratch texture, up to Graphite's budget (256 MB by - default), for as long as the thread lives. Nothing happens on a render - thread (see RNSkGraphiteProducer). Never makes a recorder. Any thread. - */ - static void trimThreadIfDue() { - if (RNSkThreadPool::isPoolThread()) { - return; - } - auto &slot = threadSlot(); - if (slot.recorder == nullptr && uploadSlot().recorder == nullptr) { - return; - } - const auto now = std::chrono::steady_clock::now(); - if (now - slot.lastTrim < kThreadTrimDelay) { - return; - } - slot.lastTrim = now; - trimThreadRecorders(kThreadTrimDelay); - } - /** Replays the recordings, in order, onto the target surface (a deferred canvas target) and submits them as one batch. A recording Graphite diff --git a/packages/skia/src/renderer/__tests__/e2e/Surfaces.spec.tsx b/packages/skia/src/renderer/__tests__/e2e/Surfaces.spec.tsx index 8733337b4b..17bbc79315 100644 --- a/packages/skia/src/renderer/__tests__/e2e/Surfaces.spec.tsx +++ b/packages/skia/src/renderer/__tests__/e2e/Surfaces.spec.tsx @@ -1,6 +1,6 @@ -import { itRunsE2eOnly } from "../../../__tests__/setup"; import { AlphaType, ColorType } from "../../../skia/types"; import { surface } from "../setup"; +import { itRunsE2eOnly } from "../../../__tests__/setup"; describe("Surfaces", () => { it("surface has width and height", async () => { From 17fb67e122c10e8f33304588ef7c8381d9b5fa02 Mon Sep 17 00:00:00 2001 From: William Candillon Date: Wed, 25 Nov 2026 10:53:43 +0100 Subject: [PATCH 15/15] fix(graphite): flushAsync() on a surface that owns its recorder Surface.flushAsync() (#4532) came with the merge of main written for the recorder of a thread, which a surface no longer uses on this branch, and for the dispatcher this branch removed, so the merge commit does not build on its own: - RNSkSurfaceRecorder::flushAsync() flushes the surface's own recorder, as flush() does, and trims after it. - DawnContext::submitRecordingAsync() takes the generation that recorder was made for, as submitRecording() does. Without it the draws of every surface would be reported lost. - Its documentation says the promise covers the draws of the surface: each surface submits its own here. --- apps/docs/docs/webgpu.md | 2 +- packages/skia/cpp/api/JsiSkSurface.h | 32 ++++++++------- packages/skia/cpp/rnskia/RNDawnContext.h | 8 +++- .../skia/cpp/rnskia/RNSkSurfaceRecorder.h | 40 ++++++++++++++----- .../renderer/__tests__/e2e/Surfaces.spec.tsx | 2 +- .../skia/src/skia/types/Surface/Surface.ts | 7 ++-- 6 files changed, 58 insertions(+), 33 deletions(-) diff --git a/apps/docs/docs/webgpu.md b/apps/docs/docs/webgpu.md index e653c3c27f..eff10104ab 100644 --- a/apps/docs/docs/webgpu.md +++ b/apps/docs/docs/webgpu.md @@ -104,7 +104,7 @@ const drawFrame = async () => { }; ``` -The promise covers the draws pending on the thread, as the GPU surfaces of a thread are submitted together. +The promise covers the draws of this surface: each surface submits its own drawing. While the app is in the background, it settles on return. On Android, `Skia.gpu.foreground` is whether the host activity is resumed; on the web, whether the document is visible. diff --git a/packages/skia/cpp/api/JsiSkSurface.h b/packages/skia/cpp/api/JsiSkSurface.h index 9da55309c0..495e84eeef 100644 --- a/packages/skia/cpp/api/JsiSkSurface.h +++ b/packages/skia/cpp/api/JsiSkSurface.h @@ -16,6 +16,7 @@ #include "rnskia/RNDawnContext.h" #include "rnskia/RNSkAsync.h" +#include "rnskia/RNSkSurfaceRecorder.h" #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdocumentation" @@ -90,29 +91,30 @@ class JsiSkSurface // they were lost (see DawnContext::submitRecordingAsync). Nothing blocks: // the readback thread waits for the GPU. JSI_HOST_FUNCTION(flushAsync) { - _dispatcher->processQueue(); auto surface = getObject(); - if (surface->recorder() == nullptr) { + if (!_recorder) { // A raster surface holds its draws already. return RNSkAsync::settled( runtime, [](jsi::Runtime &, RNSkAsync::Promise &promise) { promise.resolve(jsi::Value::undefined()); }); } + // The surface's own recorder (see RNSkSurfaceRecorder), which the work + // keeps alive with the surface. return RNSkAsync::run( - runtime, getContext(), [surface](RNSkAsync::Complete complete) { - DawnContext::getInstance().submitRecordingAsync( - surface->recorder(), - [complete = std::move(complete)](std::string error) { - complete([error = std::move(error)]( - jsi::Runtime &, RNSkAsync::Promise &promise) { - if (error.empty()) { - promise.resolve(jsi::Value::undefined()); - } else { - promise.reject("flushAsync: " + error); - } - }); - }); + runtime, getContext(), + [surface, recorder = _recorder](RNSkAsync::Complete complete) { + recorder->flushAsync([complete = + std::move(complete)](std::string error) { + complete([error = std::move(error)](jsi::Runtime &, + RNSkAsync::Promise &promise) { + if (error.empty()) { + promise.resolve(jsi::Value::undefined()); + } else { + promise.reject("flushAsync: " + error); + } + }); + }); }); } diff --git a/packages/skia/cpp/rnskia/RNDawnContext.h b/packages/skia/cpp/rnskia/RNDawnContext.h index 56c9f3c155..69cf041a98 100644 --- a/packages/skia/cpp/rnskia/RNDawnContext.h +++ b/packages/skia/cpp/rnskia/RNDawnContext.h @@ -584,9 +584,13 @@ class DawnContext { was submitted: it must not use the context nor a JS runtime (hand the result to the right thread instead). The readback thread waits for the GPU (see awaitReadbacks), so that the callback runs even when nothing - else submits. Called on the recorder's thread. + else submits. `generation` as for submitRecording(): the one a recorder of + its own was made for (see makeRecorder), or none for a thread's, looked + up. Never trims (see RNSkSurfaceRecorder). Called on the recorder's + thread. */ void submitRecordingAsync(skgpu::graphite::Recorder *recorder, + std::optional generation, std::function callback) { if (recorder == nullptr) { callback(""); @@ -613,7 +617,7 @@ class DawnContext { auto recording = recorder->snap(); std::unique_lock lock(_mutex); auto *current = _current.load(std::memory_order_acquire); - if (generationOf(recorder) != current->id || + if (generation.value_or(generationOf(recorder)) != current->id || current->lost.load(std::memory_order_acquire)) { failure = kLost; } else if (recording == nullptr) { diff --git a/packages/skia/cpp/rnskia/RNSkSurfaceRecorder.h b/packages/skia/cpp/rnskia/RNSkSurfaceRecorder.h index ff28f44836..84c8ae7ba3 100644 --- a/packages/skia/cpp/rnskia/RNSkSurfaceRecorder.h +++ b/packages/skia/cpp/rnskia/RNSkSurfaceRecorder.h @@ -4,7 +4,9 @@ #include #include #include +#include #include +#include #include #include "RNDawnContext.h" @@ -56,19 +58,23 @@ class RNSkSurfaceRecorder { _dirty = false; const bool submitted = DawnContext::getInstance().submitRecording( _recorder.get(), _generation, syncToCpu); - // Trimmed, throttled: the scratch textures the recorder cached and did - // not use for a while go. - const auto now = std::chrono::steady_clock::now(); - if (now - _lastTrim >= DawnContext::kThreadTrimDelay) { - _lastTrim = now; - _recorder->performDeferredCleanup(DawnContext::kThreadTrimDelay); - } - // The images the drawing uploaded went through the upload recorder of - // this thread, not this one. - DawnContext::trimThreadIfDue(); + trimIfDue(); return submitted; } + /** + surface.flushAsync(): flush(), with `callback` called exactly once: with + an empty string once the GPU has run what was drawn into the surface, or + with what lost it (see DawnContext::submitRecordingAsync, which says where + the callback runs). Called by the thread using the surface. + */ + void flushAsync(std::function callback) { + _dirty = false; + DawnContext::getInstance().submitRecordingAsync( + _recorder.get(), _generation, std::move(callback)); + trimIfDue(); + } + /** flush(), unless nothing was drawn since the last one. For a surface about to go: what is not submitted by then is lost with the recorder, and the @@ -81,6 +87,20 @@ class RNSkSurfaceRecorder { } private: + /** + After a flush. Trimmed, throttled: the scratch textures the recorder + cached and did not use for a while go. The images the drawing uploaded + went through the upload recorder of this thread, not this one. + */ + void trimIfDue() { + const auto now = std::chrono::steady_clock::now(); + if (now - _lastTrim >= DawnContext::kThreadTrimDelay) { + _lastTrim = now; + _recorder->performDeferredCleanup(DawnContext::kThreadTrimDelay); + } + DawnContext::trimThreadIfDue(); + } + RNSkSurfaceRecorder(std::unique_ptr recorder, uint64_t generation) : _recorder(std::move(recorder)), _generation(generation) {} diff --git a/packages/skia/src/renderer/__tests__/e2e/Surfaces.spec.tsx b/packages/skia/src/renderer/__tests__/e2e/Surfaces.spec.tsx index ebfd08022e..55bf609d07 100644 --- a/packages/skia/src/renderer/__tests__/e2e/Surfaces.spec.tsx +++ b/packages/skia/src/renderer/__tests__/e2e/Surfaces.spec.tsx @@ -1,6 +1,6 @@ +import { itRunsE2eOnly } from "../../../__tests__/setup"; import { AlphaType, ColorType } from "../../../skia/types"; import { surface } from "../setup"; -import { itRunsE2eOnly } from "../../../__tests__/setup"; describe("Surfaces", () => { it("surface has width and height", async () => { diff --git a/packages/skia/src/skia/types/Surface/Surface.ts b/packages/skia/src/skia/types/Surface/Surface.ts index 0e38d7652f..04edaf1cbc 100644 --- a/packages/skia/src/skia/types/Surface/Surface.ts +++ b/packages/skia/src/skia/types/Surface/Surface.ts @@ -58,10 +58,9 @@ export interface SkSurface extends SkJSIInstance<"Surface"> { * to a consumer that needs the draws in it: a video encoder, another * command queue (see `Skia.Surface.MakeFromGPUTexture`). * - * The draws of all the GPU surfaces of a thread are recorded together and - * submitted by the first call that needs them, so the promise covers the - * draws pending on the thread, and an error may come from the draws of - * another surface. + * Each GPU surface records and submits its own draws: the promise covers + * what was drawn into this surface, not what is pending on another one + * (flush that one first when this one draws its image, see `asImage()`). * * It rejects when Graphite cannot record, insert or submit the draws, when * the GPU fails to run them, and when the GPU device of the surface is