Skip to content

Clock/frame divergence accumulates under sustained seek rate (#35-class, #38 retest follow-up) #49

Closed

Description

@superuser404notfound

Summary

Split out from the #38 retest (thanks @rrgomes). On that retest the #37 seek-bounce fix was confirmed on real hardware, but a separate, #35-class issue surfaced and is tracked here so #35 (released, closed, its clock re-fold intentional) and the #38 signal work stay clean.

Under a sustained high seek rate, the reported clock (currentTime) decouples from the actually decoded frame: the frame runs ahead of the clock, and the gap accumulates with seek count rather than reconciling.

Reported observations (2-Apple-TV synchronized-playback setup, one device scrubs the native AVKit transport bar, the other follows via programmatic seeks):

Investigation so far (off-device)

The native loopback-HLS clock is currentTime = AVPlayer clock + playlistShiftSeconds, where playlistShiftSeconds folds the active producer's videoShiftPts back onto source PTS. A "frame ahead of clock" gap means the published fold trails what is actually on screen.

To chase this without a device, aetherctl seektest gained:

  • AetherEngine.activeProducerShiftSeconds: a diagnostics-only ground truth for the native-path shift, read straight off the active producer rather than the host-folded value.
  • A frameAhead = activeProducerShiftSeconds - playlistShiftSeconds metric sampled across the burst and settle (peak, early-vs-late-third accumulation, post-settle residual).
  • --slow-ms, --stall-every, --stall-ms: drive the source through a throttled custom IOReader. Per-read latency alone never overlaps restarts (the pump checks shouldStop between reads). A multi-second stall on a single read does, pushing a restarting producer past the 5 s waitForFinish and firing the abandon path (old producer's in-flight read consumes the post-seek packet, new producer starts a GOP late).

Result across clean, slow, aggressive, heavy-throttle, and stall-injection runs (the last firing the abandon path 13 times, maxWedge 6.66 s): frameAhead stays 0.00 throughout. The producer-to-host shift sync is tight and the muxer's per-segment tfdt forcing keeps the fold self-consistent per restart, so the abandon path reproduces but does not by itself open a currentTime-vs-frame gap in the headless macOS harness.

This is consistent with #35 only reproducing against a real slow source / on-device AVKit HLS, whose buffering and seek tuning differ from headless macOS AVPlayer.

The instrumentation is on branch diag/issue38-clock-frame-divergence.

What would help reproduce it

@rrgomes, the offer of sync logs and a minimal repro would be very useful. Specifically:

  1. The source characteristics for the file where the ~63 s gap built up: container, video codec, GOP/keyframe cadence, and whether it is a remux/CMAF vs a single MKV. The headless harness only shows zero divergence on keyframe-aligned plans; a source whose keyframe index is sparse enough to fall back to the uniform segment plan (or whose seeks land imprecisely) is the prime suspect for a shift that drifts and does not reconcile.
  2. A sync log capturing currentTime vs the intended seek targets across the burst on the follower, so the per-seek residual is visible.

Reopen-or-new was the open question on #38; opening this as new to keep the failure modes separated.

Activity

  1. rrgomes commented on Jun 17, 2026

    @rrgomes
    Contributor

    Thanks for splitting this out, and for the detailed harness writeup.

    1. Source characteristics

    The file loaded for the 2-device scrub where the gap built up:

    • Single MKV (Matroska), not CMAF/fragmented. 1.74 GB, 31.8 Mbps avg.
    • Video: H.264 [email protected], 1920×1080, 23.976 fps (24000/1001), yuv420p, SDR (untagged color).
    • Audio: FLAC, 48 kHz, stereo (this is the audio that desynced/dropped out).
    • One embedded PGS subtitle track. Duration 7:17.8 (437.8 s).
    • Keyframe cadence: dense. 591 keyframes over 437 s — mean GOP 0.74 s, max 0.835 s (≈ a 20-frame keyint at 23.976 fps), min 0.041 s (scene-cut insertions). The Cues index resolves fine: programmatic seeks land sub-second in our logs, never the multi-second prewarm path.

    So this isn't the sparse-index / uniform-segment-plan case — the divergence built up on a keyframe-rich, keyframe-aligned source. That seems to point away from the segment-plan suspect and toward the on-device AVKit HLS seek/buffer behavior under a high seek rate (the gap vs your headless macOS harness).

    2. Setup + sync log, with one honest caveat

    First a correction to the original framing: in the burst where the gap blew out, both devices were scrubbing the native transport bar at the same time (a dueling scrub) while the follower also issued the programmatic catch-up seeks — so the aggregate seek rate across the loopback producer was very high and bidirectional, not one-scrubs / one-follows.

    The caveat: our host logs the engine's reported currentTime (off clock.$currentTime) plus our own seek targets/verdicts, but not the decoded-frame PTS. The "frame ~63 s ahead of the clock" was a concurrent on-screen visual observation, not a logged number — so the trace below shows the reported-clock trajectory and our sync verdicts, not the clock-vs-frame gap directly.

    Follower, dueling-scrub burst (positions in ms):

    09:51:01.6  native scrub → broadcast local seek 215675        (follower scrubs to 3:35)
    09:51:03.1  applyRemoteSeek to=288542 (local was 215675)       (peer's scrub to 4:48 arrives)
    09:51:04.6  drift: local=289300 remote=288542 drift=752  → ok
    09:51:07.6  drift: local=292300 remote=215675 drift=76619 → force-resync   (peers 76 s apart)
    09:51:16.1  native scrub → broadcast local seek 202642
    09:51:18.6  native scrub → broadcast local seek 82642
    09:51:28.3  native scrub → broadcast local seek 180974
    09:51:29.7  applyRemoteSeek to=91450 (local was 221100)
    09:51:38.0  drift: local=94100 remote=189000 drift=94900 → force-resync    (peers 95 s apart)
    

    Two things the trace does show that may help:

    • Under the dueling scrub the two reported positions spread to 76–95 s and we force-resync (expected, since both scrubbed to different spots).
    • Separately, after a programmatic seek the follower's clock holds at the target and the player then stalls 3+ s before resuming (loopback rebuffer) while the authority keeps advancing — e.g.:
    09:42:22.4  applyRemoteSeek to=147703 (local was 144400)
    09:42:25.4  local=147702 drift=3004 → skip (settle)
    09:42:28.4  local=147702 drift=6004 → skip (settle)        [clock frozen 3+ s post-seek]
    09:42:31.4  local=147702 remote=156700 drift=9003 → gentle-resync (stalled 1/3)
    09:42:49.5  local=165705 drift=9101 → free-run (player stalled ×3)
    

    Under a sustained seek cadence these post-seek stalls stack up.

    3. The measurement we can't get from our side — and an offer

    Since we don't log decoded-frame PTS, we can't produce the on-device equivalent of your frameAhead = activeProducerShiftSeconds − playlistShiftSeconds. If you'd expose activeProducerShiftSeconds (and/or the folded frameAhead) as a published or debug-readable value in a release or a branch we can pin, we'll log currentTime vs that on-device across the dueling-scrub burst and hand you the real on-device frameAhead trace — the exact thing your headless harness reads 0.00 for. That seems like the fastest way to bridge headless-vs-device.

    Repro on our side: 2 Apple TVs, this keyframe-dense single MKV streamed over Plex HTTP (native loopback-HLS path), both scrubbing the AVKit bar bidirectionally at a high rate while the follower also issues ~1 programmatic seek/s. Happy to share more log or run a diagnostic build.

  2. rrgomes commented on Jun 18, 2026

    @rrgomes
    Contributor

    On-device repro of the seek-induced wedge (engine-native DV-P7)

    Captured on Apple TV 4K (3rd gen), AetherEngine 3.10.0. Content: single-MKV HEVC DV-P7, direct play (engine-native loopback HLS → AVPlayer). Repro: a rapid D-pad skip-ahead burst — 7 skips, 24s → 84s in ~2.5s — then normal playback resumes and runs cleanly for ~10s, then aborts.

    At the moment of failure (host-side snapshot of the engine's currentAVPlayer):

    • state = loadFailed("The requested URL was not found on this server.")
    • AVPlayer: timeControlStatus = playing, rate = 1.0, clock at 94.9s (advanced normally from the 84.4s seek target), loadedTimeRanges = [84.2–100.6], seekableTimeRanges = [0–7080].

    So the AVPlayer was healthy and playing with ~16s buffered when the pipeline surfaced a 404. It reads like a loopback-HLS playlist-refresh or upcoming-segment request whose session was invalidated by the seek burst ~10s earlier — distinct from the clock/frame divergence described in this issue.

    Is this the same root cause as #49, or a separate issue? And is there an on-device signal (you mentioned activeProducerShiftSeconds / frameAhead) you'd want us to capture next? We have the device repro.

  3. superuser404notfound commented on Jun 18, 2026

    @superuser404notfound
    OwnerAuthor

    Thanks, this is exactly the data that moves it forward, and the honest caveat about not logging decoded-frame PTS is appreciated.

    Your source rules out the suspect I was chasing

    Keyframe-dense (mean GOP 0.74 s), Cues resolve, seeks land sub-second: that is the keyframe-aligned plan path, not the sparse-index / uniform-segment-plan fallback. So the "shift drifts because seek landings are imprecise" theory is out. Combined with the dueling-bidirectional-scrub correction, the prime suspect is now the on-device AVKit HLS seek/buffer behavior under a high seek rate, which is precisely the gap between your hardware and my headless macOS harness (it reads frameAhead 0.00 even with the abandon path firing 13 times).

    Shipped the readout you offered to log

    main (504b37b, pinnable by SHA) now exposes two diagnostics-only accessors on AetherEngine:

    • activeProducerShiftSeconds (Double): the native producer's true shift, read synchronously off the active HLSVideoEngine rather than the host-folded playlistShiftSeconds. The two paths differ because the host value updates across an async main-actor hop (the onPlaylistShiftChanged relay) plus a seam-history resolution.
    • frameAhead (Double): the folded delta activeProducerShiftSeconds - playlistShiftSeconds. Positive means the decoded frame leads the published currentTime by that many seconds. ~0 when the fold keeps up; a value that grows with seek count and does not reconcile is this issue.

    Both are read-on-demand (poll them, no publisher needed) and 0 on the SW / audio paths.

    What would nail it

    1. Log currentTime vs frameAhead (and optionally activeProducerShiftSeconds and playlistShiftSeconds raw) on the follower across the dueling-scrub burst. That is the on-device equivalent of the harness metric and tells us directly whether the fold is going stale or whether the frame really is running ahead of a correctly-folded clock.

    2. Separately, the post-seek stall in your trace is its own signal worth quantifying:

      09:42:25.4  local=147702 drift=3004 -> skip (settle)
      09:42:28.4  local=147702 drift=6004 -> skip (settle)   [clock frozen 3+ s]
      

      The clock freezing at the seek target for 3+ s is a loopback rebuffer after the seek, and under a sustained cadence these stack. If you can capture how often that 3+ s freeze fires per burst and whether frameAhead moves during the freeze, that separates "rebuffer stall" from "fold divergence" cleanly, they may be two different things hiding in the same burst.

    Pin 504b37b whenever convenient and send whatever trace you can capture. Happy to add more readouts if a missing value would help.

  4. superuser404notfound commented on Jun 18, 2026

    @superuser404notfound
    OwnerAuthor

    On your second comment (the on-device DV-P7 404 wedge): our replies crossed, that one is a different failure mode from this issue, so I split it into #50.

    Short version: #49 is the clock/frame fold divergence (non-fatal). The 404 loadFailed after the skip burst is a loopback-HLS forward-request wedge, #35-family but still open on 3.10.0. Your snapshot makes the distinction clean: with loadedTimeRanges=[84.2-100.6] and the clock at 94.9 being served fine, the 404 is a forward segment (past 100.6) or a media.m3u8 LL-HLS blocking reload, not a pruned old segment.

    What pins #50 needs no new build, the engine already logs the cause. From an on-device EngineLog capture across the burst to failure (categories .hlsServer + .session), the two load-bearing lines are:

    • The 404 reason line: ... reason=segment[N] empty (segmentCount=M). N vs M tells us forward-unproduced (N >= M, my prime suspect: an abandoned producer stopped extending the buffer) vs pruned (N < M).
    • Any restart at idx=...: old producer didn't exit within 5s, abandoning it line plus the surrounding restart/coalesce sequence.

    Let's keep the 404 on #50 and the frameAhead trace (pin 504b37b) here on #49. Both repros are gold, thank you.

  5. rrgomes commented on Jun 18, 2026

    @rrgomes
    Contributor

    On-device #49 trace (pinned 504b37b, ALIHL native loopback-HLS, 2-device dueling scrub): frameAhead reads 0.000 throughout — but the published clock and the AVPlayer clock diverge up to 180 s

    Captured 646 samples (516 during the scrub burst, 130 steady-state heartbeats) on Apple TV 4K hardware, polling your two accessors at 4 Hz while reproducing the visible divergence (subtitles + UI racing ahead of the picture). One honest caveat as before: we log the engine's published clock.currentTime and currentAVPlayer.currentTime(), not decoded-frame PTS.

    Your frameAhead accessor reads 0.000 on-device, the whole time

    Every one of the 646 samples — including all 516 in the aggressive dueling-scrub burst — reads:

    frameAhead=0.000  activeProducerShiftSeconds=0.000  playlistShiftSeconds=0.000
    

    So on real hardware, on the native H.264 loopback path, both the producer shift and the host-folded shift sit at 0 even while the divergence is plainly visible on screen. Your headless harness reads 0.00, and our on-device host poll agrees — the shift-fold metric doesn't see this divergence.

    Where it does show up: published clock vs the AVPlayer's own clock

    The divergence is large and unmistakable in clock.currentTime (t) vs currentAVPlayer.currentTime() (avpClock) — up to 180 s, in 153 of the 516 burst samples — and it's tightly gated on timeControlStatus:

    # steady playback — the two clocks are locked to ~70 ms:
    t=91.000  avpClock=91.019  tcs=2(playing)   frameAhead=0.000
    t=91.200  avpClock=91.270  tcs=2(playing)   frameAhead=0.000
    
    # dueling-scrub burst — published clock jumps to the seek target while the
    # AVPlayer stalls rebuffering (tcs=1, waitingToPlayAtSpecifiedRate); gap blows out:
    t=290.100 avpClock=110.100 tcs=1(rebuffer)  frameAhead=0.000   Δ=+180s
    t=120.100 avpClock=60.100  tcs=1(rebuffer)  frameAhead=0.000   Δ=+60s
    t=110.100 avpClock=140.100 tcs=1(rebuffer)  frameAhead=0.000   Δ=−30s   (AVPlayer ahead — opposite scrub direction)
    
    # playback resumes — the two re-lock to ~70 ms:
    t=90.100  avpClock=90.100  tcs=2(playing)   frameAhead=0.000
    t=90.200  avpClock=90.270  tcs=2(playing)   frameAhead=0.000
    

    The pattern across the whole burst: while tcs=2 (playing) the two clocks track to ~70 ms; the moment a seek lands and the AVPlayer enters tcs=1 rebuffer, the published clock.currentTime jumps to (or past) the seek target while the AVPlayer is still parked at its last-rendered position, opening gaps of tens-to-180 s. It's bidirectional — the published clock follows the seek target, not the AVPlayer — and it reconciles to ~70 ms once playback resumes. (Max gap seen while tcs=2 was a transient ~100 s right at the resume boundary, before re-lock.)

    Read

    This isn't a producer-shift-vs-host-shift fold (that's pinned at 0). It's the engine's published PlaybackClock decoupling from the underlying AVPlayer's actual position during post-seek rebuffer. Since subtitles, UI, and our WT sync all ride the published clock while the visible frame rides the AVPlayer, that decoupling is exactly the on-screen "subtitles/frame ahead of the picture" symptom — and it explains why your frameAhead accessor can't see it (the producer shift is fine; it's the published clock that runs ahead of where AVPlayer actually is).

    Happy to send the full 646-line trace, or instrument a different signal if clock.currentTime vs currentAVPlayer.currentTime() isn't the comparison you'd want for the fold. Is the published clock meant to hold at the AVPlayer's position through a rebuffer, or is frameAhead simply the wrong accessor for this failure mode?

  6. rrgomes commented on Jun 18, 2026

    @rrgomes
    Contributor

    Full 646-line trace (as offered above), self-documented with the field key at the top: https://gist.github.com/rrgomes/d482f64df016c69d2096fced793681ef

  7. superuser404notfound commented on Jun 18, 2026

    @superuser404notfound
    OwnerAuthor

    frameAhead is the wrong accessor for this, and your trace proves it. Thank you, this nails the mechanism. Fixed on main (15dca96, pinnable by SHA).

    Your 646-sample capture closes the original hypothesis: frameAhead (the producer-shift fold) reads 0.000 on-device exactly as it does in the headless harness, so the producer-to-host shift is tight and the "frame runs ahead because the shift drifts" theory is dead. The divergence you measured (clock.currentTime vs the AVPlayer's own clock) is a different mechanism, and it's in the seek path, not the fold.

    What's happening

    AetherEngine.seek(to:) publishes the seek target to currentTime up front, before the AVPlayer seek physically lands. That's the #37 anti-bounce fix: snap the scrub bar to the drop point and suppress the periodic time observer (via seekInFlight) so it can't bounce the clock back through the pre-seek position. The design assumes the seek lands shortly and the observer re-syncs on resume.

    Under your sustained dueling-scrub burst that assumption breaks: the seeks keep superseding each other (a superseded completion deliberately does not clear seekInFlight), and the AVPlayer stays in tcs=1 rebuffer and never resumes to let the observer re-sync. So the published clock holds the latest target while the picture stays parked at the AVPlayer's last-rendered position. Gap = target minus parked, which is why it grows with scrub distance, goes bidirectional, and re-locks to ~70 ms the instant tcs returns to .playing. That matches every line of your trace.

    The visible symptom follows directly: our subtitle-overlay cue selection and your WT sync both ride the published clock, so they pick the target's position while the frame is parked. The scrub bar wants the target; frame-accurate consumers want the rendered position. They were sharing one clock.

    The fix (15dca96)

    Re-split the two intents:

    • NativeAVPlayerHost now publishes a renderedTime on every periodic tick, including mid-seek (the suppression that protects currentTime does not apply to it). During a not-yet-landed seek AVPlayer keeps reporting the pre-seek clock, which is the parked on-screen frame, so this is the picture's position.
    • The engine folds renderedTime onto source PTS (same seam-resolved shift as the playhead) and publishes it as clock.sourceTime. currentTime keeps the optimistic target (no Seek on the loopback-HLS native path resolves clock + state before the seek lands → reported time bounces back through the pre-seek position #37 regression); sourceTime now holds the picture. They agree in steady playback and diverge only across the rebuffer window.
    • The subtitle overlay, side-demuxer re-arm and cue retention all key off sourceTime, so they now follow the frame instead of the scrub target. If your WT sync wants the picture rather than the scrub intent, read sourceTime instead of currentTime for the comparison; currentTime stays the right value to drive a scrub bar.

    Verifying it on-device

    I added AetherEngine.clockLeadSeconds (currentTime - sourceTime) as a diagnostics-only readout, the direct analogue of what you measured. Before this change it was identically 0 (both rode the same clock); after it, during your burst, currentTime will race to the target while sourceTime holds the picture, so clockLeadSeconds reports the gap and sourceTime should stay locked to the AVPlayer clock you were logging.

    One honest caveat, same as before: a headless seektest run reads clockLead peak 0.00s because a fast macOS AVPlayer lands the seek almost immediately, so the rebuffer-stall window that opens the gap on your hardware never forms here. The fix is structural (it changes which position frame-accurate consumers read), so your device retest is what confirms it. Pin 15dca96 whenever convenient and the subtitles should track the picture through the burst.

    Your distinction between the rebuffer stall and the fold was the key, this saved a lot of guessing.

  8. rrgomes commented on Jun 19, 2026

    @rrgomes
    Contributor

    Confirmed reconciled on 3.11.1; host now reads sourceTime

    Folded 3.11.1 in and wired our host to the new clock.sourceTime: the subtitle clock now reads sourceTime so cues follow the rendered frame, not the optimistic scrub target. (We deliberately kept our Watch-Together position/drift on currentTime to preserve a monotonic broadcast position — the subtitle clock is where picture-following matters.)

    On-device (tvOS 26.x, Apple TV 4K 3rd-gen), the divergence is gone where we could observe it:

    We didn't reach the original sustained dueling-scrub repro on the DV-P7 title this round because #50 ended playback at ~27 s first. If you'd like a clean sustained-scrub clockLeadSeconds trace, we can capture it on a title that doesn't trip #50. Thanks for the fix.

  9. superuser404notfound commented on Jun 19, 2026

    @superuser404notfound
    OwnerAuthor

    Confirmed reconciled on-device, closing this out.

    Your 3.11.1 retest is the acceptance I was waiting for: clock.sourceTime now tracks the rendered frame while currentTime keeps the optimistic scrub target, so the subtitle clock follows the picture through a scrub instead of racing to the drop point. Keeping Watch-Together on currentTime for a monotonic broadcast position and the subtitle clock on sourceTime is exactly the split the fix was designed for.

    The engineClock vs internal-AVPlayer-clock reconciliation you measured (0.07 s, none of the earlier ~180 s spread) closes the mechanism: the original frameAhead/producer-shift hypothesis was dead, and the real divergence was the seek-path clock decoupling, now resolved in 15dca96 (shipped in 3.11.1).

    The one thing left open here was the sustained dueling-scrub clockLeadSeconds capture, but that is blocked by #50 ending playback before the burst can run, not by anything outstanding in #49. Tracking the remaining loopback-404 work in #50. Thanks for the 646-sample trace and the rebuffer-vs-fold distinction, that is what pinned it.

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