FrameTimingDetector class
Detects jank frames using SchedulerBinding.addTimingsCallback (fast, every frame) and optionally augments with exact VM Timeline phase data.
Runtime Detector — near-zero overhead, always available.
Measurement window. Sleuth reports the frame total duration
(build-to-raster span) from FrameTiming — not vsync delivery cadence
(CADisplayLink-anchored on iOS, Choreographer.doFrame callback on
Android). The two are different metrics: FrameTiming reports how
long the engine took to produce a frame; vsync-anchored metrics report
when the OS displayed it. A frame produced in 3 ms still waits ~13 ms
for the next vsync — FrameTiming reports 3 ms, vsync metrics report
~16 ms. Cross-framework comparison numbers that mix the two read as
large performance deltas where the underlying behaviour is identical.
Lifecycle phase. Each emission stamps
extraTraceArgs.lifecyclePhase: 'startup' | 'steady' based on whether
the issue EMITTED within
DetectorThresholds.startupPhaseWindowSeconds of
StartupTracker.dartEntryMonotonicUs. The classification reads Timeline.now
at emission time — it is emission-time semantics, not event-time.
A startup-phase frame whose addTimingsCallback delivery is delayed
past the window boundary tags as 'steady' even when the underlying
frame timestamp was inside startup. Buffer-aggregated emissions
(sustained_jank over the judged frames, raster-cache trends over
30+ frames) tag from emission-time Timeline.now; a buffer that
straddles the boundary tags as 'steady' once Timeline.now exceeds
the window even if most contributing frames landed inside startup.
This differs from ShaderJankDetector.shaderWarmupContext, which
classifies against per-event shader timestamp. The two tags are
related but NOT aligned at the boundary.
Hot restart resets StartupTracker.dartEntryMonotonicUs (Dart re-initializes
statics; Sleuth.init() re-runs and writes a fresh anchor). Emissions
for the configured window after each hot restart tag as 'startup'
even when the prior session was already past the window.
The tag is observable in capture-mode trace records and audit-gate replay; it is not serialized into saved JSON snapshots.
Route epoch. sustained_jank and jank_detected judge only the
frames that arrived since the last markRouteEpoch, which
SleuthController calls when its scan loop sees a new route, and each
emission carries the route it was computed on
(PerformanceIssue.sourceRoute). The epoch is set on the first scan
tick after navigation, so frames drawn between the push and that tick
(at most one scan interval, including the transition) count toward
the previous route. The first scan after launch is also a route
change, so startup frames never count toward jank. The frame buffer
itself is untouched: verdicts, FPS, cache trends and exports keep the
full window.
- Inheritance
-
- Object
- BaseDetector
- FrameTimingDetector
- Mixed-in types
- Annotations
-
- @experimental
Constructors
- FrameTimingDetector({int? warningThresholdMs, int? criticalThresholdMs, int fpsTarget = 60, int warmupFrameCount = 0, Duration warmupDuration = _defaultWarmupDuration, bool captureMode = false, int startupPhaseWindowSeconds = 5, void onFrameStats(FrameStatsBuffer buffer)?, void onFrame(FrameStats frame)?, String? sourceRouteProvider()?, int? appStartMonotonicUsForTest()?, int ownWorkOverlapUs(int fromUs, int toUs)?})
Properties
- captureMode → bool
-
Capture-mode short-circuit. When
true,_isPastWarmupreturnstrueimmediately regardless of warmupDuration / warmupFrameCount. Set viaSleuthConfig.captureModeand plumbed bySleuthControllerso in-app capture screens can bracket thejank_detected.warningandsustained_jank.criticalaxes inside a short scenario span without waiting out the 3 s warmup. Defaultfalse— never engaged in normal app sessions.final - criticalBudgetUs ↔ int
-
Severe-jank budget in microseconds (2x warningBudgetUs).
getter/setter pair
- criticalThresholdMs → int
-
criticalBudgetUs in whole milliseconds.
no setter
- description → String
-
Short description of what this detector checks.
finalinherited
- fpsTarget → int
-
final
- frameBuffer → FrameStatsBuffer
-
no setter
- hashCode → int
-
The hash code for this object.
no setterinherited
-
highlights
→ List<
WidgetHighlight> -
Highlight candidates collected during the last scan.
Empty for detectors that don't produce visual highlights.
no setterinherited
- isEnabled ↔ bool
-
Whether this detector is currently active.
getter/setter pairoverride
-
issues
→ List<
PerformanceIssue> -
Current list of detected issues. Reset each analysis cycle.
no setteroverride
- key → String?
-
Stable identifier for config-driven gating of custom detectors.
finalinherited
- lifecycle → DetectorLifecycle
-
Lifecycle classification determining data source requirements.
finalinherited
- measuredCadenceHz → double?
-
Vsync cadence estimated from the 10th percentile of recent
vsyncStartdeltas, or null until 30 valid deltas have been seen.no setter - name → String
-
Human-readable name of this detector (e.g., "Frame Timing").
finalinherited
- onFrame → void Function(FrameStats frame)?
-
Called once per frame, right after the frame enters the buffer and
before onFrameStats. A batch of N timings yields N calls in
presentation order.
SleuthControlleruses it to fan frames out to BaseDetector.processFrame.final - onFrameStats → void Function(FrameStatsBuffer buffer)?
-
final
- requiresTreeScan → bool
-
Whether this detector scans the widget/render tree.
no setterinherited
- requiresVm → bool
-
Whether this detector needs VM service data to function.
DetectorLifecycle.runtime detectors benefit from VM data but don't require it.
no setterinherited
- runtimeType → Type
-
A representation of the runtime type of the object.
no setterinherited
- startupPhaseWindowSeconds → int
-
Window in seconds after Dart entry within which emissions stamp
extraTraceArgs.lifecyclePhase: 'startup'; emissions outside the window stamp'steady'. Default mirrors DetectorThresholds.startupPhaseWindowSeconds — the canonical source for users wiring viaSleuthConfig. See class dartdoc for buffer-spanning behaviour.final - type → DetectorType
-
The detector type identifier used for configuration.
finalinherited
- validationMetadata → DetectorMetadata
-
Metadata for this detector. Must be non-null on shipping detectors —
the audit test gates this.
no setteroverride
- validCadenceSampleCount → int
-
Number of vsync deltas currently held by the cadence estimator.
no setter
- vmConnected ← bool
-
Update VM connectivity state.
no getterinherited
- warmupDuration → Duration
-
Wall-clock gate suppressing jank evaluation during app warmup
(shader compilation, route init, Dart VM JIT). Refresh-rate
independent. Measured against the timestamp of the first frame the
detector observes, not app-launch time.
final
- warmupFrameCount → int
-
Legacy frame-count gate (AND-combined with warmupDuration).
final
- warningBudgetUs ↔ int
-
Per-frame budget in microseconds. A frame whose effective duration
exceeds it is jank. Defaults to
1e6 / fpsTarget(16667 at 60);SleuthControllermoves it to the resolved budget via updateFrameBudget.getter/setter pair - warningThresholdMs → int
-
warningBudgetUs in whole milliseconds.
no setter
Methods
-
addFrameForTest(
FrameStats stats) → void - Add a synthetic frame for testing — feeds directly into the buffer and triggers jank evaluation without requiring SchedulerBinding.
-
afterElement(
Element element) → void -
Called after an element's children have all been visited.
inherited
-
checkElement(
Element element) → void -
Check a single element during the unified tree walk.
inherited
-
dispose(
) → void -
Dispose of any resources held by this detector.
override
-
evaluateNow(
) → void -
Triggers issue evaluation using whatever data has been staged.
inherited
-
finalizeScan(
) → void -
Finalise the scan: process accumulated data and create issues.
inherited
-
handleTimingsForTest(
List< FrameTiming> timings) → void -
Test-only bridge into the real
addTimingsCallbackpipeline so callers can feedList<FrameTiming>batches through the exact code path the engine uses. Validates that batched delivery (one callback with many frames) no longer collapses the warmup duration gate. -
markRouteEpoch(
) → void -
Starts a new jank window at the current frame and removes the
sustained_jank/jank_detectedissues computed on the previous window. Frames already in the buffer stay there (FPS, verdicts and exports still read them) but no longer count toward jank. Warmup, lifecycle phase and cache-trend state are untouched; reset is the full clear. -
noSuchMethod(
Invocation invocation) → dynamic -
Invoked when a nonexistent method or property is accessed.
inherited
-
notifyWalkCompleted(
) → void -
Called when the tree walk completed without exceptions.
inherited
-
prepareScan(
BuildContext context) → void -
Prepare for a new scan cycle. Called once before the unified tree walk.
inherited
-
processFrame(
FrameStats frame) → void -
Process one presented frame from
FrameTiming.inherited -
processTimelineData(
ParsedTimelineData data) → void -
Process VM timeline data.
inherited
-
refreshOwnStartDelays(
) → int - Re-reads Sleuth's own share of each buffered frame's start delay and re-judges jank when any changed. A VM stall that a later timeline poll measures can cover a frame read before it. Returns how many frames changed.
-
reset(
) → void -
Capture-mode reset hook. Clears all per-leg state — buffer, ephemeral
_issues, warmup anchors, cache-trend counters, the route epoch, the vsync cadence estimate — so back-to-back scenario legs cannot leak frames or counters from prior runs. -
scanTree(
BuildContext context) → void -
Scan the widget/render tree for issues.
inherited
-
start(
) → void -
toString(
) → String -
A string representation of this object.
inherited
-
updateDebugSnapshot(
DebugSnapshot snapshot) → void -
Called with debug callback data when available.
inherited
-
updateFrameBudget(
int budgetUs) → void -
Applies a resolved frame budget. No-op in captureMode (bracket
recordings use the fixed
fpsTargetbudget), when explicit thresholds were passed to the constructor, or for a non-positivebudgetUs. -
updateTimelineData(
ParsedTimelineData data) → void - Call this to update with latest VM Timeline data.
Operators
-
operator ==(
Object other) → bool -
The equality operator.
inherited
Constants
- jankPercentThreshold → const int
-
jank_detectedfires when more than this percentage of the judged frames missed their deadline. - jankWindow → const Duration
- How far back, behind the newest frame's vsync, jank looks. On a quiet screen Sleuth's own scans draw about one frame a second, so without a time limit janky frames took 4 to 8 minutes to leave the 240-frame buffer and the card stayed that long after the jank stopped.
- minJankFrameCount → const int
-
Late frames
jank_detectedneeds besides the percentage. A quiet screen draws only Sleuth's own scan frames, about one a second, so one late frame among the ten in jankWindow already reads 10 % and two read 20 %. On an animated screen the percentage needs many more. - minJankSampleFrames → const int
- Judged frames needed before jank is evaluated.
- sustainedSevereFrameCount → const int
-
sustained_jankfires at this many severe frames (see FrameStats.severeJankBudgetMultiplier).