Repository navigation
Description
Steps to reproduce
- Run the code sample below on an iPhone in release mode (
flutter run --release). - It renders, every frame, a chain of 32 offscreen passes of 256×256 px with
Picture.toImageSync, each pass drawing the previous pass's image (the pattern a multi-pass effect needs when every pass feeds the next one within the same frame), and draws the last image. - Profile the raster thread with Instruments (Time Profiler, attach to the app).
- Compare with
--dart-define=MODE=layer, which records the same amount of offscreen work with nestedCanvas.saveLayerin a single picture (not visually identical — it only serves as a baseline for the cost of offscreen render targets that come from Impeller's render target cache).
Expected results
Images that are created every frame and disposed right after use should not cost a new GPU texture allocation each time — or there should be a way to opt into reusing the render target of an image that has been disposed (similar to what RenderTargetCache already does for saveLayer).
Actual results
Every toImageSync call allocates a fresh texture: DisplayListToTexture (impeller/display_list/dl_dispatcher.cc) creates its render target through a new RenderTargetAllocator on the context's resource allocator, bypassing RenderTargetCache. On iOS, every allocation goes through -[AGXTexture initWithDevice:desc:isSuballocDisabled:] → IOGPUResourceCreate (a kernel call).
Raster thread, iPhone 16 Pro Max (iOS 27.0), 32 passes × 256×256 per frame at 120 Hz, 10 s Time Profiler each:
| mode | raster thread CPU | creating textures (AGXTexture init… / IOGPUResourceCreate) |
render pass setup (renderCommandEncoderWithDescriptor) |
|---|---|---|---|
snapshot (Picture.toImageSync chain) |
41 % of one core | 29 % of the raster thread (≈ 1.0 ms per frame) | 23 % |
layer (saveLayer, render target cache) |
26 % of one core | 0 % | 32 % |
Note that the cost of the toImageSync work does not show up in FrameTiming.rasterDuration (snapshot mode reports a raster p50 of 0.27 ms against 2.1 ms for the layer mode), because the snapshots are rasterized as separate tasks on the raster thread. The time is real, though: it delays the next frame's rasterization, and in a larger app with more and bigger offscreen passes we see frames start 0.5–1 s late right after launch, while the first big textures are being allocated.
There is currently no alternative that keeps zero frames of latency: flutter_gpu's Texture.fromImage cannot wrap a toImageSync image (it is not rasterized yet), and FragmentShader.setImageSampler only accepts a ui.Image (#136025).
Possible directions (any one would help):
- let a
ui.Imageproduced bytoImageSyncreturn its render target toRenderTargetCachewhen it is disposed, so that the nexttoImageSyncof the same size and format can reuse it; - or an API to render a
Pictureinto an existing image/texture of the same size (e.g. a reusable target object).
Related: #190613 (render target cache configuration), #192937 (host buffer growth on raster snapshots), #136025, #193775.
Code sample
Code sample
// Minimal reproduction: chained Picture.toImageSync passes allocate a new GPU
// texture for every pass, every frame.
//
// --dart-define=MODE=snapshot each pass is Picture.toImageSync (default)
// --dart-define=MODE=layer the same draws nested in Canvas.saveLayer
// within one picture (render targets come
// from Impeller's render target cache)
// --dart-define=PASSES=32 passes per frame
// --dart-define=SIZE=256 pass size in pixels
import 'dart:math' as math;
import 'dart:ui' as ui;
import 'package:flutter/scheduler.dart';
import 'package:flutter/widgets.dart';
const String kMode = String.fromEnvironment('MODE', defaultValue: 'snapshot');
const int kPasses = int.fromEnvironment('PASSES', defaultValue: 32);
const int kSize = int.fromEnvironment('SIZE', defaultValue: 256);
void main() => runApp(
const Directionality(textDirection: TextDirection.ltr, child: ReproPage()));
class ReproPage extends StatefulWidget {
const ReproPage({super.key});
@override
State<ReproPage> createState() => _ReproPageState();
}
class _ReproPageState extends State<ReproPage>
with SingleTickerProviderStateMixin {
late final Ticker _ticker =
createTicker((Duration d) => setState(() => _t = d));
Duration _t = Duration.zero;
@override
void initState() {
super.initState();
_ticker.start();
}
@override
void dispose() {
_ticker.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return ColoredBox(
color: const Color(0xFF000000),
child: Center(
child: CustomPaint(
size: const Size.square(300),
painter: _ChainPainter(_t.inMicroseconds / 1e6),
),
),
);
}
}
class _ChainPainter extends CustomPainter {
_ChainPainter(this.t);
final double t;
// One pass: the previous result, slightly rotated, plus a moving square.
void _pass(Canvas c, int i, ui.Image? previous) {
final Rect r = Rect.fromLTWH(0, 0, kSize.toDouble(), kSize.toDouble());
c.drawRect(r, Paint()..color = Color.fromARGB(255, (i * 7) % 255, 40, 90));
if (previous != null) {
c.save();
c.translate(kSize / 2, kSize / 2);
c.rotate(0.02);
c.translate(-kSize / 2, -kSize / 2);
c.drawImageRect(previous, r, r.deflate(4), Paint());
c.restore();
}
final double x = (math.sin(t * 2 + i) * 0.5 + 0.5) * (kSize - 40);
c.drawRect(Rect.fromLTWH(x, 20, 40, 40),
Paint()..color = const Color(0xFFFFFFFF));
}
@override
void paint(Canvas canvas, Size size) {
final Rect dst = Offset.zero & size;
final Rect src = Rect.fromLTWH(0, 0, kSize.toDouble(), kSize.toDouble());
if (kMode == 'layer') {
// The same amount of offscreen work in one picture.
canvas.save();
canvas.scale(size.width / kSize);
for (int i = 0; i < kPasses; i++) {
canvas.saveLayer(src, Paint());
_pass(canvas, i, null);
}
for (int i = 0; i < kPasses; i++) {
canvas.restore();
}
canvas.restore();
return;
}
ui.Image? previous;
for (int i = 0; i < kPasses; i++) {
final ui.PictureRecorder recorder = ui.PictureRecorder();
_pass(Canvas(recorder), i, previous);
final ui.Picture picture = recorder.endRecording();
final ui.Image image = picture.toImageSync(kSize, kSize);
picture.dispose();
previous?.dispose();
previous = image;
}
canvas.drawImageRect(previous!, src, dst, Paint());
previous.dispose();
}
@override
bool shouldRepaint(_ChainPainter old) => old.t != t;
}Performance profiling on master channel
- The issue still persists on the master channel
Timeline Traces
Timeline Traces JSON
The cost is on the raster thread outside the frame's own raster work, so the Instruments Time Profiler breakdown above is more telling than a DevTools timeline.
Video demonstration
Video demonstration
[Upload media here]
What target platforms are you seeing this bug on?
iOS
OS/Browser name and version | Device information
iPhone 16 Pro Max (A18 Pro), iOS 27.0 (24A437)
Does the problem occur on emulator/simulator as well as on physical devices?
Unknown
Is the problem only reproducible with Impeller?
Yes
Logs
Logs
FrameTiming over 2 s (242 frames each), collected with SchedulerBinding.addTimingsCallback:
mode=snapshot passes=32 size=256 frames=242 build ms p50 0.56 p90 0.63 | raster ms p50 0.27 p90 0.31
mode=layer passes=32 size=256 frames=242 build ms p50 0.20 p90 0.34 | raster ms p50 2.05 p90 2.77Flutter Doctor output
Doctor output
[✓] Flutter (Channel master, 3.49.0-1.0.pre-337, on macOS 26.5.1 25F80 darwin-arm64)
• Framework revision d454b1b841, 2026-10-06 16:52:01 +0000
• Engine revision a554b8ac18
• Dart version 3.14.0 (build 3.14.0-311.0.dev)
• DevTools version 2.61.0
[✓] Xcode - develop for iOS and macOS (Xcode 27.0)
• Build 27A266a
• CocoaPods version 1.16.2
[✓] Connected device
• iPhone (mobile) • ios • iOS 27.0 24A437
Activity
mbcorona commentedon Oct 7, 2026
Hi @b3nni97, thanks for the repro and the profiler numbers.
Routing to team-engine. The two directions you list are for them to weigh.
gaaclarke commentedon Oct 13, 2026
toImageSyncallocates 3 textures: the msaa color texture, depth+stencil buffer, resolve texture.I tried routing [the msaa color texture, depth+stencil buffer] to the render target cache because they are used temporarily and could be easily cleaned up. Since they are transient textures though they are memoryless and contribute little to the cost of
toImageSyncin terms of cpu and memory so I don't think that's probably worth pursuing.b3nni97 commentedon Oct 13, 2026
Most of what we measured is probably the resolve texture, i.e. the image itself. In a chain the image is disposed right after the next pass reads it, so a texture of the same size and format would be free again every frame. Would it be feasible to return the resolve texture to the cache when the
ui.Imageis disposed (or to render into an existing target)?gaaclarke commentedon Oct 13, 2026
Yes, it's possible. It's not trivial though. Once you start recycling things you have to make sure the GPU is not still referencing them on vulkan. This is not going to be a 30 line fix, this is is more like a 500 line fix with a design doc and the risk of synchronization errors or memory errors.
gaaclarke commentedon Oct 13, 2026
I've poked around and iterated on a design with an agent to get a feel for the scope of the fix. There have been a lot of questions about the render target cache lately, it's worth maybe revisiting again with this use case in mind. This design sounds pretty reasonable but is pretty involved and will be worth iterating on with the team.
Details
Make
RenderTargetCachethe single render target pool (#193941)Summary
Picture.toImageSync/toImageallocate a new set of render target textures for every call, bypassingRenderTargetCache. Workloads that make many snapshots per frame spend much of their raster time creating and destroying textures.This design makes
RenderTargetCachethe one pool forsaveLayers and snapshots (Picture.toImage(Sync),Scene.toImage(Sync)):shared_ptrs to its textures, each with its own control block, and watches them.Snapshots and
saveLayers share entries in both directions, under one budget and one frame clock.Out of scope:
TextShadowCacheandDlImageImpeller::MakeFromYUVTextureskeep callingDisableCache(). Their textures must keep their contents across frames and are long-lived, so pooling them gains nothing (see Alternatives considered).Background
How a snapshot is produced
Picture.toImageSync(w, h)returns aui.Imageright away. Natively it's aDlDeferredImageGPUImpellerholding the picture'sDisplayList(display_list_deferred_image_gpu_impeller.cc). It posts a task to the raster thread to render it.SnapshotDelegate::MakeImpellerSnapshotSync→SnapshotControllerImpeller→DoMakeRasterSnapshot→DisplayListToTexture. The resulting texture is stored in the image wrapper.Picture.toImage(async) takes the same path throughMakeImpellerSnapshotand wraps the result in aDlImageImpeller.Scene.toImage(Sync)first flattens the layer tree into a display list.FrameTiming.rasterDuration, but it delays the next frame.toImageSyncagain. The reporter's repro makes 32 such passes per frame.What an offscreen render target is made of
DisplayListToTextureandsaveLayerboth render into an offscreenRenderTarget. With offscreen MSAA (Metal, Vulkan, most GLES), that's three textures:kDeviceTransient: memoryless on Apple GPUs, lazily allocated on Vulkan where supportedkDevicePrivate(real memory; lossy compression on Apple8+)kDeviceTransientVariations:
EXT_multisampled_render_to_texture): the MSAA texture is also the result.How
RenderTargetCacheworks todayRenderTargetCacheis aRenderTargetAllocatorowned byContentContext(one perAiksContext). Its users:CanvasforsaveLayers and root passes that need an extra target (CreateRenderTarget);EntityPassTarget;ContentContext::MakeSubpass.How it works:
RenderTarget(all of its textures), keyed byRenderTargetConfig {size, mip_count, has_msaa, has_depth_stencil}. The key has no pixel format.CreateOffscreen(MSAA)returns the first entry with a matching config that isn'tused_this_frame, rebuilt with the caller's attachment configs. If there's none, it allocates a new set and adds it.Start()clearsused_this_frameon every entry.End()keeps entries used sinceStart(). Other entries count downkeep_alive_frame_count(default 4) and are evicted at zero.CanvascallsStart()inSetupRenderPassandEnd()inEndReplay. That includes onscreen surfaces (one per platform-view overlay too) and every snapshot. So a "frame" for the cache is really oneCanvas.Start(). Nothing checks this. A texture still referenced later can be handed to someone else and overwritten.DisableCache()/EnableCache()turn caching off around work whose result must outlive the frame.TextShadowCachekeeps blurred text shadows across frames, andDlImageImpeller::MakeFromYUVTexturesproduces a long-lived image.Clear()drops everything.Rasterizer::NotifyLowMemoryWarningcalls it throughClearRenderTargetCache()([Impeller] Add render target cache clearing and test hook #193497).Why snapshots bypass the cache, and what that costs
The bypass. A snapshot's result is a
ui.Imagethat outlives the frame. Its lifetime is controlled by Dart:dispose()or a GC finalizer on the UI thread;The cache has no way to know when that image is released, so
DisplayListToTexturedeliberately doesn't use it ("the lifecycle of this texture will outlive a particular frame"). Instead it builds a plainRenderTargetAllocatoreach call and allocates all three textures.Canvas::SetupRenderPassalso allocates the depth/stencil texture directly from the resource allocator.The costs:
-[AGXTexture initWithDevice:…]→IOGPUResourceCreate(a kernel call). The reporter measured 29% of the raster thread spent creating textures for 32 × 256² snapshots per frame at 120 Hz. The equivalentsaveLayerworkload, which uses the cache, spent 0%. In the benchmark (Motivation), the resolve texture dominates, and its cost grows with size.CanvascallsStart()/End(). More than 4 snapshots between two frames evicts the onscreen frame's cachedsaveLayertargets, so they get reallocated next frame too.GPU lifetime and synchronization by backend
Reusing a texture is only safe once earlier GPU work that reads it is ordered before the new writes:
MTLTexture, and textures track hazards by default (Impeller never changeshazardTrackingModeor uses unretained command buffers). So write-after-read on the same queue is ordered automatically.CommandBufferVKkeeps theTextureSourceVK(not theTexture) alive until its fence signals. Reuse is ordered by the incoming dependency at the start of each render pass (render_pass_builder_vk.cc), which waits for earlier fragment-shader reads and color-attachment writes, but not transfer, compute or vertex-stage reads. That's enough forsaveLayers, which are only read by fragment shaders.Framebuffer caching
On Vulkan and GLES, the backend caches the framebuffer on the resolve (or color) texture:
Both assume the MSAA and depth/stencil textures used with it never change.
RenderTargetCachesatisfies this by always handing out the same set of textures together.Related work
RenderTargetCacheconfiguration.RenderTargetCache.FragmentShader.setImageSampleronly acceptsui.Image, which is one reason effects usetoImageSyncchains.Motivation
The reported problem (#193941)
The reporter's workload is a multi-pass effect: 32 chained
Picture.toImageSyncpasses of 256×256 per frame, each drawing the previous pass's image. They profiled it on an iPhone 16 Pro Max (iOS 27, 120 Hz, release mode) with the Instruments Time Profiler and compared it with a baseline. The baseline records the same amount of offscreen work as nestedsaveLayers in a single picture, so its targets come fromRenderTargetCache.AGXTexture init…/IOGPUResourceCreate)toImageSyncchainsaveLayerbaseline (cached)Other observations from the report:
FrameTiming. Snapshot work runs as separate raster tasks, soFrameTiming.rasterDurationreports a p50 of 0.27 ms for the snapshot chain against 2.05 ms for thesaveLayerbaseline. The time is real, though: it delays the next frame.Texture.fromImagecan't wrap atoImageSyncimage, because it isn't rasterized yet.FragmentShader.setImageSampleronly accepts aui.Image(Feature request for FragmentShader.setImageSampler to support Texture #136025).Where the time goes: microbenchmark
To see which of the three textures (Background: "What an offscreen render target is made of") costs the most, a small Metal program (texbench.m) creates them with the same descriptors Impeller uses:
It ran on an Apple M5 Max (macOS 26.7). Each configuration ran 3 times; results varied by under about 5%.
Creating one texture on its own (5000 iterations, cost per texture):
These costs are the same at 256², 1024² and 2048².
A loop shaped like a snapshot. Each pass:
There are 32 passes per frame, with a wait for the GPU at each frame boundary, over 300 frames after warm-up. Three configurations, in µs per pass:
What this shows:
Caveats:
IOGPUResourceCreateinside texture creation, so iOS may do at creation time some of the work macOS defers.The proportions should still hold: the result texture is the one worth reusing, and the target is the "reuse all three" row.
Design
1. Entries, leases and the reuse rule
Entries stay whole render targets (MSAA color + resolve + depth/stencil). The Vulkan and GLES backends cache the framebuffer on the resolve (or color) texture and assume its companion attachments never change:
Keeping each set together preserves that.
The cache never hands out the
shared_ptrit owns. Every texture it returns is a lease.RenderTargetfrom leases, passing them as theexisting_*textures toRenderTargetAllocator::CreateOffscreen(MSAA)with the caller's attachment configs, as the cache already does today.depth_stencil's lease goes into both the depth and stencil attachments. With implicit resolve,result's lease goes in as both the multisample and the resolve texture.weak_ptrs from like any other texture.An entry can be handed out when both of these hold:
!used_this_frame: no reuse within a frame, as today.IsLeased()is false for all of them. On Vulkan, GPU work that render-pass barriers don't order also holds the lease until it completes (section 5).Why this is safe:
weak_ptr::lock()on it returns null forever (a standard library guarantee).weak_ptrs made from a lease point at the lease's control block, not the cache's.CachedTexture. "Never hand it out" can be checked by reading one small class.enable_shared_from_thisis ruled out at compile time.shared_from_this()would return a pointer from the owning control block. Each backend texture (TextureMTL,TextureVK,TextureGLES) and the test mock gets astatic_assertagainst it, with a comment pointing atCachedTexture.get()but not the control block. Nothing inimpeller/,lib/,shell/ordisplay_list/usesowner_less,owner_beforeorowner_hash, and==andstd::hashonshared_ptruseget().ui.Imagefinalizer, the Vulkan fence thread). The lease deleter only releases itskeep_alivecopy.Canvaseven after that canvas's ownStart()clearsused_this_frame.Cost: one control block allocation per distinct texture each time an entry is handed out (about 3 per
saveLayeror snapshot).2. Snapshots use the cache
DisplayListToTexturetakes its render target fromcontext.GetRenderTargetCache():kDefaultColorAttachmentConfig(MSAA);Canvas(kDeviceTransient,kDontCare/kDontCare).It returns
GetRenderTargetTexture()and drops the rest of the render target, so only the result texture's lease survives and the entry is checked out.3. Checked-out entries and memory
A checked-out entry still holds its MSAA and depth/stencil textures. That's free on Metal (memoryless) and on Vulkan with lazily allocated memory, but real memory elsewhere.
So after
max_checked_out_framesframes checked out, or immediately when over budget, the cache drops the entry:Short-lived results come back and get reused. Long-lived ones stop holding transient memory after a few frames.
4. Pixel format in the cache key
Add the pixel format to
RenderTargetConfig(operator==,Hash,ToConfig). Requests without a format resolve toGetDefaultColorFormat()before the lookup. Without this, a float-format snapshot (kR32Float,kR32G32B32A32Float) could get a default-format entry.5. Vulkan: command buffers track the
Textureby default; render passes opt outThe problem.
CommandBufferVK::Track(Texture)currently keeps only theTextureSourceVKalive. So a lease can expire while the GPU still reads the texture.saveLayerentries across frames safe while earlier frames are in flight.toByteData(image_encoding_impeller.cc), whose completion lambda doesn't hold the texture;The change:
CommandBufferVK::Track(std::shared_ptr<const Texture>)keeps theTexture(the lease) alive inTrackedObjectsVKuntil the fence signals, as well as itsTextureSourceVK. Blit passes, compute passes and any future kind of pass get this automatically.RenderPassVKtracks only theTextureSourceVK(e.g. aTrackTextureSourceOnly(...)helper, with a comment pointing at the render-pass dependency) for:stage == ShaderStage::kFragmentinBindResource.Other stages use the default. No Impeller entity shader samples textures in the vertex stage.
Effects:
saveLayerreuse on Vulkan is unchanged; render passes don't hold leases past encoding.toByteDatacopy holds its lease until it completes.Metal and GLES need no change. Metal textures track hazards by default (Impeller never changes
hazardTrackingModeor uses unretained command buffers), and GLES commands run in order.6. Frame clock
Keep-alive must count onscreen frames, not
Canvasinstances (everyCanvas, including each snapshot's, callsStart()/End()). With snapshots in the cache, counting per canvas would evict entries a chain of snapshots needs between frames.Start()/End()(perCanvas) only clear and trackused_this_frame.RenderTargetCache::AdvanceFrame()does the aging:checked_out_frame_countfor checked-out ones;Rasterizer::DrawToSurfacescallsaiks_context->AdvanceFrame()once, after all views.Rasterizer(skwasm, the interop toolkit, playgrounds and tests) keep aging inEnd(). The shell turns on the external clock withSetUsesExternalFrameClock(true)when it creates theAiksContext.7. Budget
RenderTargetCache. Until then, cap free bytes at a placeholder of 32 MB.8. Low memory
Unchanged:
Rasterizer::NotifyLowMemoryWarning→ClearRenderTargetCache()→RenderTargetCache::Clear()drops all entries. Checked-out results stay alive with their owners.Lifetime scenarios
saveLayers within a frameEntityPassTargets; reused next frame.toImageSyncchain, each image disposed after the next pass is recordedsaveLayermax_checked_out_framesframes the entry is dropped and its MSAA and depth/stencil freed. The result texture is unaffected.toByteData()thendispose()Texture.fromImagePhased plan
AdvanceFrame(),SetUsesExternalFrameClock(), theRasterizerhook.Start()/End()aging bug on its own.RenderTargetConfig;CachedTextureleases, the reuse rule,checked_out_frame_count,static_asserts; Vulkan tracking by default with theRenderPassVKopt-out;DisplayListToTextureuses the cache.Testing plan
RenderTargetCacheunit tests:weak_ptrs made from a lease don't keep an entry checked out;max_checked_out_framesand its transient textures freed while the result stays valid;snapshot-cache-transient-attachmentscan be reused);saveLayerof the same size share an entry.CommandBufferVKtests: blit and compute passes keep theTextureuntil completion;RenderPassVKattachments and fragment-stage samples keep only theTextureSourceVK; vertex-stage samples keep theTexture.AdvanceFrame()per frame across several views.saveLayer-heavy benchmarks for regressions.Risks
saveLayergoes through this cache. The checks are a few atomic loads per entry, but the linear scan grows with snapshot entries. If needed, bucket entries byRenderTargetConfighash.Rasterizerkeep aging inEnd(). We need to make sure the shell always switches to the external clock.Later improvements
Open questions
max_checked_out_frames: same askeep_alive_frame_count(4), or shorter?static_asserts againstenable_shared_from_thislive: each backend's texture header, or one place?Start()/End()aging bug before phase 2?Alternatives considered
Cache only the transient attachments of snapshots
RenderTargetCache, keep allocating the result texture, and keep those entries separate fromsaveLayerentries.snapshot-cache-transient-attachments(5221c51c438).A separate pool for snapshot result textures
SnapshotTexturePoolnext toRenderTargetCache, recycling only snapshot result textures.saveLayers couldn't use each other's textures.Pool individual textures instead of whole render targets
Treat an entry as free when
use_count()shows only the cache's referencesshared_ptrand treats an entry as free whenuse_count()equals the references it holds itself.weak_ptr<Texture>exists anywhere and no texture class usesenable_shared_from_this. The cache's own strong reference keeps the control block alive, so anyweak_ptrcouldlock()and revive a texture the cache considers free. Nothing would enforce that over time.Return textures through a custom deleter
shared_ptrs whose deleter returns the texture to the pool as soon as the last reference drops.Texture::HasPendingGPUWork()for entries that were checked outTextureSourceVK, checked only for entries that had been checked out (awas_checked_outflag).TextureAPI and cache bookkeeping. Tracking theTexturein command buffers gives the same guarantee through the existing lease rule.Track the
Texturein every Vulkan command buffer, including render passessaveLayerentries would stay leased until frame N finishes on the GPU. Frame N+1 is usually encoded before then, so it would allocate a second set, costing about frames-in-flight × one frame's render targets in memory on Vulkan. Render-pass reads are already ordered by barriers, so the opt-out loses nothing.Widen the render pass's incoming dependency
eTransfer | eComputeShader(and the vertex stage) to the incoming dependency'ssrcStageMask, so all earlier reads are ordered before render-pass writes.Also pool
TextShadowCacheand YUV conversion texturesDisableCache()calls and rely on the lease rule to keep their textures checked out while held.