Skip to content

fix: harden HDR and TrueHD playback recovery - #81

Merged
Quick104 merged 3 commits into
mainfrom
codex/hdr-truehd-playback-stability
Jul 10, 2026
Merged

Quick104 merged 3 commits into
mainfrom
codex/hdr-truehd-playback-stability

Conversation

@Quick104

@Quick104 Quick104 commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Derive fragmented MP4 video sample durations from forward DTS and preserve mux ordering.
  • Retain and replay bounded selected-audio preroll across VOD restart keyframe gates.
  • Add bounded AVPlayer seeks, early VOD response headers, item-death reloads, and short interactive origin timeouts.
  • Serialize AVAudioSession activation off the main thread.
  • Avoid false CoreMedia demux timeouts after intentional pauses and clear stale scrub state on fresh/retry loads.

Root causes

  • Matroska default duration could diverge from the observed 41/42 ms DTS cadence, accumulating track drift.
  • Restart demux ordering could discard selected audio before the first accepted video keyframe.
  • AVPlayer seek completions and resource loading could remain pending indefinitely, while slow initial segment responses delayed AVPlayer too long.
  • AVAudioSession category and activation work ran synchronously on the main thread.
  • A deliberate pause aged the Compatibility Player I/O watchdog, and stale scrub-preview state could survive a retry.

Validation

  • 73 focused tests pass on the iPhone 17 Pro Simulator.
  • The SiloTV scheme builds successfully for the tvOS Simulator.
  • git diff --check origin/main...HEAD is clean.
  • Computer User confirmed route selection and fallback behavior using an explicit 2160p HDR HEVC source with TrueHD 7.1 audio.

Simulator limitation

Finding Dory does not prove end-to-end SiloPlayer playback in the Simulator:

  1. siloPlayerLoopback was selected and began source/cache work.
  2. Simulator AVPlayer rejected that route with AVFoundation -11868 / CoreMedia -17223.
  3. Rendering and manual seek checks occurred only after fallback to playerCoreDirect (Compatibility Player).

The local tests cover deterministic muxing, recovery-policy, timeout, seek, and loopback-server behavior. Dolby Vision, TrueHD/Atmos output, sustained high-bitrate A/V sync, and real SiloPlayer recovery still require validation on physical Apple TV hardware.

Closes #75
Closes #76
Closes #77
Closes #78
Closes #79
Closes #80

Summary by CodeRabbit

  • Bug Fixes
    • Improved playback recovery from VOD stalls, missing segments, and loopback item failures.
    • Reduced delays when waiting for unavailable VOD segments and improved response handling.
    • Prevented false playback timeouts after intentional pauses.
    • Improved seek and scrubbing cleanup when loading new content.
    • New device authorization no longer carries over the previous profile selection.
    • Improved VOD audio/video timing, buffering, and packet ordering.
  • Performance
    • Interactive playback requests now use shorter timeouts for faster retry behavior.

@coderabbitai

coderabbitai Bot commented Jul 9, 2026 •

Copy link
Copy Markdown

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 6f0942af-bbc2-495a-849b-781065461729

📥 Commits

Reviewing files that changed from the base of the PR and between d857ee7 and 0d95e20.

📒 Files selected for processing (17)
  • iosApp/Tests/LoopbackSegmentCutterTests.swift
  • iosApp/Tests/LoopbackSegmentServerRangeTests.swift
  • iosApp/Tests/LoopbackStartupRecoveryPolicyTests.swift
  • iosApp/Tests/PairingCoordinatorTests.swift
  • iosApp/Tests/PlaybackOriginOutageTests.swift
  • iosApp/Tests/PlaybackOriginStreamPolicyTests.swift
  • iosApp/Tests/SeekLatchTests.swift
  • iosApp/Tests/TrueHDPrimingPolicyTests.swift
  • iosApp/iosApp/Networking/ServerRegistry.swift
  • iosApp/iosApp/Pairing/Receiver/ReceiverPairingCoordinator.swift
  • iosApp/iosApp/Screens/Player/AVPlayerRoute/AVPlayerBackend.swift
  • iosApp/iosApp/Screens/Player/AVPlayerRoute/LoopbackSegmentServer.swift
  • iosApp/iosApp/Screens/Player/AVPlayerRoute/LoopbackSegmentStore.swift
  • iosApp/iosApp/Screens/Player/AVPlayerRoute/LoopbackSegmentWriter.swift
  • iosApp/iosApp/Screens/Player/CoreMedia/PlayerCore.swift
  • iosApp/iosApp/Screens/Player/PlaybackOriginChunkFetcher.swift
  • iosApp/iosApp/Screens/Player/PlayerViewModel.swift

