Skip to content

[Impeller] Picture.toImageSync allocates a new GPU texture on every call; chained offscreen passes spend ~30% of the raster thread creating textures #193941

Open

Description

@b3nni97

Steps to reproduce

  1. Run the code sample below on an iPhone in release mode (flutter run --release).
  2. 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.
  3. Profile the raster thread with Instruments (Time Profiler, attach to the app).
  4. Compare with --dart-define=MODE=layer, which records the same amount of offscreen work with nested Canvas.saveLayer in 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.Image produced by toImageSync return its render target to RenderTargetCache when it is disposed, so that the next toImageSync of the same size and format can reuse it;
  • or an API to render a Picture into 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.77

Flutter 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

  1. added
    from: performance template
    on Oct 7, 2026
  2. added
    platform-ios
    engine
    perf: speed
    e: impeller
    team-engine
    on Oct 7, 2026
  3. mbcorona commented on Oct 7, 2026

    @mbcorona
    Member

    Hi @b3nni97, thanks for the repro and the profiler numbers.
    Routing to team-engine. The two directions you list are for them to weigh.

  4. added
    P1
    on Oct 12, 2026
  5. added
    triaged-engine
    on Oct 12, 2026
  6. gaaclarke commented on Oct 13, 2026

    @gaaclarke
    Member

    toImageSync allocates 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 toImageSync in terms of cpu and memory so I don't think that's probably worth pursuing.

  7. b3nni97 commented on Oct 13, 2026

    @b3nni97
    Author

    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.Image is disposed (or to render into an existing target)?

  8. gaaclarke commented on Oct 13, 2026

    @gaaclarke
    Member

    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.

  9. gaaclarke commented on Oct 13, 2026

    @gaaclarke
    Member

    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 RenderTargetCache the single render target pool (#193941)

    Summary

    Picture.toImageSync / toImage allocate a new set of render target textures for every call, bypassing RenderTargetCache. Workloads that make many snapshots per frame spend much of their raster time creating and destroying textures.

    This design makes RenderTargetCache the one pool for saveLayers and snapshots (Picture.toImage(Sync), Scene.toImage(Sync)):

    • Leases: the cache hands out separate shared_ptrs to its textures, each with its own control block, and watches them.
    • Reuse rule: an entry is free once it isn't used in the current frame and none of its leases is alive.
    • Results that outlive the frame: a snapshot just keeps its texture, and its entry stays "checked out" until that lease is released.

    Snapshots and saveLayers share entries in both directions, under one budget and one frame clock.

    Out of scope: TextShadowCache and DlImageImpeller::MakeFromYUVTextures keep calling DisableCache(). 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

    • Creating the image (UI thread): Picture.toImageSync(w, h) returns a ui.Image right away. Natively it's a DlDeferredImageGPUImpeller holding the picture's DisplayList (display_list_deferred_image_gpu_impeller.cc). It posts a task to the raster thread to render it.
    • Rendering it (raster thread): that task calls SnapshotDelegate::MakeImpellerSnapshotSync → SnapshotControllerImpeller → DoMakeRasterSnapshot → DisplayListToTexture. The resulting texture is stored in the image wrapper.
    • Other entry points:
      • Picture.toImage (async) takes the same path through MakeImpellerSnapshot and wraps the result in a DlImageImpeller.
      • Scene.toImage(Sync) first flattens the layer tree into a display list.
    • Timing: each snapshot is its own raster-thread task, separate from frame rasterization. Its cost doesn't show in FrameTiming.rasterDuration, but it delays the next frame.
    • Common use: multi-pass effects chain snapshots, each pass drawing the previous pass's image into a new picture and calling toImageSync again. The reporter's repro makes 32 such passes per frame.

    What an offscreen render target is made of

    DisplayListToTexture and saveLayer both render into an offscreen RenderTarget. With offscreen MSAA (Metal, Vulkan, most GLES), that's three textures:

    Texture Storage mode Purpose Lifetime
    MSAA color (4×) kDeviceTransient: memoryless on Apple GPUs, lazily allocated on Vulkan where supported Rendering target Only while rendering
    Resolve kDevicePrivate (real memory; lossy compression on Apple8+) Holds the result; sampled later As long as the result is used
    Depth/stencil kDeviceTransient Clipping Only while rendering

    Variations:

    • Without MSAA (float formats, devices without offscreen MSAA): a single color texture holds the result, plus depth/stencil.
    • Implicit resolve (GLES EXT_multisampled_render_to_texture): the MSAA texture is also the result.

    How RenderTargetCache works today

    RenderTargetCache is a RenderTargetAllocator owned by ContentContext (one per AiksContext). Its users:

    • Canvas for saveLayers and root passes that need an extra target (CreateRenderTarget);
    • EntityPassTarget;
    • filters through ContentContext::MakeSubpass.

    How it works:

    • Entries: each entry is a whole RenderTarget (all of its textures), keyed by RenderTargetConfig {size, mip_count, has_msaa, has_depth_stencil}. The key has no pixel format.
    • Lookup: CreateOffscreen(MSAA) returns the first entry with a matching config that isn't used_this_frame, rebuilt with the caller's attachment configs. If there's none, it allocates a new set and adds it.
    • Frame bookkeeping:
      • Start() clears used_this_frame on every entry.
      • End() keeps entries used since Start(). Other entries count down keep_alive_frame_count (default 4) and are evicted at zero.
    • Who drives it: every Canvas calls Start() in SetupRenderPass and End() in EndReplay. That includes onscreen surfaces (one per platform-view overlay too) and every snapshot. So a "frame" for the cache is really one Canvas.
    • The key assumption: a texture handed out isn't used after the next Start(). Nothing checks this. A texture still referenced later can be handed to someone else and overwritten.
    • Opting out: DisableCache()/EnableCache() turn caching off around work whose result must outlive the frame. TextShadowCache keeps blurred text shadows across frames, and DlImageImpeller::MakeFromYUVTextures produces a long-lived image.
    • Clearing: Clear() drops everything. Rasterizer::NotifyLowMemoryWarning calls it through ClearRenderTargetCache() ([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.Image that outlives the frame. Its lifetime is controlled by Dart:

    • dispose() or a GC finalizer on the UI thread;
    • pictures, display lists and layer trees that reference it, often released on the raster thread.

    The cache has no way to know when that image is released, so DisplayListToTexture deliberately doesn't use it ("the lifecycle of this texture will outlive a particular frame"). Instead it builds a plain RenderTargetAllocator each call and allocates all three textures. Canvas::SetupRenderPass also allocates the depth/stencil texture directly from the resource allocator.

    The costs:

    • Every snapshot allocates and frees a full set of textures. On iOS each allocation goes through -[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 equivalent saveLayer workload, which uses the cache, spent 0%. In the benchmark (Motivation), the resolve texture dominates, and its cost grows with size.
    • Snapshots also age the cache for everyone else. Each snapshot's Canvas calls Start()/End(). More than 4 snapshots between two frames evicts the onscreen frame's cached saveLayer targets, 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:

    Backend What keeps it safe today
    Metal Command buffers retain the MTLTexture, and textures track hazards by default (Impeller never changes hazardTrackingMode or uses unretained command buffers). So write-after-read on the same queue is ordered automatically.
    Vulkan CommandBufferVK keeps the TextureSourceVK (not the Texture) 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 for saveLayers, which are only read by fragment shaders.
    GLES Commands run in order on a single context.

    Framebuffer caching

    On Vulkan and GLES, the backend caches the framebuffer on the resolve (or color) texture:

    • render_pass_vk.cc
    • render_pass_gles.cc

    Both assume the MSAA and depth/stencil textures used with it never change. RenderTargetCache satisfies this by always handing out the same set of textures together.

    Related work

    Motivation

    The reported problem (#193941)

    The reporter's workload is a multi-pass effect: 32 chained Picture.toImageSync passes 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 nested saveLayers in a single picture, so its targets come from RenderTargetCache.

    Mode Raster thread CPU Creating textures (AGXTexture init… / IOGPUResourceCreate) Render pass setup
    toImageSync chain 41% of one core 29% of the raster thread (~1.0 ms per frame) 23%
    saveLayer baseline (cached) 26% of one core 0% 32%

    Other observations from the report:

    • The cost is hidden from FrameTiming. Snapshot work runs as separate raster tasks, so FrameTiming.rasterDuration reports a p50 of 0.27 ms for the snapshot chain against 2.05 ms for the saveLayer baseline. The time is real, though: it delays the next frame.
    • Larger apps feel it most at startup. In a bigger app with more and larger offscreen passes, frames start 0.5–1 s late right after launch, while the first large textures are being allocated.
    • There's no zero-latency workaround.

    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:

    • MSAA color: BGRA8, 4×, memoryless;
    • resolve: BGRA8, private, render target + shader read, lossy compression;
    • depth/stencil: D32Float_S8, 4×, memoryless.

    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):

    Texture Create Release
    Resolve (private) ~1.7 µs ~0.7 µs
    MSAA color (memoryless) ~0.43 µs ~0.1 µs
    Depth/stencil (memoryless) ~0.44 µs ~0.1 µs

    These costs are the same at 256², 1024² and 2048².

    A loop shaped like a snapshot. Each pass:

    • gets its textures;
    • encodes a render pass that clears the MSAA texture and resolves it;
    • commits its own command buffer (Impeller submits one per snapshot).

    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:

    Size Configuration Texture creation calls Encoding thread CPU Process CPU Wall time
    256² Allocate all three (today) 5.3 11.1 40.4 23.0
    256² Reuse MSAA + depth/stencil, allocate resolve 3.5 9.3 36.8 21.7
    256² Reuse all three 0.0 4.9 25.5 16.8
    1024² Allocate all three (today) 4.6 10.1 70.6 54.9
    1024² Reuse MSAA + depth/stencil, allocate resolve 3.2 8.7 68.6 54.6
    1024² Reuse all three 0.0 4.9 25.2 16.4
    2048² Allocate all three (today) 4.0 8.9 167 152
    2048² Reuse MSAA + depth/stencil, allocate resolve 2.9 8.0 166 152
    2048² Reuse all three 0.0 4.8 24.9 23.6

    What this shows:

    • The resolve texture dominates. Reusing only the two memoryless textures saves about 1–2 µs per pass. Reusing the resolve texture as well removes most of the remaining cost.
    • A newly allocated resolve texture has a second, larger cost that grows with size, beyond its creation call: process CPU of 40 → 71 → 167 µs per pass. It lands on threads other than the encoding thread, after creation. That's most likely the kernel setting up and zeroing pages on first use. Reusing the texture avoids it entirely.
    • With all three reused, the cost per pass is flat (about 25 µs of process CPU) regardless of size.

    Caveats:

    • Different hardware: this is a Mac, not an iPhone. The reporter's numbers work out to about 31 µs per pass creating textures (1.0 ms / 32), against about 5 µs of creation calls here, so the iOS path is heavier.
    • Allocation timing: the reporter's stack shows IOGPUResourceCreate inside 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:

    • render_pass_vk.cc
    • render_pass_gles.cc

    Keeping each set together preserves that.

    The cache never hands out the shared_ptr it owns. Every texture it returns is a lease.

    /// A texture owned by the cache. The owning pointer never leaves this class.
    class CachedTexture {
     public:
      explicit CachedTexture(std::shared_ptr<Texture> texture);
    
      /// Returns the current lease if one is alive, otherwise a new one. The
      /// lease's deleter keeps the texture alive even if the cache drops it.
      std::shared_ptr<Texture> Lease() {
        if (std::shared_ptr<Texture> lease = lease_.lock()) {
          return lease;
        }
        std::shared_ptr<Texture> lease(texture_.get(),
                                       [keep_alive = texture_](Texture*) {});
        lease_ = lease;
        return lease;
      }
    
      /// True while any lease is alive.
      bool IsLeased() const { return !lease_.expired(); }
    
     private:
      std::shared_ptr<Texture> texture_;  // Owning; never handed out.
      std::weak_ptr<Texture> lease_;
    };
    
    struct RenderTargetData {
      RenderTargetConfig config;  // Includes pixel format (section 4).
      /// The texture that holds the rendered result
      /// (`RenderTarget::GetRenderTargetTexture()`): the resolve texture with
      /// MSAA, otherwise the color texture. With implicit MSAA resolve
      /// (GLES `EXT_multisampled_render_to_texture`), this is the multisample
      /// texture itself.
      CachedTexture result;
      /// The multisample color texture. Absent without MSAA, and with implicit
      /// resolve (where `result` is the multisample texture).
      std::optional<CachedTexture> msaa;
      /// Used for both the depth and stencil attachments.
      std::optional<CachedTexture> depth_stencil;
      bool used_this_frame;
      uint32_t keep_alive_frame_count;
      /// Frames this entry has been checked out (leased past the frame).
      uint32_t checked_out_frame_count = 0;
    };
    • Handing out an entry: the cache builds the RenderTarget from leases, passing them as the existing_* textures to RenderTargetAllocator::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.
    • What callers see: only leases, which they can copy, keep, or make weak_ptrs from like any other texture.

    An entry can be handed out when both of these hold:

    1. !used_this_frame: no reuse within a frame, as today.
    2. No texture in the entry is leased: 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:

    • An expired lease can't come back. When the last strong reference to a lease drops, 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.
    • The owning pointer is private to CachedTexture. "Never hand it out" can be checked by reading one small class.
    • enable_shared_from_this is 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 a static_assert against it, with a comment pointing at CachedTexture.
    • Owner-based comparisons are unaffected. A lease and the owning pointer share get() but not the control block. Nothing in impeller/, lib/, shell/ or display_list/ uses owner_less, owner_before or owner_hash, and == and std::hash on shared_ptr use get().
    • All decisions stay on the raster thread. The last reference can drop on any thread (a ui.Image finalizer, the Vulkan fence thread). The lease deleter only releases its keep_alive copy.
    • Entries in use right now are protected regardless of frame flags. For example, a snapshot's root target is leased by its Canvas even after that canvas's own Start() clears used_this_frame.

    Cost: one control block allocation per distinct texture each time an entry is handed out (about 3 per saveLayer or snapshot).

    2. Snapshots use the cache

    DisplayListToTexture takes its render target from context.GetRenderTargetCache():

    • color: kDefaultColorAttachmentConfig(MSAA);
    • depth/stencil: the same config as 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_frames frames checked out, or immediately when over budget, the cache drops the entry:

    • its MSAA and depth/stencil textures are freed;
    • the result texture lives on with its owner (kept alive by the lease's deleter).

    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 to GetDefaultColorFormat() before the lookup. Without this, a float-format snapshot (kR32Float, kR32G32B32A32Float) could get a default-format entry.

    5. Vulkan: command buffers track the Texture by default; render passes opt out

    The problem. CommandBufferVK::Track(Texture) currently keeps only the TextureSourceVK alive. So a lease can expire while the GPU still reads the texture.

    • Fragment-shader reads are already ordered. The incoming dependency at the start of each render pass (render_pass_builder_vk.cc) waits for earlier fragment-shader reads and color-attachment writes. That's what makes reusing saveLayer entries across frames safe while earlier frames are in flight.
    • Other reads are not ordered:
      • transfer, e.g. toByteData (image_encoding_impeller.cc), whose completion lambda doesn't hold the texture;
      • compute, e.g. flutter_gpu;
      • vertex-stage sampling, possible in flutter_gpu render passes.

    The change:

    • CommandBufferVK::Track(std::shared_ptr<const Texture>) keeps the Texture (the lease) alive in TrackedObjectsVK until the fence signals, as well as its TextureSourceVK. Blit passes, compute passes and any future kind of pass get this automatically.

    • RenderPassVK tracks only the TextureSourceVK (e.g. a TrackTextureSourceOnly(...) helper, with a comment pointing at the render-pass dependency) for:

      • color, resolve and depth/stencil attachments;
      • textures bound for sampling with stage == ShaderStage::kFragment in BindResource.

      Other stages use the default. No Impeller entity shader samples textures in the vertex stage.

    Effects:

    • saveLayer reuse on Vulkan is unchanged; render passes don't hold leases past encoding.
    • A toByteData copy holds its lease until it completes.

    Metal and GLES need no change. Metal textures track hazards by default (Impeller never changes hazardTrackingMode or uses unretained command buffers), and GLES commands run in order.

    6. Frame clock

    Keep-alive must count onscreen frames, not Canvas instances (every Canvas, including each snapshot's, calls Start()/End()). With snapshots in the cache, counting per canvas would evict entries a chain of snapshots needs between frames.

    • Start()/End() (per Canvas) only clear and track used_this_frame.
    • New RenderTargetCache::AdvanceFrame() does the aging:
      • decrement keep-alive for free entries;
      • increment checked_out_frame_count for checked-out ones;
      • evict.
    • Rasterizer::DrawToSurfaces calls aiks_context->AdvanceFrame() once, after all views.
    • Callers without a Rasterizer (skwasm, the interop toolkit, playgrounds and tests) keep aging in End(). The shell turns on the external clock with SetUsesExternalFrameClock(true) when it creates the AiksContext.

    7. Budget

    • Count free entries plus the transient textures of checked-out entries. When over budget:
      1. evict free entries, least recently used first;
      2. then drop checked-out entries (section 3).
    • Tie into Adds memory budget to RenderTargetCache #193027, which adds a memory budget to 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

    Scenario Expected
    saveLayers within a frame Used this frame and leased by EntityPassTargets; reused next frame.
    toImageSync chain, each image disposed after the next pass is recorded Image i's last reference is task i+1's display list, released on the raster thread. Reads are fragment-shader samples, so about 2 entries per chain get reused on every backend. No allocations in steady state.
    Snapshot of the same size as a saveLayer Entries are shared both ways.
    Image drawn in the current layer tree Checked out until the next frame replaces the layer tree, then reused.
    Image kept for a long time After max_checked_out_frames frames the entry is dropped and its MSAA and depth/stencil freed. The result texture is unaffected.
    toByteData() then dispose() Vulkan: the blit's command buffer holds the lease until the copy completes. Metal/GLES: ordered by the backend.
    flutter_gpu Texture.fromImage Holds a lease, so the entry stays checked out.
    YUV conversion / text shadow snapshots Created with the cache disabled; never pooled.
    Float-format snapshot Separate entry because of the format key.

    Phased plan

    Phase Change Notes
    1 Frame clock: AdvanceFrame(), SetUsesExternalFrameClock(), the Rasterizer hook. Also fixes the Start()/End() aging bug on its own.
    2 Pixel format in RenderTargetConfig; CachedTexture leases, the reuse rule, checked_out_frame_count, static_asserts; Vulkan tracking by default with the RenderPassVK opt-out; DisplayListToTexture uses the cache. The fix for #193941.
    3 Budget that counts checked-out transient textures; #193027. Independent.

    Testing plan

    1. RenderTargetCache unit tests:
      • no reuse while any lease is alive;
      • reuse after release;
      • one lease for a texture used in two attachments;
      • weak_ptrs made from a lease don't keep an entry checked out;
      • an entry is dropped after max_checked_out_frames and its transient textures freed while the result stays valid;
      • format is part of the key;
      • aging in both clock modes.
    2. AiksTest:
      • a chain of snapshots reaches steady state with no new allocations after warm-up (counting allocator);
      • readback shows earlier images aren't overwritten while referenced (an existing test on branch snapshot-cache-transient-attachments can be reused);
      • a snapshot and a saveLayer of the same size share an entry.
    3. Vulkan:
      • CommandBufferVK tests: blit and compute passes keep the Texture until completion; RenderPassVK attachments and fragment-stage samples keep only the TextureSourceVK; vertex-stage samples keep the Texture.
      • Run with sync validation from the out dir, including readback → dispose → snapshot.
    4. Shell test: one AdvanceFrame() per frame across several views.
    5. On device: the reporter's repro in Instruments, before and after phases 1 and 2. Also run saveLayer-heavy benchmarks for regressions.

    Risks

    • Hot path: every saveLayer goes through this cache. The checks are a few atomic loads per entry, but the linear scan grows with snapshot entries. If needed, bucket entries by RenderTargetConfig hash.
    • Changed reuse rules: code that holds cache textures longer than expected now keeps entries checked out instead of having them reused under it. That's safer, but it can raise memory use. Log entries that stay checked out for a long time in debug builds.
    • Two clock modes: embedders without a Rasterizer keep aging in End(). We need to make sure the shell always switches to the external clock.

    Later improvements

    • Make the Vulkan and GLES framebuffer caches check the full set of attachments. That would allow pooling single textures, e.g. dropping only a checked-out entry's transient textures while its result texture stays available for reuse.
    • Allow reuse within a frame (drop rule 1) once the lease rule has proven reliable.

    Open questions

    • max_checked_out_frames: same as keep_alive_frame_count (4), or shorter?
    • Interim free-bytes cap (32 MB placeholder) until Adds memory budget to RenderTargetCache #193027: different on desktop vs mobile?
    • Depth/stencil attachments: the render-pass incoming dependency doesn't list the early/late fragment-test stages, so reusing depth textures across frames may already be a write-after-write hazard. This design doesn't change that, but it's worth checking with sync validation.
    • Where do the static_asserts against enable_shared_from_this live: each backend's texture header, or one place?
    • Ship phase 1 as the standalone fix for the Start()/End() aging bug before phase 2?

    Alternatives considered

    Cache only the transient attachments of snapshots

    • What: take the MSAA color and depth/stencil textures from RenderTargetCache, keep allocating the result texture, and keep those entries separate from saveLayer entries.
    • Status: implemented on branch snapshot-cache-transient-attachments (5221c51c438).
    • Rejected because: the two cached textures are memoryless on Apple GPUs and cheap to create. The benchmark showed only a small gain (256²: 40 → 37 µs per pass; 2048²: 167 → 166 µs), because the result texture is what's expensive.

    A separate pool for snapshot result textures

    • What: a SnapshotTexturePool next to RenderTargetCache, recycling only snapshot result textures.
    • Rejected because:
      • No sharing: snapshots and saveLayers couldn't use each other's textures.
      • More memory: two budgets and two eviction clocks.
      • Unsafe pairing: combined with cached transient attachments, it would pair recycled result textures with different MSAA or depth/stencil textures. That breaks the framebuffer-cache assumption in the next alternative.

    Pool individual textures instead of whole render targets

    • What: pool each texture on its own, so any free texture of the right shape can be used in any combination.
    • Rejected because: the Vulkan and GLES backends cache the framebuffer on the resolve (or color) texture and assume its MSAA and depth/stencil textures never change (render_pass_vk.cc, render_pass_gles.cc). Mixing textures would render into stale attachments.
    • Could be revisited once those caches check the full set of attachments (see Later improvements).

    Treat an entry as free when use_count() shows only the cache's references

    • What: the cache hands out its own shared_ptr and treats an entry as free when use_count() equals the references it holds itself.
    • Rejected because:
      • Not robust: it's only correct if no weak_ptr<Texture> exists anywhere and no texture class uses enable_shared_from_this. The cache's own strong reference keeps the control block alive, so any weak_ptr could lock() and revive a texture the cache considers free. Nothing would enforce that over time.
      • Fiddly bookkeeping: the cache would have to count its own references to textures used in two attachments.

    Return textures through a custom deleter

    • What: hand out shared_ptrs whose deleter returns the texture to the pool as soon as the last reference drops.
    • Rejected because:
      • the deleter runs on whatever thread drops the last reference, so the pool would need locking;
      • it fires as soon as the last reference drops, even while the GPU may still be reading the texture.

    Texture::HasPendingGPUWork() for entries that were checked out

    • What: a new virtual method, true on Vulkan while a command buffer still tracks the TextureSourceVK, checked only for entries that had been checked out (a was_checked_out flag).
    • Rejected because: it adds public Texture API and cache bookkeeping. Tracking the Texture in command buffers gives the same guarantee through the existing lease rule.

    Track the Texture in every Vulkan command buffer, including render passes

    • What: have every use in a command buffer hold the lease until its fence signals.
    • Rejected because: frame N's saveLayer entries 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

    • What: add eTransfer | eComputeShader (and the vertex stage) to the incoming dependency's srcStageMask, so all earlier reads are ordered before render-pass writes.
    • Rejected because: it changes synchronization for every render pass, and it still relies on every future kind of read being covered by that one mask. Tracking by default is safe for new kinds of pass without anyone remembering to update the mask.

    Also pool TextShadowCache and YUV conversion textures

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    P1e: impellerenginefrom: performance templateperf: speedplatform-iosteam-enginetriaged-engine

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions