diff --git a/apps/docs/docs/animations/textures.md b/apps/docs/docs/animations/textures.md index ba568a43bf..8a047ce4a2 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 @@ -196,4 +198,13 @@ Read the snapshot back with `makeRasterImage()` before drawing it in a canvas. T ::: +## GPU memory of offscreen surfaces + +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. + +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. + Textures can also be shared with WebGPU: see [WebGPU](/docs/webgpu). 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/android/cpp/jni/JniPlatformContext.cpp b/packages/skia/android/cpp/jni/JniPlatformContext.cpp index f29f8d51ba..d778a097bf 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 { @@ -37,6 +38,10 @@ void JniPlatformContext::registerNatives() { JniPlatformContext::runMainThreadTasks), makeNativeMethod("setForegroundNative", JniPlatformContext::setForegroundNative), + makeNativeMethod("onLowMemoryNative", + JniPlatformContext::onLowMemoryNative), + makeNativeMethod("onTrimMemoryNative", + JniPlatformContext::onTrimMemoryNative), makeNativeMethod("setCacheDirectoryNative", JniPlatformContext::setCacheDirectoryNative), makeNativeMethod("setPixelDensityNative", @@ -97,6 +102,15 @@ void JniPlatformContext::setForegroundNative(jni::alias_ref, DawnContext::setForeground(foreground == JNI_TRUE); } +void JniPlatformContext::onLowMemoryNative(jni::alias_ref) { + RNSkGpuPurge::onLowMemory(); +} + +void JniPlatformContext::onTrimMemoryNative(jni::alias_ref, + jint level) { + RNSkGpuPurge::onTrimMemory(level); +} + 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..714ed05837 100644 --- a/packages/skia/android/cpp/jni/include/JniPlatformContext.h +++ b/packages/skia/android/cpp/jni/include/JniPlatformContext.h @@ -33,6 +33,11 @@ class JniPlatformContext : public jni::HybridClass { // and outlives it. static void setForegroundNative(jni::alias_ref, jboolean foreground); + // 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 a671b4bef6..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 @@ -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; @@ -35,8 +35,10 @@ 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. - private final ComponentCallbacks mComponentCallbacks = new ComponentCallbacks() { + // 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) { updatePixelDensity(); @@ -44,6 +46,12 @@ public void onConfigurationChanged(Configuration newConfig) { @Override public void onLowMemory() { + onLowMemoryNative(); + } + + @Override + public void onTrimMemory(int level) { + onTrimMemoryNative(level); } }; @@ -172,6 +180,12 @@ public void run() { // Whether the app is in the foreground (DawnContext::setForeground). private static native void setForegroundNative(boolean foreground); + // 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 a622c1b19d..ddd68de26e 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" @@ -183,6 +184,12 @@ usingBlock:^(NSNotification *) { DawnContext::setForeground(true); }]; + [center addObserverForName:UIApplicationDidReceiveMemoryWarningNotification + object:nil + queue:nil + usingBlock:^(NSNotification *) { + RNSkGpuPurge::onMemoryWarning(); + }]; }); #endif // !TARGET_OS_OSX } diff --git a/packages/skia/cpp/api/JsiSkApi.h b/packages/skia/cpp/api/JsiSkApi.h index 15e8892358..b44bf5739f 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" @@ -168,6 +169,12 @@ class JsiSkApi : public JsiSkNativeObject { JSI_HOST_FUNCTION(Color) { return JsiSkColor::createCtor()(runtime, thisValue, arguments, count); } + JSI_HOST_FUNCTION(purgeGpuResources) { + // The recorders of this thread, which only it may touch, then Dawn. + DawnContext::purgeThreadRecorders(); + RNSkGpuPurge::request(); + 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 +274,8 @@ class JsiSkApi : public JsiSkNativeObject { } static void definePrototype(jsi::Runtime &runtime, jsi::Object &prototype) { + 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..2010a30117 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" @@ -29,6 +28,7 @@ #include "rnskia/RNDawnContext.h" #include "rnskia/RNSkAtlas.h" +#include "rnskia/RNSkSurfaceRecorder.h" #include @@ -50,6 +50,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 +527,8 @@ class JsiSkCanvas : public JsiSkNativeObject { } if (_surface) { auto snapshot = _surface->makeImageSnapshot(); - if (auto *recorder = _surface->recorder()) { - DawnContext::getInstance().submitRecording(recorder); + if (_recorder) { + _recorder->flush(); } return JsiSkImage::readPixelsAsync( runtime, getContext(), std::move(snapshot), *info, srcX, srcY); @@ -612,35 +625,35 @@ 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->markDirty(); + } return _canvas; } // 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 e42ba1f7c5..495e84eeef 100644 --- a/packages/skia/cpp/api/JsiSkSurface.h +++ b/packages/skia/cpp/api/JsiSkSurface.h @@ -9,7 +9,6 @@ #include #include "JsiSkConverters.h" -#include "JsiSkDispatcher.h" #include "JsiSkNativeObjects.h" #include "JsiSkCanvas.h" @@ -17,6 +16,7 @@ #include "rnskia/RNDawnContext.h" #include "rnskia/RNSkAsync.h" +#include "rnskia/RNSkSurfaceRecorder.h" #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdocumentation" @@ -36,15 +36,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 @@ -70,13 +66,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 @@ -86,10 +81,9 @@ 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) { + _recorder->flush(sync ? skgpu::graphite::SyncToCpu::kYes + : skgpu::graphite::SyncToCpu::kNo); } } @@ -97,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); + } + }); + }); }); } @@ -127,7 +122,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) @@ -142,7 +136,6 @@ class JsiSkSurface } JSI_HOST_FUNCTION(makeImageSnapshot) { - _dispatcher->processQueue(); auto surface = getObject(); sk_sp image; if (count > 0 && arguments[0].isObject()) { @@ -154,8 +147,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) { + _recorder->flush(); } // Without a snapshot (e.g. bounds outside of the surface), outputImage // keeps its previous content and the image returned is a null one. @@ -215,6 +208,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); @@ -236,6 +235,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) { + _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 // on the canvas throws from here on. @@ -247,16 +251,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 RNSkSurfaceRecorder): 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..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" @@ -54,14 +55,14 @@ class JsiSkSurfaceFactory : public JsiSkNativeObject { } } } - auto context = getContext(); - auto surface = - context->makeOffscreenSurface(width, height, useP3ColorSpace); - if (surface == nullptr) { - return jsi::Value::null(); - } - return makeJsiObject(runtime, std::make_shared( - getContext(), std::move(surface))); + // A recorder of its own: the surface may be drawn into on another thread + // 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))); } // 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 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"); } - 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 b339afbfc6..69cf041a98 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 @@ -26,6 +27,7 @@ #include "RNImageProvider.h" #include "RNSkGpuActivity.h" #include "RNSkPipelineWarmup.h" +#include "RNSkThreadPool.h" #include "rnwgpu/DawnBlobCache.h" #include "utils/RNSkLog.h" @@ -117,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. @@ -212,7 +223,23 @@ 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); + 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(); }); } /** @@ -374,6 +401,23 @@ class DawnContext { return makeRecorderLocked(); } + /** + 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. + */ + std::unique_ptr + makeRecorder(size_t budget, uint64_t *generation) { + std::lock_guard lock(_mutex); + auto recorder = makeRecorderLocked(/* forUploads= */ false, budget); + if (recorder == nullptr) { + throw std::runtime_error("Failed to create graphite context"); + } + *generation = _current.load(std::memory_order_acquire)->id; + return recorder; + } + /** 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 @@ -403,59 +447,94 @@ 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) { - auto *instance = tryGetInstance(); - if (instance == nullptr) { + 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(); }); + } + + /** + 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 &drawing = threadSlot(); - auto &uploads = uploadSlot(); - if (drawing.recorder == nullptr && uploads.recorder == nullptr) { + auto &slot = threadSlot(); + if (slot.recorder == nullptr && uploadSlot().recorder == 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(); + const auto now = std::chrono::steady_clock::now(); + if (now - slot.lastTrim < kThreadTrimDelay) { + return; } - instance->checkFinishedWork(); + slot.lastTrim = now; + trimThreadRecorders(kThreadTrimDelay); } /** 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, skgpu::graphite::SyncToCpu syncToCpu = skgpu::graphite::SyncToCpu::kNo) { + const bool inserted = submitRecording(recorder, std::nullopt, syncToCpu); + if (recorder != nullptr && recorder == threadSlot().recorder.get()) { + trimThreadIfDue(); + } + return inserted; + } + + /** + 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). + */ + bool submitRecording(skgpu::graphite::Recorder *recorder, + std::optional generation, + skgpu::graphite::SyncToCpu syncToCpu) { if (recorder == nullptr) { return false; } @@ -465,7 +544,7 @@ class DawnContext { auto recording = recorder->snap(); 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; } @@ -505,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(""); @@ -534,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) { @@ -688,9 +771,11 @@ class DawnContext { return upload(image, mipmapped).texture; } - // Create offscreen surface - sk_sp MakeOffscreen(int width, int height, - bool useP3ColorSpace = false) { + // Create an offscreen surface, on the recorder of this thread unless given + // 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) @@ -698,7 +783,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 : getRecorder(), info); if (!surface) { throw std::runtime_error("Failed to create offscreen Skia surface."); @@ -781,7 +867,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 RNSkSurfaceRecorder). + sk_sp MakeSurfaceFromTexture(wgpu::Texture texture, + skgpu::graphite::Recorder *recorder) { if (!texture) { return nullptr; } @@ -800,7 +888,7 @@ class DawnContext { // The color type is derived from the texture format. return SkSurfaces::WrapBackendTexture( - getRecorder(), backendTexture, + recorder, backendTexture, nullptr, // colorspace nullptr, // surfaceProps [](void *context) { @@ -897,6 +985,8 @@ class DawnContext { or for one destroyed already. Any thread. */ void destroyRetiredDevice(uint64_t generation) { + // Before the context lock, as in reduceMemoryUsage(). + std::lock_guard destroyLock(_destroyMutex); std::lock_guard lock(_mutex); for (auto *retired : _retired) { if (retired->id == generation && !retired->deviceDestroyed) { @@ -907,6 +997,37 @@ 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's ReduceMemoryUsage(). + 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; @@ -946,6 +1067,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; @@ -983,6 +1106,24 @@ class DawnContext { return foreground; } + // 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; + } + 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 @@ -993,6 +1134,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()); @@ -1193,8 +1335,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 @@ -1207,6 +1351,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. @@ -1234,9 +1379,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 the offscreen surfaces of this thread recorded 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; @@ -1299,6 +1444,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); @@ -1466,6 +1640,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 + // 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. std::mutex _mutex; diff --git a/packages/skia/cpp/rnskia/RNSkGpuPurge.h b/packages/skia/cpp/rnskia/RNSkGpuPurge.h new file mode 100644 index 0000000000..3e81e3cc4d --- /dev/null +++ b/packages/skia/cpp/rnskia/RNSkGpuPurge.h @@ -0,0 +1,171 @@ +#pragma once + +#include +#include +#include +#include + +#include "RNDawnContext.h" +#include "RNSkThreadPool.h" +#include "utils/RNSkLog.h" + +namespace RNSkia { + +/** + * Skia.purgeGpuResources(), which the system also brings about when it is + * 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. + * + * 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 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 did. + */ +class RNSkGpuPurge { +public: + /** + 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) { + 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; + } + } + + /** + 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 + kTrimMemoryUiHidden, which is each time the app goes to the background. + Any thread. + */ + static void onTrimMemory(int level) noexcept { + if (level >= kTrimMemoryUiHidden) { + 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_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 kTrimMemoryUiHidden = 20; + + 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; + } + run(context); + } + } + + // 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 + // app is back. + DawnContext::waitForForeground(); +#endif + if (!context->reduceMemoryUsage()) { + return; + } + std::this_thread::sleep_for(kPassInterval); + } + } +}; + +} // namespace RNSkia 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 new file mode 100644 index 0000000000..84c8ae7ba3 --- /dev/null +++ b/packages/skia/cpp/rnskia/RNSkSurfaceRecorder.h @@ -0,0 +1,135 @@ +#pragma once + +#include +#include +#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); + 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 + texture may outlive both (asImage(), MakeFromGPUTexture). + */ + void flushIfDirty() { + if (_dirty) { + flush(); + } + } + +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) {} + + /** + 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 trim (see flush). + std::chrono::steady_clock::time_point _lastTrim = + std::chrono::steady_clock::now(); +}; + +} // namespace RNSkia 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()); 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/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/renderer/__tests__/e2e/Surfaces.spec.tsx b/packages/skia/src/renderer/__tests__/e2e/Surfaces.spec.tsx index c3240f06f6..55bf609d07 100644 --- a/packages/skia/src/renderer/__tests__/e2e/Surfaces.spec.tsx +++ b/packages/skia/src/renderer/__tests__/e2e/Surfaces.spec.tsx @@ -1,3 +1,4 @@ +import { itRunsE2eOnly } from "../../../__tests__/setup"; import { AlphaType, ColorType } from "../../../skia/types"; import { surface } from "../setup"; @@ -38,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/Skia.ts b/packages/skia/src/skia/types/Skia.ts index 6f9e392a50..ff7cee39f6 100644 --- a/packages/skia/src/skia/types/Skia.ts +++ b/packages/skia/src/skia/types/Skia.ts @@ -178,6 +178,21 @@ export interface Skia { ParagraphBuilder: ParagraphBuilderFactory; Skottie: SkottieFactory; Recorder(): JsiRecorder; + /** + * 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 and, on Android, each time the app + * goes to the background. + * + * It is meant for a one-off peak (a video export) followed by a long + * stretch that needs far less GPU memory. Not for a render loop, not after + * each `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; /** * 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/types/Surface/Surface.ts b/packages/skia/src/skia/types/Surface/Surface.ts index 9c4de96544..04edaf1cbc 100644 --- a/packages/skia/src/skia/types/Surface/Surface.ts +++ b/packages/skia/src/skia/types/Surface/Surface.ts @@ -32,7 +32,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. * @@ -57,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 diff --git a/packages/skia/src/skia/web/JsiSkia.ts b/packages/skia/src/skia/web/JsiSkia.ts index edb9024cb0..e3e3cc0bd6 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. + purgeGpuResources: () => {}, getNativeDevice: () => { return throwNotImplementedOnRNWeb(); },