📝 Walkthrough

Walkthrough

The changes harden loopback playback across remux duration handling, restart-time audio buffering, delayed VOD segment responses, AVPlayer recovery, demux timeouts, origin fetches, teardown, and credential-bound server replacement. New tests cover the added policies and recovery paths.

Changes

Playback hardening

Layer / File(s) Summary
Remux duration and pre-gate audio
iosApp/iosApp/Screens/Player/AVPlayerRoute/LoopbackSegmentWriter.swift, iosApp/Tests/LoopbackSegmentCutterTests.swift, iosApp/Tests/TrueHDPrimingPolicyTests.swift
Video durations are resolved from forward DTS deltas; selected restart-time audio is bounded, replayed, ordered, and routed through shared mux helpers.
Early VOD segment responses
iosApp/iosApp/Screens/Player/AVPlayerRoute/LoopbackSegmentServer.swift, iosApp/iosApp/Screens/Player/AVPlayerRoute/LoopbackSegmentStore.swift, iosApp/Tests/LoopbackSegmentServerRangeTests.swift
Missing VOD requests can emit early progressive headers, wait for segment availability, stream data, and abort terminal misses.
AVPlayer deadlines and loopback recovery
iosApp/iosApp/Screens/Player/AVPlayerRoute/AVPlayerBackend.swift, iosApp/Tests/LoopbackStartupRecoveryPolicyTests.swift, iosApp/Tests/SeekLatchTests.swift
Seek completions are generation-gated, audio-session work is coordinated asynchronously, and item-death evidence drives bounded reload or escalation.
Demux, origin, and load-state teardown
iosApp/iosApp/Screens/Player/CoreMedia/PlayerCore.swift, iosApp/iosApp/Screens/Player/PlaybackOriginChunkFetcher.swift, iosApp/iosApp/Screens/Player/PlayerViewModel.swift, iosApp/Tests/PlaybackOriginOutageTests.swift, iosApp/Tests/PlaybackOriginStreamPolicyTests.swift
Demux watchdogs ignore intentional pauses, interactive fetches use a four-second request timeout, and load reset clears pending seek and scrub state.

Server session profile replacement

Layer / File(s) Summary
Credential-bound server replacement
iosApp/iosApp/Networking/ServerRegistry.swift, iosApp/iosApp/Pairing/Receiver/ReceiverPairingCoordinator.swift, iosApp/Tests/PairingCoordinatorTests.swift
Server upserts can disable profile preservation, while receiver pairing clears stored profile identifiers and tokens during replacement.

Estimated code review effort: 5 (Critical) | ~120 minutes

Sequence Diagram(s)

sequenceDiagram
  participant AVPlayer
  participant LoopbackSegmentServer
  participant LoopbackSegmentStore
  participant AVPlayerBackend
  AVPlayer->>LoopbackSegmentServer: request missing VOD segment
  LoopbackSegmentServer-->>AVPlayer: send early response headers
  LoopbackSegmentStore-->>LoopbackSegmentServer: provide progressive segment bytes
  AVPlayer->>AVPlayerBackend: report seek timeout or item-death evidence
  AVPlayerBackend->>AVPlayerBackend: gate completion and record recovery evidence
  AVPlayerBackend-->>AVPlayer: reload item or escalate after bounded attempts
Loading
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/hdr-truehd-playback-stability

Comment @coderabbitai help to get the list of available commands.

@Quick104

Copy link
Copy Markdown
Contributor Author

Review

Overview

Six coordinated playback-hardening fixes closing #75–#80 from the AetherEngine gap audit: (1) fMP4 video sample durations derived from forward DTS via a one-packet look-behind in the loopback writer, (2) bounded retention/replay of selected-audio preroll across VOD restart keyframe gates, (3) AVPlayer seek deadlines + item-death (-12889/-15628) reload recovery, (4) early VOD response headers after 2 s (the #76 design choice: early headers over 503), (5) AVAudioSession activation moved off the main thread behind a generation-tracked coordinator, and (6) demux watchdog pause-awareness plus scrub-state cleanup. The pattern of extracting pure policy types (LoopbackVideoSampleDurationPolicy, CoreMediaDemuxInterruptPolicy, etc.) with focused XCTest coverage matches the codebase's established style, and teardown correctly frees all the new held AVPacket buffers.

Confirmed issues

1. High — the demux watchdog exemption disables wedge detection during startup and seeks, not just pause (PlayerCore.swift:3185)

CoreMediaDemuxInterruptPolicy.shouldAbort treats playbackClock.rate == 0 as "playback stopped," but the clock rate is 0 in three states, only one of which is a user pause:

  • Startup: setPlaybackTimeline(time: .zero, rate: 0) (PlayerCore.swift:1471) — the rate stays 0 through avformat_open_input and all initial demux reads until playback actually starts. A dead origin at open now blocks indefinitely instead of aborting after 10 s.
  • Seek restarts: rate is zeroed at PlayerCore.swift:1816 during the restart window. The seek path at PlayerCore.swift:1759-1763 explicitly re-stamps demuxLastProgressWall so seek I/O gets "a fresh demuxIOTimeoutSeconds window" — that documented contract is now dead code: with rate 0, the callback never aborts regardless of elapsed time. A network wedge mid-seek hangs forever (the interrupt callback is the only mechanism that can abort a blocked av_read_frame; FFmpegDemuxLoop and the buffering monitor only classify/recover after a read returns).

This partially reopens the wedge-recovery-chain gap — the one high-severity finding in the audit this PR is remediating. PlayerCore already has the precise signal: userPaused (set in pause(), cleared in resume()). Passing player.userPaused instead of playbackClock.rate == 0 fixes the false-positive-after-pause bug without disabling detection during startup/seeks. The resume-side rearm at PlayerCore.swift:1494 is correct and should stay either way.

2. High — audio-session coordinator loses cross-backend ordering (AVPlayerBackend.swift:635)

The old code ran setActive(true)/setActive(false) synchronously on the main thread, which gave a total order across backend instances: old backend deactivates, then the new one activates. The new coordinator is per-instance with a per-instance serial workQueue (created in the default parameter). On a quick item switch — teardown of the old AVPlayerBackend followed immediately by a new one — the old instance's deactivate() and the new instance's activate() land on two different queues with no ordering guarantee. If the deactivation runs last, the shared AVAudioSession singleton gets setActive(false, .notifyOthersOnDeactivation) while the new playback is live — intermittent silent-audio/stereo-latch symptoms that will be miserable to reproduce. Minimal fix: make workQueue a shared static let so all coordinators serialize on one queue. (This is exactly the #80 "process-wide coordinator" design question — the PR closes #80 with a per-instance answer without addressing the cross-instance race.)

3. Medium — a superseded initial seek permanently latches isInitialSeekInFlight (AVPlayerBackend.swift:3109-3118)

There is a single seek-deadline generation shared by two distinct state machines (initial and interactive), and seek(to:) has no guard against firing while an initial seek is in flight. Sequence: initial seek begins → user/recovery seek calls beginSeekDeadline, which cancels the initial deadline work item and supersedes its generation → the initial seek's AVPlayer completion eventually fires → completeSeekDeadline fails → early return without clearing isInitialSeekInFlight. Nothing else clears it (the deadline handler that would was cancelled), so attemptInitialPlaybackStart is permanently gated at AVPlayerBackend.swift:3083 and hasSeekedToStart never sets. Fix: clear the per-kind flags in the ignored-completion branch, or reset isInitialSeekInFlight when a new deadline supersedes an .initial one.

Worth noting (lower severity)

  • Early-headers terminal miss (LoopbackSegmentServer.swift:365-395): once the 200 is committed, a resolver miss can only connection.cancel(), so a genuinely absent segment surfaces as a network error and AVPlayer retry-loops rather than seeing a clean 404/503. Bounded and probably acceptable, but worth a log marker so retry storms are diagnosable. The waitForStart wiring is correct — the store's NSCondition is broadcast from beginProgressiveSegment, and the evicted check prevents a false empty-EOF.
  • 4 s interactive origin timeout (PlaybackOriginChunkFetcher.swift:11): timeoutIntervalForRequest is an idle timer, so flowing-but-slow responses are safe, but a time-to-first-byte over 4 s (server-side remux/seek startup on a loaded box, high-RTT remote — the exact PR SiloPlayer: streaming origin fetch — fix buffering on high-latency connections #66 scenario) now fails into the 0.5 s retry path. The reconnect-policy handoff test is a good guard; include a high-RTT remote case in the hardware pass.
  • No kill switch on the muxer look-behind: routeVideoPacketToMux rewires every packet write in the loopback writer — the single highest-risk change here — and unlike prior risky playback changes (outage ride-through, AVSyncLadder, drift governor) it ships with no fallback flag. Given hardware validation is still pending, a disable switch restoring the direct-write path would be cheap insurance.
  • Replay trigger gap: replayVODPreGateAudioPacketsIfNeeded() is invoked only from the main packet loop; the writePendingPackets drain path routes video without it, so a gate opened there delays replay by one main-loop video packet. Harmless today, but an easy one-liner for symmetry.
  • reloadEstablishedLoopbackItem copies only preferredForwardBufferDuration and the live-streaming flag onto the new item. Confirm nothing else item-scoped matters for established loopback playback (e.g., preferredPeakBitRate if ever set on this route). Observer detach/attach symmetry checks out.

Correctness verified

I specifically checked and found these sound: the pre-gate audio replay keeps timestamps on the source axis (packets cloned before rewritePacketForOutput, and vodShouldDropPacket rescales the gate DTS into the audio timebase); mux ordering is preserved (the gate keyframe is held, replayed audio defers into pendingMuxAudioPackets, and flush writes video-then-audio); the duration telescoping correctly spans segment cuts and falls back safely at EOF/backward-DTS; all new held packets are freed on teardown and the clone/free ownership around av_interleaved_write_frame is correct; the coordinator's generation tracking correctly drops stale activation completions; and the PlayerViewModel scrub-state cleanup is straightforward.

Tests & validation

Policy-level coverage is well-targeted and matches the repo's testing guidance (critical shared logic only). Two notes: the early-headers test costs ~3 s of real wall time (sleeps past the 2 s delay over a real socket) — fine as a one-off; and none of the tests exercise the three findings above, all of which live in the glue rather than the extracted policies — which is the usual blind spot of this extraction pattern. The PR's honest documentation of the simulator limitation (loopback route rejected with -11868/-17223, rendering verified only on the fallback engine) is appreciated; findings 1 and 2 are exactly the kind of thing the pending Apple TV hardware pass won't reliably catch either, since both are timing races.

Verdict: solid, well-structured work with genuinely good test hygiene — but findings 1 and 2 should be fixed before merge; both are small changes, and both undermine the recovery guarantees this PR exists to strengthen.

🤖 Generated with Claude Code

Quick104 and others added 2 commits July 9, 2026 21:28
- Scope the demux I/O watchdog exemption to explicit user pause
  (userPaused) instead of playbackClock.rate == 0. The clock also reads
  rate 0 during startup opens and seek restarts, and the interrupt
  callback is the only escape from a wedged av_read_frame there; the
  broader predicate silently disabled wedge detection in exactly those
  windows.
- Share one serial work queue across AVPlayerAudioSessionCoordinator
  instances. AVAudioSession is a process-wide singleton; per-instance
  queues let an old backend's teardown deactivation land after the next
  backend's activation and kill the new playback's audio route.
- Release isInitialSeekInFlight when a newer seek supersedes an
  in-flight initial seek's deadline generation. The superseded
  completion is ignored and its deadline work item is cancelled, so
  nothing else cleared the flag and attemptInitialPlaybackStart stayed
  gated forever.
- Trigger pre-gate audio replay from the pending-packet drain path too,
  mirroring the main loop.
- Log when an early-committed VOD response is aborted on a terminal
  miss so retry loops are diagnosable.

Co-Authored-By: Claude Fable 5 <[email protected]>
…e authorization

Companion device authorization can install a different user's credentials
for an already-saved server URL. persistServer now upserts the registry
entry without inheriting the existing profileId (new
addOrUpdate(preservingProfile:) seam) and clears the TokenStore profile
selection at the same boundary, so the new account starts without the old
account's profile. Ordinary metadata upserts keep preserving the profile,
covered by a new ServerSessionPersistenceTests case.

Co-Authored-By: Claude Fable 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment