Repository navigation
[Flutter GPU] Record on the UI thread, encode and submit on the raster thread - #194882
Conversation
There was a problem hiding this comment.
Code Review
This pull request refactors the Flutter GPU command submission by introducing a recording and replay mechanism. Commands are recorded into RenderPassRecording and CommandBufferRecording on the UI thread and subsequently replayed and submitted on the raster thread. Additionally, BindingSet now snapshots its contents to prevent post-binding mutations from affecting recorded draws, and shader registration is scheduled asynchronously. Feedback on these changes suggests adding validation checks for buffer offsets and lengths across several binding and copy operations to prevent potential integer overflows and out-of-bounds memory accesses.
|
Eh still thinking through this. I would like to avoid recording stuff to an intermediary buffer and shipping it over if possible. |
gaaclarke
left a comment
There was a problem hiding this comment.
Eh still thinking through this. I would like to avoid recording stuff to an intermediary buffer and shipping it over if possible.
Did I grab this PR too eagerly for review? From your last comment it seemed you are still trying to think things over. Let me know if you are in fact ready.
There are some merge conflicts that have to be resolved anyways. I didn't dig into this yet, I imagine it may be painful but I think we need to pull off the bandaide sooner than later. I imagine there will be performance benefits too anyways? Ultimately people usually will want a threading split between setting up draws versus performing drawing.
|
@bdero friendly ping on this, wondering where you are with this. I'm very interested in it. |
|
Sorry for the silence. I'm keeping the UI/raster split, but reworking the recording into plain data with no per-op refcounting so replay can overlap recording, then I'll rebase and ping you. |
3153992 to
e50a2dc
Compare
A thread that can react may still have unflushed commands using an object it releases, and a deletion issued from another context is not ordered after them. ReactorGLES now leaves such deletions to the releasing thread, as it already does for framebuffers. Objects released on a thread without a context are still deleted by any reacting thread. Without this, a texture released on the raster thread right after a pass sampled it could be deleted by the IO thread's next reaction (a pipeline compile or an upload) before the raster context flushed the draw.
bb4db33 to
753fbfb
Compare
…r thread Flutter GPU no longer touches Impeller's command buffers, passes, or the render pipeline, shader, and sampler libraries from the UI thread. Passes record plain data and are handed to the raster thread as they end, so encoding overlaps recording the next pass. A recording keeps what it uses alive until the GPU finishes. Compute pipelines are still created on the calling thread, which keeps their errors synchronous. Only compute encoding moved.
2eca406 to
ee8d4ae
Compare
|
🎺 🎵 🎵 🎵 ❗ |
|
@gaaclarke This is finally ready for another look. I rebased it and narrowed it to the threading fix + a GLES reactor fix for a problem that was exacerbated by this change. Huge PR, but the vast majority is pure refactoring of Flutter GPU's internals. Plain-data recording with no per-op refcounting that I mentioned earlier is stacked on top via #196621, along with the Impeller per-draw savings. I plan to mark that one ready once this lands. With both changes, my 12k-draw scene on an M3 Max goes from about 17 to 27 fps. And we're finally at the point where well designed renderers built on flutter_gpu can achieve zero per-draw heap allocations on steady state frames. |
gaaclarke
left a comment
There was a problem hiding this comment.
I didn't get a chance to look through the flutter_gpu stuff, that's going to be easier to review. I do think there may be a problem with the reactor changes though so I wanted to get that in your hands before I finish the full review tomorrow.
| } | ||
|
|
||
| /// The inverse of `ToKey`, apart from the label, which keys don't hold. | ||
| static SamplerDescriptor FromKey(uint64_t key) { |
There was a problem hiding this comment.
Let's add a unit test for this. You can probably just do fuzz(&x); EXPECT_EQ(x, FromKey(ToKey(x)).
| EXPECT_EQ(cleanup_thread, std::this_thread::get_id()); | ||
| } | ||
|
|
||
| TEST(ReactorGLES, SharedHandleDeletedOnCollectingThread) { |
There was a problem hiding this comment.
Can you add a simple comment above theses tests. They are complicated enough that you have to read through them to understand what is being tested. You can't just grok it from the names.
| HandleGLES handle = reactor->CreateHandle(HandleType::kTexture); | ||
|
|
||
| std::thread::id cleanup_thread; | ||
| reactor->RegisterCleanupCallback( |
There was a problem hiding this comment.
nit: Instead of registering a cleanup callback we can just mock out DeleteTextures
There was a problem hiding this comment.
Done in c7b2f5c. The mock never routed glDeleteFramebuffers, so I wired that up for the new framebuffer test and moved CanCallUnmockedFunction to glDeleteRenderbuffers.
| if (owner_thread.has_value() && *owner_thread != current_thread) { | ||
| continue; | ||
| } | ||
| // Objects collected by a thread that can react are deleted on that | ||
| // thread, after the commands its context issued against them. | ||
| const auto& collecting_thread = handle.second.collecting_thread; | ||
| if (collecting_thread.has_value() && | ||
| *collecting_thread != current_thread) { | ||
| continue; | ||
| } |
There was a problem hiding this comment.
I think you can end up with a leak for framebuffers here where owner_thread != current_thread and collecting_thread != current_thread.
Gemini's description of the scenario is below:
Take a cached FBO created on the raster thread (R) whose texture is later destroyed on the IO thread (I), which has its resource context current.
Field Value Set where owner_threadR HandleGLES::Create(kFrameBuffer), called fromCreateUntrackedHandlewhile the raster thread encodes the render passcollecting_threadI CollectHandleon the IO thread, becauseCanReactOnCurrentThread()is true therecurrent_threadwhichever thread is running ConsolidateHandlesbelow Each time a thread reacts:
current_threadOwner check ( owner != current→ skip)Collecting check ( collecting != current→ skip)Result R R == R → passes I != R → skip not deleted I R != I → skip (not reached) not deleted any other thread R != X → skip (not reached) not deleted Both checks can only pass when
owner_thread == collecting_thread == current_thread. Here R ≠ I, so no thread ever qualifies.Before the PR,
collecting_threaddidn't exist, so the R row passed and the raster thread deleted the FBO.
We should add a test for framebuffers since they are treated different source source.
There was a problem hiding this comment.
Good catch, that leaked. An owner thread now overrides the collecting thread, since only the owner's context can have commands against a framebuffer, and FramebufferCollectedOnAnotherThreadDeletedOnOwnerThread covers tracked and untracked handles in c7b2f5c.
…ad collects it A framebuffer created on one thread and collected by another thread that can react passed neither the owner check nor the collecting thread check, so no thread ever deleted it. An owner thread now overrides the collecting thread, since only the owner's context can have issued commands against an unshareable object. The reactor tests now mock the GL delete calls instead of registering cleanup callbacks, which suppressed the delete. That needs the GLES mock to route glDeleteFramebuffers, so the unmocked call test moves to glDeleteRenderbuffers. SamplerDescriptor::FromKey gets a round trip test.
gaaclarke
left a comment
There was a problem hiding this comment.
Okay, changes to impeller proper look good. I gave the flutter_gpu part a look. I have some requests for explicit ownership in the recording. 😵 That's a lot of code but it's mostly looking good to me.
| struct RecordingChunk { | ||
| static constexpr size_t kSize = 64 * 1024; | ||
|
|
||
| RecordingChunk* next = nullptr; |
There was a problem hiding this comment.
|
|
||
| void AddChunk(); | ||
|
|
||
| RecordingChunk* head_ = nullptr; |
There was a problem hiding this comment.
This can be moved to std::unique_ptr too.
| explicit PassReplayer(impeller::Context& context); | ||
|
|
||
| /// Replays a render pass. Draws whose pipeline fails to build are dropped. | ||
| void ReplayRender(PassRecording& recording, impeller::RenderPass& pass); |
There was a problem hiding this comment.
Does the recording need to be a non-const ref?
There was a problem hiding this comment.
It does for render passes, since replay resolves the pipeline and retains it on the recording so it outlives the GPU work. I documented that on ReplayRender in df662a3, and the compute and blit paths take it const.
| std::unordered_map<std::string, UniformBinding> uniform_structs; | ||
| std::unordered_map<std::string, TextureBinding> uniform_textures; |
There was a problem hiding this comment.
you should be using absl containers here too, flat_hash_map or node_hash_map if you need it
There was a problem hiding this comment.
Done in df662a3. flat_hash_map is enough since the reflection is never modified once built, so entry pointers stay valid.
…lection with absl maps
gaaclarke
left a comment
There was a problem hiding this comment.
woo, thanks brandon. exciting chapter in flutter_gpu's life.
| RecordingChunk* next = head_->next; | ||
| delete head_; | ||
| head_ = next; | ||
| head_ = std::move(head_->next); |
There was a problem hiding this comment.
nit: you can just call head_.reset() at this point =)
There was a problem hiding this comment.
was being overly cautious and avoiding any per-chunk recursion... but yeah, it probably doesn't matter in practice. I think we'd need 100s of MB of ops in a single pass to overflow. Left it since the follow-up moves chunk release into a pool that has to walk the chain anyway.
gaaclarke
left a comment
There was a problem hiding this comment.
Meta question: In the future could we maybe use display_lists for this?
Hmm plausibly... Kind of dig that idea. Later on when we're maximizing integration, it might be favorable to allow recording of flutter_gpu passes into the same display_list stream as the rest of UI, so they can be interleaved with canvas ops & express dependency relationships more easily. (We'd still need to keep standalone queueing for workloads not tied to a particular frame, though) |
Roll Flutter from e8cc6f3451b7 to b34b017b48ad (36 revisions) flutter/flutter@e8cc6f3...b34b017 2026-11-20 [email protected] Fix OverflowBox dry layout when deferToChild overrides the constraints (flutter/flutter#196839) 2026-11-20 [email protected] Roll Dart SDK from f118f476ebce to 3b5f45d812f8 (1 revision) (flutter/flutter#197048) 2026-11-20 [email protected] [macOS] Register plugins in multiple_windows example (flutter/flutter#196068) 2026-11-20 [email protected] Roll Skia from 87027a9d4659 to a1edf5c2ea5c (1 revision) (flutter/flutter#197045) 2026-11-20 [email protected] Add highp directives to UberSDF to prevent overflow (flutter/flutter#196997) 2026-11-20 [email protected] [Impeller] Cap the Vulkan command pool recycler cache (flutter/flutter#194793) 2026-11-20 [email protected] Roll Skia from 12610b69511d to 87027a9d4659 (4 revisions) (flutter/flutter#197037) 2026-11-20 [email protected] [macOS] Unregister nil binary message handlers (flutter/flutter#193672) 2026-11-20 [email protected] Roll Dart SDK from b803c3ec01de to f118f476ebce (2 revisions) (flutter/flutter#197034) 2026-11-20 [email protected] Roll Skia from 2f1436ba8e64 to 12610b69511d (3 revisions) (flutter/flutter#197030) 2026-11-20 [email protected] [Android] Do not use the HCPP external view embedder from its platform tasks (flutter/flutter#196490) 2026-11-20 [email protected] Roll Dart SDK from 849e17ad3ae6 to b803c3ec01de (1 revision) (flutter/flutter#197012) 2026-11-20 [email protected] [iOS a11y] Synchronize hit-test children when replacing semantics objects (flutter/flutter#196439) 2026-11-20 [email protected] Sync CHANGELOG.md from stable (flutter/flutter#197019) 2026-11-19 [email protected] [flutter_tools] Reland "Extract Windows archives using native tar" (flutter/flutter#193515) 2026-11-19 [email protected] [Reland][flutter_tools] Migrate lib/runner.dart off runInContext and overrides (flutter/flutter#196931) 2026-11-19 [email protected] Include assigned issues in Android incoming triage link (flutter/flutter#197008) 2026-11-19 [email protected] [Flutter GPU] Record on the UI thread, encode and submit on the raster thread (flutter/flutter#194882) 2026-11-19 [email protected] Add Pixel 7 Pro Impeller benchmarks without fixed-performance mode (flutter/flutter#197010) 2026-11-19 [email protected] Reduce time of uiscene_plugin_lifecycle_test_ios (flutter/flutter#196363) 2026-11-19 [email protected] [native assets] Respect Apple deployment targets (flutter/flutter#194146) 2026-11-19 [email protected] iOS: Represent platform view frames as FlutterPlatformViewFrames (flutter/flutter#196955) 2026-11-19 [email protected] Roll Skia from 0bf961e4ff05 to 2f1436ba8e64 (3 revisions) (flutter/flutter#196999) 2026-11-19 [email protected] [ios] Record OCMReject expectations before the stimulus in FlutterPluginAppLifeCycleDelegateTest (flutter/flutter#193011) 2026-11-19 [email protected] Fix post-monorepo doc rot in docs/infra and dev/bots/README.md (flutter/flutter#193010) 2026-11-19 [email protected] Roll Skia from c3567e170362 to 0bf961e4ff05 (4 revisions) (flutter/flutter#196994) 2026-11-19 [email protected] Close Linux popups when their parent loses focuses (flutter/flutter#196825) 2026-11-19 [email protected] Roll Packages from dca2e58 to 81b7c44 (6 revisions) (flutter/flutter#196992) 2026-11-19 [email protected] Roll Dart SDK from d8d40cf9c21b to 849e17ad3ae6 (1 revision) (flutter/flutter#196986) 2026-11-19 [email protected] Fix RouteObserver didPushNext not firing when routes are pushed synchronously (flutter/flutter#189057) 2026-11-19 [email protected] [Impeller] Reuse render targets on text shadow cache misses (flutter/flutter#194769) 2026-11-19 [email protected] Roll Skia from 81de64af9806 to c3567e170362 (3 revisions) (flutter/flutter#196982) 2026-11-19 [email protected] Reland: "Move macOS desktop builds to ThinLTO" (flutter/flutter#196928) 2026-11-19 [email protected] [Linux] Desynchronize the Wayland subsurface so frames don't redraw the GTK window (flutter/flutter#195287) 2026-11-19 [email protected] Roll Skia from 3dfb69d709c7 to 81de64af9806 (1 revision) (flutter/flutter#196975) 2026-11-19 [email protected] Update `ProxyAnimation.didStartListening` and `ProxyAnimation. didStopListening` to use dart's `Conditional member access` (flutter/flutter#195762) If this roll has caused a breakage, revert this CL and set the roller to dry run mode using the controls here: https://autoroll.skia.org/r/flutter-packages Please CC [email protected],[email protected] on the revert to ensure that a human is aware of the problem. To file a bug in Packages: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: ...
Fixes #193745
Flutter GPU no longer touches Impeller's command buffers, passes, or the render pipeline, shader, and sampler libraries from the UI thread. Passes record plain data and are handed to the raster thread as they end, so encoding overlaps recording the next pass, and a recording keeps what it uses alive until the GPU finishes. Compute pipelines are still created on the calling thread so that their errors stay synchronous, which the mutex-guarded Metal and Vulkan libraries allow, and only compute encoding moved.
The GLES reactor now deletes an object on the thread that released it when that thread has a context, which encoding on the raster thread needs.
Allocation-free recording and replay, and cheaper per-draw binding in Impeller, will follow in separate PRs.
Pre-launch Checklist
///).