Skip to content

fix(seek): recover slow-source VOD seeks without reverting the clock - #216

Merged
superuser404notfound merged 1 commit into
superuser404notfound:mainfrom
brandomoore:fix/slow-source-seek-recovery
Jul 25, 2026
Merged

superuser404notfound merged 1 commit into
superuser404notfound:mainfrom
brandomoore:fix/slow-source-seek-recovery

Conversation

@brandomoore

@brandomoore brandomoore commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

Summary

On a high-latency source (Dolby Vision over SMB) a VOD seek can miss its deadline while the producer is still genuinely serving the target. Recovery then reverted the clock to the pre-seek position, so the scrubber visibly jumps back and the session parks flapping paused↔playing for ~40 s. This makes recovery reconcile forward to the target instead.

What changed

Four related changes on the native VOD seek-deadline path:

  1. Extend the deadline while progress is real. AVPlayer buffers the target region into media that is not contiguous with the pinned old playhead, so bufferedEnd structurally reads 0 there and cannot tell "slow but working" from "wedged". A new NativeAVPlayerHost.bufferedSecondsAtTarget(_:) measures what the producer has actually served at the target, referencing no playhead at all — deliberately, because bufferedEnd/avPlayerBufferAheadSeconds() are measured from item.currentTime() while the loop's frozen position is renderedTime, and those two legitimately diverge during a buffering landing (Queued seek bursts: engine clock adopts each target immediately while the player rebuilds — 10-30s clock/presentation divergence; subtitle cues pace with the clock over a stale frame #123). An extension additionally requires that figure to be growing between windows (presence alone cannot distinguish a producer still filling from one that served 4 s and died) and is vetoed when the target is beyond producer coverage (AE#141).
  2. Hold the clock at the target on fallthrough. Rather than reverting, keep the clock at the target (same UX contract as the extend branch: scrubber parked at target + spinner), re-anchor the producer to the target once, re-issue the seek so AVPlayer abandons the old-position buffer, and wait a bounded number of windows — reconciling forward, never back, and never flapping the transport. A fully spent budget parks the spinner at the target instead of reverting; the $renderedTime sink settles the clock and clears the seek state when the producer finally serves it.
  3. Accept a forward overshoot as a landing. A zero-tolerance seek lands at the target and a playing item then advances, so a forward seek can render past it. Reading that as "still pending" triggered a backward-yank re-seek on an already-playing item. The pinned pre-seek playhead sits far on the opposite side, so a directional check cannot mistake it for a landing.
  4. Edge-detect the landing on the extend/wait path at AVPlayer's own ~100 ms observer cadence, so the host's loading state clears when playback actually resumes rather than lagging it by up to a full window (which left a spinner over already-playing video). The poll reads the published renderedTime rather than avPlayer.currentTime() (no synchronous XPC per tick, LiveTelemetrySampler: synchronous AVFoundation IPC on the main actor at 1 Hz → fatal app hangs on the native path #134) and bounds itself with DispatchTime, not wall clock. It requires position evidence and deliberately does not accept "the seek completion ran": reengageStalledConsumer calls cancelPendingSeeks() without bumping the seek generation, so a cancelled seek would otherwise report as a landing and silently retire the recovery target (Loopback-HLS: a single backward seek on heavy 4K can wedge the segment producer (video stalls, audio continues -> A/V desync) #93).

Bounded throughout: at most 4 deadline extensions, one re-anchor, and 4 post-re-anchor waits, then a terminal return — worst case ~10 loop iterations, so await seek(to:) stays suspended at most ~44 s (documented on nativeSeekExtensionBudgetSeconds). Every continuing branch increments a monotone counter that is never reset, and every await is followed by a load/seek generation re-check before any published state is mutated. The terminal give-up holds the clock at the target but clears the programmatic-seek gate and reconciles as starved, so a source that never serves the target reports .rebuffering/.stalled instead of parking in .seeking forever — the permanent-spinner class this PR exists to remove must not simply relocate to the give-up.

Scoped to the native VOD deadline branch; live and software/audio host paths are untouched. Preserves #65 (true-wedge bound), #122 (paused-seek transport intent) and #123 (buffering-toward-target sourceTime hold).

Test plan

  • Device / OS: Apple TV 4K (3rd generation, AppleTV14,1), tvOS 27.0.
  • Source media (container / video codec + profile / audio / HDR-DV): MKV, HEVC Dolby Vision Profile 7, E-AC-3 JOC audio, streamed over SMB from a NAS — i.e. deliberately slow, high-latency serving, which is what makes the deadline miss reproducible. Also exercised against fast local HTTP to confirm no regression on sources that land in budget.
  • Result: Large backward seeks (late-film → ~10 min) and far-forward seeks into unbuffered territory now land without the scrubber snapping back to the pre-seek position, and without the ~40 s paused↔playing flap. Seeks that land in budget on a fast source are unchanged (no extra extensions, no re-anchor). The spinner clears as playback resumes rather than a window later. Rebased onto 5.22.0; full suite green (1054 tests) plus iOS/tvOS simulator builds, including RecoverySeekTargetTests coverage for the growth/coverage/budget rules of the extension decision, overshoot acceptance and the recovery anchor.

Checklist

  • CHANGELOG.md updated
  • Commit messages follow Conventional Commits (feat(...), fix(...), chore(...))
  • The fix lives in the engine, not in a host-side workaround
  • Public API changes are intentional and documented (no public API change here)

@brandomoore
brandomoore force-pushed the fix/slow-source-seek-recovery branch 2 times, most recently from 1e18ee6 to d7bd00e Compare July 25, 2026 08:23
On a high-latency source (Dolby Vision over SMB, HLS re-mux path) a VOD seek can
miss its deadline while the producer is still genuinely serving the target. The
deadline recovery reverted the reported clock to the frozen pre-seek position and
reconciled the transport, which on device is the reported failure: the scrubber
visibly jumps back to the old spot and the session parks flapping paused<->playing
for ~40s while the orphaned old-position segment drains.

Four parts:

1. Extend the deadline while progress is real. AVPlayer buffers the target region
   into an island that is NOT contiguous with the pinned old playhead, so the
   old-playhead buffer metric (bufferedEnd) structurally reads 0 there and cannot
   distinguish "slow but working" from "wedged". Measuring the disjoint forward
   island (total forward ahead minus the contiguous portion) can, so a filling
   island extends the deadline instead of triggering a teardown.

2. Hold the clock at the target on fallthrough. Rather than reverting, keep the
   clock at the target (same UX contract as the extend branch: scrubber parked at
   target + spinner), re-anchor the producer to the target once, re-issue the seek
   so AVPlayer abandons the old-position buffer, and wait a bounded number of
   windows -- reconciling FORWARD to the target, never back, and never flapping the
   transport. Budget exhausted while still buffering parks the spinner at the target
   instead of reverting; the $renderedTime sink then settles the clock and clears the
   seek state when the producer finally serves it.

3. Accept a forward overshoot as a landing. A zero-tolerance seek lands AT the
   target and a playing item then advances, so a forward seek can render past it.
   Reading that as "still pending" triggered a backward-yank re-seek on an
   already-playing item. The pinned pre-seek playhead sits far on the opposite side,
   so a directional check cannot mistake it for a landing.

4. Edge-detect the landing on the extend/wait path at AVPlayer's own ~100ms observer
   cadence, so the host's loading state clears when playback actually resumes instead
   of lagging it by up to a full window (that left a spinner over playing video).

Bounded throughout: at most 4 deadline extensions, one re-anchor, and 4 post-
re-anchor waits, then a terminal return -- worst case ~10 loop iterations. Every
continuing branch increments a monotone counter that is never reset, and every
await is followed by a load/seek generation re-check before publishing state.

Scoped to the native VOD deadline branch; live and software/audio host paths are
untouched. Preserves superuser404notfound#65 (true-wedge bound), superuser404notfound#122 (paused-seek transport intent)
and superuser404notfound#123 (buffering-toward-target sourceTime hold).
@superuser404notfound
superuser404notfound force-pushed the fix/slow-source-seek-recovery branch from d7bd00e to a4e049b Compare July 25, 2026 11:20
@superuser404notfound
superuser404notfound merged commit 10c5ea0 into superuser404notfound:main Jul 25, 2026
3 checks passed
superuser404notfound pushed a commit that referenced this pull request Jul 25, 2026
Follow-up to #216 on three edges the new wait windows opened.

1. The $renderedTime sink can finalize the same seek underneath the deadline
   loop, and its landing predicate is looser than the loop's: pendingSeekLanded
   accepts anything within +-5s of the target (symmetric), seekLandedAtTarget
   wants +-0.75s on the near side. A landing 3s short of a forward target
   therefore ran finalizeLateRecoverySeekLanding (clearing the seek gate,
   reconciling the transport) while the loop still read "pending" and would go
   on to re-anchor the producer and re-seek backward onto an item already
   reported as playing -- the yank the overshoot rule exists to prevent,
   reintroduced through the back door. Guard on programmaticSeekInFlight, the
   authoritative "this seek is still ours" latch.

2. bufferedSecondsAtTarget's 30s window only keeps a FAR backward seek clear of
   the abandoned playhead's forward buffer. A backward seek of less than the
   window leaves that buffer inside the measurement range, where a still-full
   old buffer reads as "the producer is serving the target" and earns an
   extension it has not earned. The deadline loop now passes the frozen playhead
   as an exclusion bound on backward seeks. Extracted the window arithmetic into
   a pure bufferedSecondsInWindow so the case is testable without an item.

3. awaitPendingSeekLanding sleeps on the caller's task, so a cancelled task
   makes every remaining window return false in microseconds: the loop burned
   its whole budget in one runloop turn and still restarted the producer on the
   way through. (host.seek(to:deadlineSeconds:) runs its deadline on a detached
   task, which is why this could not happen before the wait windows existed.)
   Terminate on the give-up contract instead.

Full suite green (1066 tests) plus iOS/tvOS simulator builds.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01QYhPvBB1sLCYoZNasEXFeB
superuser404notfound pushed a commit that referenced this pull request Jul 25, 2026
House style is commas, colons or parentheses. The 11 the seek-recovery
change introduced were the only ones in either file.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01QYhPvBB1sLCYoZNasEXFeB
@superuser404notfound

Copy link
Copy Markdown
Owner

Merged as 10c5ea0. Thank you for this one, it is a genuinely hard piece of reasoning and the writeup carried it: the observation that bufferedEnd is structurally blind at the target because it spans a playhead that a pending zero-tolerance seek pins in place is the part that made the whole failure make sense. Measuring at the target instead, and requiring the figure to grow rather than merely exist, is the right shape. So is holding the clock forward instead of reverting it, and refusing to let the give-up quietly relocate the permanent spinner it exists to remove.

Rebased onto 5.23.1 (the only conflict was the CHANGELOG entry landing next to the new release sections) and followed up with three bits of hardening in 46d50bc, all on edges the new wait windows opened rather than anything wrong in the original reasoning:

  1. The loop could be finalized underneath. The $renderedTime sink and the loop's poll use different landing predicates: pendingSeekLanded accepts anything within ±5 s of the target (symmetric), seekLandedAtTarget wants ±0.75 s on the near side. A landing a few seconds short of a forward target therefore ran your new finalizeLateRecoverySeekLanding (clearing the seek gate, reconciling the transport) while the loop still read "pending" and went on to re-anchor the producer and re-issue a backward seek onto an item already reported as playing. That is the yank your overshoot rule removes, coming back through a different door. The loop now guards on programmaticSeekInFlight, which is the authoritative "this seek is still ours" latch: set before the first host seek, cleared only by a finalize or stopInternal.

  2. bufferedSecondsAtTarget's window only protects a far backward seek. A backward seek of less than the 30 s window leaves the abandoned playhead's own forward buffer sitting inside [target - tolerance, target + window], where a still-full old buffer reads as "the producer is serving the target" and earns an extension nothing was served for. The deadline loop now passes the frozen playhead as an exclusion bound on backward seeks only. Worth noting the doc comment claimed the window already ruled this out, which is what sent me looking. The window arithmetic moved into a pure bufferedSecondsInWindow so the case is testable without an AVPlayerItem.

  3. Cancellation. awaitPendingSeekLanding sleeps on the caller's task, so a cancelled task makes every remaining window return false in microseconds: the loop burned its entire budget inside one runloop turn and still restarted the producer on the way through. host.seek(to:deadlineSeconds:) runs its deadline on a detached task, which is why this could not happen before the wait windows existed. It now terminates on the give-up contract instead.

Also dropped the em-dashes from the new comments (f88cd48), house style here is commas, colons or parentheses.

Full suite green at 1066 tests plus both simulator builds. It will go out in the next release.

@superuser404notfound

Copy link
Copy Markdown
Owner

Shipped in 5.23.2. Both consumers are pinned to it and building clean.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants