Skip to content

iOS / native (rive_native): DeferredConsumer::canAccept() always returns true, blocking the Flutter UI thread in enqueue() when replay falls behind #676

Backlog

Description

@alexflav23

Submission checklist

  • I have confirmed the issue is present in the latest version of the rive Flutter package (rive 0.15.0-dev.5 / rive_native 0.2.0-dev.5)
  • I have searched the documentation and forums and could not find an answer
  • I have searched existing issues and this is not a duplicate

Description

On native threaded deferred targets (iOS, macOS, Windows, Linux — #elif !defined(__EMSCRIPTEN__)), RiveNativeRenderBox.paintTexture() checks renderTexture.canAcceptDeferredFrame before recording a frame so that if the replay worker falls behind, Dart can bank _bankedElapsedSeconds and skip recording without stalling Flutter's UI thread (lib/src/rive_widget.dart:1672-1677).

In native/src/deferred_binding.cpp:350-364, riveDeferredCanAccept() explicitly describes this contract and delegates to DeferredConsumer::canAccept():

// The Dart render driver checks this before recording and skips the whole
// frame when the consumer is behind, pacing without blocking or dropping.
EXPORT int riveDeferredCanAccept(void* sessionPtr)
{
  if (!rive_native::deferredCanAcceptProbe())
  {
    return 0;
  }
  auto it = g_sessionConsumers.find(sessionPtr);
  if (it == g_sessionConsumers.end() || it->second == nullptr)
  {
    return 1;
  }
  return it->second->canAccept() ? 1 : 0;
}

However, in rive_native 0.2.0-dev.5 (native/include/rive_native/deferred_consumer.hpp:222-230), the native DeferredConsumer hardcodes canAccept() to true and instead blocks the calling (Flutter UI) thread inside enqueue():

#elif !defined(__EMSCRIPTEN__)
  bool canAccept() const { return true; } // bound lives in enqueue's wait

  void enqueue(std::function<void()> job)
  {
    {
      std::unique_lock<std::mutex> lock(m_mutex);
      m_notFull.wait(lock, [this] { return m_inFlight < maxQueued(); });
      m_inFlight++;
    }

On iOS (native/src/pls_binding.mm:377), MetalTextureRenderer::deferredFlush() calls job.consumer->enqueue(...) synchronously on the Flutter UI thread. Whenever a heavy scripted GPUCanvas scene (or ProMotion 120 Hz display) produces frames faster than Metal replay can complete them, m_inFlight hits kMaxQueued (2) and m_notFull.wait() hard-blocks the entire Flutter UI thread — freezing gestures, buttons, transitions, and Flutter animations alongside Rive.

Expected behavior: canAccept() returns false once m_inFlight >= maxQueued(), allowing RiveNativeRenderBox.paintTexture()'s existing _bankedElapsedSeconds pacing gate to skip recording until replay catches up, keeping the Flutter UI thread responsive at native 120 Hz even when a complex Rive scene drops below display refresh rate.

Physical iOS --profile Measurements

Measured on a physical iPhone (iPhone19,4, iOS 27.3, 120 Hz ProMotion, Flutter 3.47.8 --profile) rendering a scripted 3D GPUCanvas scene with RiveDeferredPacingDiagnostics, SchedulerBinding.addTimingsCallback, deferredThreadStats(), and a 16 ms Dart event-loop gap probe:

Configuration Flutter UI FPS Rive Paints/s skipsCanAccept Build avg / p95 / max Event-loop max gap Replay (replayUs / frames)
Uncapped 120 Hz (heavy GPU scene, calm) 12 fps 11/s 0/s 10.7 / 66.4 / 68.3 ms 78 ms 69.26 ms
Uncapped 120 Hz (heavy GPU scene, orbiting) 12 fps 10/s 0/s 13.9 / 83.2 / 84.3 ms 90 ms 74.79 ms
Uncapped 120 Hz (heaviest weather pass) 6 fps 6/s 0/s 8.6 / 129.2 / 129.2 ms 163 ms 141.30 ms
Same heavy scene, Dart-side paced to 60 fps 19 fps 11/s 0/s 0.2 / 0.4 / 0.5 ms 22 ms 22.56 ms

Notice two things:

  1. skipsCanAccept is always 0, even while replay lags at 69–141 ms/frame.
  2. As soon as recording stops outrunning m_inFlight == 2, UI-thread buildDuration p95 drops from 83.2–129.2 ms to 0.4–0.5 ms and Dart event-loop stalls vanish (163 ms -> 22 ms).

Suggested Fix

In native/include/rive_native/deferred_consumer.hpp (#elif !defined(__EMSCRIPTEN__)), track m_inFlight as std::atomic<uint32_t> (or inspect it under m_mutex) and have canAccept() report whether the queue has room, while keeping m_notFull.wait() inside enqueue() as a safety backstop for non-gated callers (e.g., flushPendingDestroys):

--- a/native/include/rive_native/deferred_consumer.hpp
+++ b/native/include/rive_native/deferred_consumer.hpp
@@ -219,13 +219,16 @@ public:
   // Native: jobs from all sessions run serially on one shared render
   // thread. Each consumer bounds only its own in flight frames.
 
-  bool canAccept() const { return true; } // bound lives in enqueue's wait
+  bool canAccept() const
+  {
+    return m_inFlight.load(std::memory_order_acquire) < maxQueued();
+  }
 
   void enqueue(std::function<void()> job)
   {
     {
       std::unique_lock<std::mutex> lock(m_mutex);
-      m_notFull.wait(lock, [this] { return m_inFlight < maxQueued(); });
-      m_inFlight++;
+      m_notFull.wait(lock, [this] { return m_inFlight.load(std::memory_order_relaxed) < maxQueued(); });
+      m_inFlight.fetch_add(1, std::memory_order_release);
     }
     DeferredRenderThread::instance().post([this, job = std::move(job)]() {
@@ -237,7 +240,7 @@ public:
       }
       std::lock_guard<std::mutex> lock(m_mutex);
-      m_inFlight--;
+      m_inFlight.fetch_sub(1, std::memory_order_release);
       m_notFull.notify_all();
       m_idle.notify_all();
     });
@@ -247,7 +250,7 @@ public:
   void drain()
   {
     std::unique_lock<std::mutex> lock(m_mutex);
-    m_idle.wait(lock, [this] { return m_inFlight == 0; });
+    m_idle.wait(lock, [this] { return m_inFlight.load(std::memory_order_relaxed) == 0; });
   }
 
   // Jobs capture this consumer's replayer, so drain before dying.
@@ -257,7 +260,7 @@ private:
   std::mutex m_mutex;
   std::condition_variable m_notFull;
   std::condition_variable m_idle;
-  uint32_t m_inFlight = 0;
+  std::atomic<uint32_t> m_inFlight{0};

Reproduction steps / code

  1. Load any .riv file containing a GPU-heavy scripted GPUCanvas scene (e.g., 4× MSAA render target + multi-pass post-processing) in a RiveWidget with Factory.rive on a 120 Hz ProMotion iPhone/iPad in --profile mode.
  2. Mount a lightweight Flutter AnimationController (e.g., RotationTransition) alongside it and enable RiveDeferredPacingDiagnostics.enabled = true.
  3. Observe skipsCanAccept == 0 while FrameTiming.buildDuration spikes to match the GPU frame time (60–200 ms) because MetalTextureRenderer::deferredFlush() blocks on m_notFull.wait().

Rive Flutter package version

rive 0.15.0-dev.4 / rive_native 0.2.0-dev.4 (verified identical in rive_native 0.2.0-dev.5 source)

Flutter version

Flutter 3.47.8 • channel stable • https://github.com/flutter/flutter.git
Framework • revision 737ba8f885 (5 weeks ago) • 2026-10-22 21:37:31 -0700
Engine • hash dfd2e6cb7d319db05e3bf1503f3e2ac60f6288a2 (revision cf636b1dfb)
Tools • Dart 3.13.7 • DevTools 2.60.0

Device

Physical iPhone (iPhone19,4, 120 Hz ProMotion)

OS version

iOS 27.3

Activity

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions