Repository navigation
SiloPlayer: loopback-primary playback engine (static-VOD serving) - #52
Conversation
Two instrumentation changes from the loopback-primary plan (docs/tvos-player/2026-07-03-siloplayer-loopback-primary-plan.md): - PlaybackSourceProxy: classify how a proxied GET response loop ended via the pure PlaybackSourceResponseEnd.classify decision. A short origin read (the 2026-06-28 living-room incident: open-ended GET over 69 GB, origin stopped at 4.31 GB) now logs a structured '[CMP-SOURCE-CACHE] premature eof' line and surfaces a typed .prematureEOF interruption into the existing outage-recovery path instead of dying as an FFmpeg-only 'Stream ends prematurely'. - [CMP-TTFF] time-to-first-frame logs on both engines: AVPlayerBackend emits one line per load (first_segment_ms/ready_ms/first_frame_ms, first frame = first playhead advance while playing, axis-agnostic for the session-relative loopback timeline); PlayerCore emits at its existing one-shot FirstFrame signpost. Baseline for the Stage 2 startup-latency acceptance gates. Co-Authored-By: Claude Fable 5 <[email protected]>
…e types) The three load-bearing pure types for the VOD serving model, ported as patterns (not source) from the AetherEngine mechanisms verified in the plan's M1/M2/M4 rows, each with the boundary cases pinned by tests: - LoopbackSegmentPlan: load-time segment planning with keyframe-index trust gates (largest gap <= max(4x target, 30 s) AND first-to-last coverage >= one target duration), uniform-stride fallback, and segment 0 anchored at the first indexed keyframe so late-start titles never advertise unproducible leading segments. - LoopbackSegmentCutter: decode-order, keyframe-gated segment routing keyed on the IRAP's PTS (never DTS, which mis-routes under B-frame reorder); open-GOP RASL leading pictures stay with their CRA; late keyframes clamp into the last real segment. - LoopbackRestartCoalescer: one in-flight producer restart + one settled pending target; authoritative recovery re-bases own the pending slot over scrub bursts; isInFlight exposed for fetch-ride (1e). 38 tests green on iOS simulator. Co-Authored-By: Claude Fable 5 <[email protected]>
…playlist Adds LoopbackServingMode.vodPlan behind the session spec (default .event; zero behavior change for existing routes). When engaged, DVSegmentWriter: - resolves a LoopbackSegmentPlan after openInput (bounded mid-file cue prewarm loads the container keyframe index; trust gates pick keyframe vs uniform planning; degrades to EVENT serving if no plan is possible) and reports it via onSegmentPlanResolved so AVPlayerBackend can hand the same plan to restarted producers; - muxes with +empty_moov+default_base_moof+frag_custom+delay_moov+ frag_discont, use_editlist=0, avoid_negative_ts=disabled (plan M3) and cuts fragments explicitly through LoopbackSegmentCutter (drain interleaver -> flush -> first-cut double flush), naming segments by plan index; - emits one static VOD media playlist (full title, PLAYLIST-TYPE:VOD, ENDLIST) whose body never changes across the session, and attaches AVPlayer at the first produced video segment instead of the EVENT runway heuristics. Co-Authored-By: Claude Fable 5 <[email protected]>
…d restarts In VOD mode the per-session zero-basing (normalizeSeekedTimelineIfNeeded) is replaced by a plan-anchored timestamp shift: the anchor is the plan's first boundary — a plan constant — so a restarted producer applies the identical shift and its tfdt continues the session timeline. Restart correctness gates: - video pre-roll: a restarted demuxer seek that lands before the restart boundary drops everything until the first keyframe at-or-after it; - audio rides the video gate on restarts and the plan anchor at head of stream, with span-overlap semantics: a frame belongs to the region its duration overlaps, not where its start timestamp falls (the demuxer's per-track seek lands on the sample containing the target instant — a start-time gate lost exactly one audio frame per restart); - head-of-stream audio that would map below tfdt 0 is dropped (the muxer no longer absorbs negatives with avoid_negative_ts=disabled). Pinned by DVSegmentWriterVODContinuityTests over a committed 20 s H.264+EAC3 MP4 fixture: a restarted producer's segment is byte-identical to its continuous twin modulo the mfhd sequence number, with equal tfdt on both tracks. The fixture is MP4 deliberately — matroska synthesizes DTS after seeks, scattering byte layout by a frame while presentation stays epoch-invariant (same caveat AetherEngine documents). Co-Authored-By: Claude Fable 5 <[email protected]>
…estarts The static playlist's serving contract: - DVSegmentStore VOD retention: hard window [target-20, max(target+10, highWater)] never evicted; extras retained nearest-to-target-first under min(2 GiB, freeTmp/4); pruned segments read .missing (never .gone) because a producer restart regenerates them; every segment GET declares the consumer target and re-prunes around it. - Producer window backpressure: appends past target+forwardWindow park the mux thread, so the producer paces on consumption — replacing the EVENT generated-ahead throttle in VOD mode and inherently parking on a wedged playhead. VOD stats move to the plan axis so the shipped playhead watchdog compares like with like across restarts. - DVSegmentServer segment-miss resolver: a miss under the VOD playlist hops off the accept queue, asks the backend for a coalesced producer restart, and waits (bounded, 8 s) for the bytes before answering. - AVPlayerBackend restart-by-writer-swap: the store, server, and player item all survive; LoopbackRestartCoalescer serializes bursts; a fetch the running producer already covers (base..base+8) never restarts. Co-Authored-By: Claude Fable 5 <[email protected]>
- Seeks on a VOD session never take the teardown-reanchor path: the static playlist covers the whole title and a fetch into never-produced content restarts the producer behind the stable item (1e). The media-timeline offset becomes the plan anchor (the item timeline IS the plan's playlist axis), set at load and refined at plan resolution. - Stall recovery (M7) aims at the unlanded seek target when one exists — a wedged zero-tolerance seek leaves the frozen clock at the pre-seek position. Attempt 1 nudges AVPlayer (cancel pending seeks + fresh zero-tolerance seek + play, rebuilding its loading pipeline); later attempts swap the item in place (same URL, no pre-pause). Both ride an authoritative producer restart, which skips the coverage check and owns the coalescer's pending slot. The shipped watchdog budget still escalates to a route fallback when the ladder doesn't take. Co-Authored-By: Claude Fable 5 <[email protected]>
LoopbackServingMode.gated reads 'player.apple.siloplayer_primary_enabled' (UserDefaults, default OFF — flipping the default is the Stage 3 change after hardware validation). When ON: - the planner's h264/hevc-sdr 'loopback_startup_unreliable' blockers lift — the VOD serving mode removes the growing-playlist startup dependency those blockers exist for — and eligible sources route to the loopback with servingMode=.vodPlan (trace: silo_vod_gate_open); - every loopback spec construction site (planner + view model + proxy rewrite) threads the serving mode, so DV/HDR sources also serve VOD under the gate for hardware validation. When OFF, route selection and serving are byte-identical to today. Co-Authored-By: Claude Fable 5 <[email protected]>
First on-device DV run: the plan resolved (1193 segments, trusted) and production anchored at the resume point, but three resume-path holes stranded startup until the 12 s timeout fell back to PlayerCore: - the consumer window and coverage base were seeded at segment 0 while the writer's cutter anchored at the resume segment, parking the producer against its own backpressure window; - the stale coverage base made the segment-miss resolver believe the producer covered segment 0, suppressing the rescue restart; - AVPlayer buffered from position 0 (whose segments a resume-anchored producer never emits) because the initial seek waited for readyToPlay. Fix: the writer derives its EFFECTIVE anchor from the resume position at plan resolution and reports it via onVODProducerAnchored (window re-seeded + coverage base corrected before production begins), and on VOD resume the backend fires AVPlayer's initial seek immediately after item creation so its first fetches land at the resume segment. Regression test pins the shape: a first session with base 0 + mid-title start produces the same bytes as an explicit restart and no leading segments. Co-Authored-By: Claude Fable 5 <[email protected]>
Scrub-driven producer restarts anchored past the requested segment (anchored 322, parked 336) so the requested fetch 404'd after the full miss-wait, cascading into recovery nudges. Two causes, both restart-only: - a restarted writer's demuxer has a cold matroska cue index; the anchor seek lands by linear estimate up to a GOP away. Restarts now warm the cues (one proxy-cached mid-file read, same as the harvest path) and redo the start seek so it lands on the anchor keyframe. - the extradata bootstrap scan swallowed ~a GOP of packets it never replays before giving up. Plan-provided sessions skip it: their output extradata comes from codecpar, which the on-device run proved muxes valid DV segments (the give-up session played fine). Byte-identity and resume-anchor tests still green through the new path. Also instruments the segment miss-wait (enter/exit/present/evicted) and first-segment storage so the remaining 9 s startup-404 race, if it survives these fixes, names itself in the next device log. Co-Authored-By: Claude Fable 5 <[email protected]>
…ug 3) A large forward seek trapped playback in a buffering loop: the playhead watchdog read the post-seek buffer fill as a wedge (playhead frozen + media generated ahead), and each recovery attempt restarted the covering producer at the same anchor and reloaded the item — discarding the forward march and resetting the buffer it was punishing for filling. - Watchdog now holds recovery while the consumer is actively pulling segments (a serve within 4 s — the fetch-high-water signal the wedge detector was missing). A fill is not a wedge. - Recovery re-bases no longer restart a producer that already covers the target; the player-side nudge/reload handles consumer wedges. - The post-seek matroska DTS repair backs the anchor keyframe's DTS off by the codec reorder depth instead of dts:=pts, which over-stated it and made following packets non-monotonic — silently dropped by the muxer (-22), leaving sample-timeline gaps at every restarted segment head that AVPlayer refused to play through. - Mux write failures now mirror to stdout (OSLog is invisible to the devicectl console capture). Co-Authored-By: Claude Fable 5 <[email protected]>
The remaining on-device symptom — picture freezes for a few seconds while audio keeps playing after crossing a producer-session seam — is invisible in the devicectl capture because the transport telemetry goes to OSLog. Mirror to stdout in VOD mode: - 3 s transport state (pos/timeControl/rate/bufAhead/stationaryFor) to distinguish clock stalls from video-decode starvation; - per-track tfdt of the first three segments each producer session emits, to check seam timeline alignment against the prior session. Co-Authored-By: Claude Fable 5 <[email protected]>
The gate ('player.apple.siloplayer_primary_enabled') now defaults ON —
an absent key serves the static-VOD mode validated on hardware today;
an explicit false remains the kill switch to the EVENT path. With the
gate open by default, the planner's h264/hevc-sdr startup blockers lift
and the loopback is the primary engine for all H.264/HEVC direct play.
The names now match the architecture (all in-memory identifiers — no
persisted keys or wire strings changed, verified in the Stage 3 audit):
- PlaybackEngineKind.avPlayerLocalDVLoopback -> .siloPlayerLoopback
- SourceStrategy .localDVLoopback -> .siloLoopback (+ derived symbols)
- DVSegmentWriter/Store/Server -> LoopbackSegmentWriter/Store/Server
(types, files, and test files); DVWriterError -> LoopbackWriterError
Route capability matrix doc re-snapshotted for the new hierarchy.
Co-Authored-By: Claude Fable 5 <[email protected]>
buildVideoFormatDescription's default case rejected every codec outside HEVC/H264/ProRes/MPEG-2 even though the FFmpeg decoders were compiled in. Anything avcodec_find_decoder resolves now routes through the existing software path (same shape as the MPEG-2 case): VP9/VP8, AV1 via dav1d, MPEG-4 Part 2, VC-1, and the rest of the long tail play in-process as the codec-tail fallback instead of forcing a server transcode. Documented follow-ups (consolidation-report steps 3-4, unchanged in scope): the SW output path is 8-bit BGRA (10-bit SW HDR renders SDR) and decode is single-threaded (4K AV1/VP9 may stutter on Apple TV). Co-Authored-By: Claude Fable 5 <[email protected]>
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThis PR renames the DV loopback path to ChangesSilo Loopback Rename and VOD Serving Mode
Playback Source EOF Classification
HDR Criteria and PlayerCore Telemetry
Estimated code review effort: 5 (Critical) | ~120 minutes Possibly related PRs
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 1271671057
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| ) | ||
| load( | ||
| strategy: .localDVLoopback(spec: updatedSpec), | ||
| strategy: .siloLoopback(spec: updatedSpec), |
There was a problem hiding this comment.
Preserve VOD mode when rebuilding for audio changes
When a user changes audio on a .vodPlan SiloPlayer session, updatedSpec is created without copying spec.servingMode, so it falls back to the initializer default .event and this reload silently leaves the static-VOD path. That re-enables the legacy EVENT seek/startup behavior for the rest of the playback after an audio-track switch; pass through the existing serving mode when rebuilding the spec.
Useful? React with 👍 / 👎.
| } else { | ||
| guard let urlAsset = currentItem?.asset as? AVURLAsset else { return } | ||
| cmpLog("[CMP-AVP] vod stall recovery in-place item reload anchorPlayer=\(anchorPlayer)") | ||
| prepareAssetPlayback(url: urlAsset.url, headers: [:]) |
There was a problem hiding this comment.
Remove old item observers before VOD item reloads
On the second VOD stall-recovery rung this calls prepareAssetPlayback directly, bypassing teardownMediaPipeline, so the existing NotificationCenter observers installed by attachItemObservers are overwritten locally but never removed from the old item. In particular the old AVPlayerItemDidPlayToEndTime observer does not check item === currentItem, so if the replaced item finishes after the reload it can incorrectly fire onEndOfFile for the new playback.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Actionable comments posted: 5
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
iosApp/iosApp/Screens/Player/AVPlayerRoute/AVPlayerBackend.swift (1)
2151-2156: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winStale "DV loopback" wording in a user-surfaced error after the SiloPlayer rename.
reportError("Local DV loopback startup timed out after %.1fs ...")still says "DV loopback"; with the route now branded SiloPlayer (seedisplayRouteLabel), this error text is inconsistent with the rest of the UX.✏️ Suggested wording
- format: "Local DV loopback startup timed out after %.1fs before AVPlayer became ready", + format: "SiloPlayer loopback startup timed out after %.1fs before AVPlayer became ready",🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@iosApp/iosApp/Screens/Player/AVPlayerRoute/AVPlayerBackend.swift` around lines 2151 - 2156, The user-facing timeout message in AVPlayerBackend’s error reporting still uses the old “DV loopback” wording and should be updated to match the SiloPlayer branding used elsewhere, such as displayRouteLabel. Change the String(format:) text inside reportError so it consistently refers to SiloPlayer while keeping the same timeout context and AVPlayer readiness failure meaning.
🧹 Nitpick comments (4)
iosApp/iosApp/Screens/Player/PlayerViewModel.swift (1)
5634-5634: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueTwo serving-mode gate resolutions coexist. This method fixes
servingMode: .gated, while the planner path derivessiloPlayerPrimaryEnabledfromLoopbackServingMode.gated == .vodPlan(Line 1920) and re-maps it to.vodPlan/.event. Both read the sameprimaryGateKey, so they're equivalent today, but keeping two independent gate-resolution sites invites divergence if the gating logic ever grows (e.g., per-codec overrides). Consider having both paths funnel through a single resolver.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@iosApp/iosApp/Screens/Player/PlayerViewModel.swift` at line 5634, There are two separate gate-resolution paths for serving mode, which can drift if the gating logic changes. Consolidate the logic in PlayerViewModel by having both the planner path and the servingMode: .gated path use the same shared resolver for primaryGateKey, rather than independently mapping to .vodPlan or .event. Keep the behavior centralized in a single helper so future gate rules are applied consistently everywhere.iosApp/Tests/LoopbackSegmentPlanTests.swift (1)
172-207: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winMissing test coverage for the sub-target-duration uniform-fallback case.
None of the uniform-fallback tests exercise
sourceDurationSecondssmaller thantargetSegmentDurationSeconds(e.g. a 2s clip with a 4s target), which is the scenario whereduration = max(target, sourceDurationSeconds)(seeLoopbackSegmentPlan.swiftlines 186) would overstate the plan's total duration beyond the actual content length.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@iosApp/Tests/LoopbackSegmentPlanTests.swift` around lines 172 - 207, Add a new test in LoopbackSegmentPlanTests around LoopbackSegmentPlan.build to cover the uniform-fallback path when sourceDurationSeconds is shorter than targetSegmentDurationSeconds. Verify the plan still falls back without using the keyframe index, but does not overstate the total span for a short clip (for example, a 2s source with a 4s target). Use the existing uniform-fallback tests like testUntrustedIndexFallsBackToUniformStride and testEmptyIndexUniformPlanAnchorsAtZero as the reference points.iosApp/iosApp/Screens/Player/CoreMedia/PlayerCore.swift (1)
3451-3475: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winCodec-tail fallback logic is correct; consider deduplicating the software-decode setup/logging.
This block repeats the same
videoDecodeMode/dynamicRange/videoPixelFormatassignment and logging pattern already used by theAV_CODEC_ID_MPEG2VIDEOcase just above (Lines 3436-3449). Extracting a small shared helper (e.g.logAndSetupSoftwareVideoDecode(codecpar:codecparPtr:tail:)) would remove the duplication without changing behavior.♻️ Sketch of a shared helper
+ private func logAndSetupSoftwareVideoDecode( + codecpar: AVCodecParameters, + codecparPtr: UnsafeMutablePointer<AVCodecParameters>, + isTail: Bool + ) -> Bool { + videoDecodeMode = .software + dynamicRange = VideoColorMetadata.dynamicRange(forTransfer: codecpar.color_trc) + videoPixelFormat = kCVPixelFormatType_32BGRA + let codecName = Self.codecName(for: codecpar.codec_id) ?? "unknown" + Self.logger.info( + "video: codec=\(codecpar.codec_id.rawValue) \(codecpar.width)x\(codecpar.height) fps=\(self.refreshRate) dr=\(self.dynamicRange.rawValue) mode=software\(isTail ? " (codec-tail)" : "")" + ) + print(String(format: + "[CMP] video codecId=%d codec=%@ %dx%d fps=%.3f dr=%d color_trc=%d color_range=%d software=1\(isTail ? " tail=1" : "")", + Int(codecpar.codec_id.rawValue), codecName, Int(codecpar.width), Int(codecpar.height), + Double(self.refreshRate), Int(dynamicRange.rawValue), + Int(codecpar.color_trc.rawValue), Int(codecpar.color_range.rawValue))) + return setupSoftwareVideoDecoder(codecpar: codecpar, codecparPtr: codecparPtr) + }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@iosApp/iosApp/Screens/Player/CoreMedia/PlayerCore.swift` around lines 3451 - 3475, The codec-tail fallback in PlayerCore’s video decode switch duplicates the same software-decode setup and logging already done in the AV_CODEC_ID_MPEG2VIDEO path. Extract the shared work from the repeated block into a small helper (for example, a helper around the setup/logging near setupSoftwareVideoDecoder, videoDecodeMode, dynamicRange, and videoPixelFormat) and call it from both branches, keeping the codec-tail-specific log text or flag as an argument if needed.iosApp/iosApp/Screens/Player/AVPlayerRoute/LoopbackSegmentWriter.swift (1)
3778-3814: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win
emitVODMediaPlaylistrewrites an identical body on every segment finalize.The playlist body is plan-derived and idempotent, yet
emitPlaylists→emitVODMediaPlaylistruns on everyfinalizeCurrentSegment, re-serializing and re-writing the full-title playlist to the store/disk each time (only the stats need refreshing). For long titles this is hundreds of redundant identical writes. Consider writing the body once (guarded by a flag) and re-emitting only the generated-media stats.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@iosApp/iosApp/Screens/Player/AVPlayerRoute/LoopbackSegmentWriter.swift` around lines 3778 - 3814, The VOD playlist body is being re-serialized and rewritten on every finalize even though it is identical for the whole session; update `emitVODMediaPlaylist(plan:)` so the `writePlaylistArtifact` call happens only once per plan/title using a guard or cached state, and keep `emitGeneratedMediaStats` running on each invocation. Use the existing `emitPlaylists`, `finalizeCurrentSegment`, and `emitVODMediaPlaylist` flow to locate the write path and add a boolean/cache flag that skips redundant body writes while still refreshing stats.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@iosApp/iosApp/Screens/Player/AVPlayerRoute/LoopbackRestartCoalescer.swift`:
- Around line 27-54: The coalesced restart path in LoopbackRestartCoalescer is
dropping follow-up targets because next(justRan:) returns another index while
leaving isInFlight set, so the subsequent begin(_:authoritative:) call is
treated as already in flight and never triggers the restart work. Update the
contract between requestVODProducerRestart and LoopbackRestartCoalescer so a
returned follow-up target can actually start a new run, either by clearing
isInFlight before handing back the next target or by changing the loop to bypass
begin() for chained targets; keep the behavior aligned with
LoopbackRestartCoalescerTests.testBurstCoalescesToLatestTarget and the
begin(_:authoritative:)/next(justRan:) flow.
In `@iosApp/iosApp/Screens/Player/AVPlayerRoute/LoopbackSegmentPlan.swift`:
- Around line 179-216: Cap buildUniformPlan to the actual media length by using
sourceDurationSeconds as the upper bound instead of always extending to
targetSegmentDurationSeconds. Update the duration calculation and the final
boundary/startSeconds appended in LoopbackSegmentPlan so the last EXTINF
reflects the real source duration for short assets. Keep the existing uniform
stride logic, but ensure the values returned from buildUniformPlan stay within
sourceDurationSeconds.
In `@iosApp/iosApp/Screens/Player/AVPlayerRoute/LoopbackSegmentServer.swift`:
- Around line 313-354: In respondWithStoreResource, the synchronous
store.resource(path:) lookup is still waiting on near-future segment
availability even when vodSegmentMissResolver is configured, which blocks the
server queue before the async resolver runs. Update the missing/gone handling so
that when vodSegmentMissResolver is non-nil, the resource lookup uses
waitForNearFuture set to false and immediately falls through to the async
resolver path; keep the current behavior only when the resolver is absent.
In `@iosApp/iosApp/Screens/Player/AVPlayerRoute/LoopbackSegmentStore.swift`:
- Around line 180-352: The legacy eviction path in putSegment can still mark
VOD-window segments as `.gone` after vodPruneLocked runs. Update putSegment so
evictIfNeededLocked is skipped in VOD mode or constrained by vodTargetIndex and
vodHighWaterIndex, ensuring segments inside the configured VOD retention window
are never added to evictedResources.
In `@iosApp/iosApp/Screens/Player/PlaybackSourceProxy.swift`:
- Around line 682-707: The end-cause classification in
PlaybackSourceResponseEnd.classify is relying on Task.isCancelled, but
PlaybackSourceProxy.stop() can tear down the session without cancelling the
detached GET task, causing cancellation-shaped errors to be misclassified as
fetch failures. Update the range-fetch loop and the classify call to carry an
explicit teardown/stop cancellation flag (or otherwise recognize cancellation
errors before classification) so that stop-triggered cancellation maps to
.cancelled instead of .fetchFailed.
---
Outside diff comments:
In `@iosApp/iosApp/Screens/Player/AVPlayerRoute/AVPlayerBackend.swift`:
- Around line 2151-2156: The user-facing timeout message in AVPlayerBackend’s
error reporting still uses the old “DV loopback” wording and should be updated
to match the SiloPlayer branding used elsewhere, such as displayRouteLabel.
Change the String(format:) text inside reportError so it consistently refers to
SiloPlayer while keeping the same timeout context and AVPlayer readiness failure
meaning.
---
Nitpick comments:
In `@iosApp/iosApp/Screens/Player/AVPlayerRoute/LoopbackSegmentWriter.swift`:
- Around line 3778-3814: The VOD playlist body is being re-serialized and
rewritten on every finalize even though it is identical for the whole session;
update `emitVODMediaPlaylist(plan:)` so the `writePlaylistArtifact` call happens
only once per plan/title using a guard or cached state, and keep
`emitGeneratedMediaStats` running on each invocation. Use the existing
`emitPlaylists`, `finalizeCurrentSegment`, and `emitVODMediaPlaylist` flow to
locate the write path and add a boolean/cache flag that skips redundant body
writes while still refreshing stats.
In `@iosApp/iosApp/Screens/Player/CoreMedia/PlayerCore.swift`:
- Around line 3451-3475: The codec-tail fallback in PlayerCore’s video decode
switch duplicates the same software-decode setup and logging already done in the
AV_CODEC_ID_MPEG2VIDEO path. Extract the shared work from the repeated block
into a small helper (for example, a helper around the setup/logging near
setupSoftwareVideoDecoder, videoDecodeMode, dynamicRange, and videoPixelFormat)
and call it from both branches, keeping the codec-tail-specific log text or flag
as an argument if needed.
In `@iosApp/iosApp/Screens/Player/PlayerViewModel.swift`:
- Line 5634: There are two separate gate-resolution paths for serving mode,
which can drift if the gating logic changes. Consolidate the logic in
PlayerViewModel by having both the planner path and the servingMode: .gated path
use the same shared resolver for primaryGateKey, rather than independently
mapping to .vodPlan or .event. Keep the behavior centralized in a single helper
so future gate rules are applied consistently everywhere.
In `@iosApp/Tests/LoopbackSegmentPlanTests.swift`:
- Around line 172-207: Add a new test in LoopbackSegmentPlanTests around
LoopbackSegmentPlan.build to cover the uniform-fallback path when
sourceDurationSeconds is shorter than targetSegmentDurationSeconds. Verify the
plan still falls back without using the keyframe index, but does not overstate
the total span for a short clip (for example, a 2s source with a 4s target). Use
the existing uniform-fallback tests like
testUntrustedIndexFallsBackToUniformStride and
testEmptyIndexUniformPlanAnchorsAtZero as the reference points.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: b98ca261-f5aa-4a11-8c85-5649b92de75f
⛔ Files ignored due to path filters (1)
iosApp/Tests/Fixtures/loopback_continuity_h264_eac3.mp4is excluded by!**/*.mp4
📒 Files selected for processing (28)
docs/tvos-player/05-route-capability-matrix.mdiosApp/Tests/GeneratedAheadThrottlePolicyTests.swiftiosApp/Tests/LoopbackRestartCoalescerTests.swiftiosApp/Tests/LoopbackSegmentCutterTests.swiftiosApp/Tests/LoopbackSegmentPlanTests.swiftiosApp/Tests/LoopbackSegmentServerRangeTests.swiftiosApp/Tests/LoopbackSegmentStoreResourceTests.swiftiosApp/Tests/LoopbackSegmentStoreTests.swiftiosApp/Tests/LoopbackSegmentStoreVODRetentionTests.swiftiosApp/Tests/LoopbackSegmentWriterVODContinuityTests.swiftiosApp/Tests/PlaybackSourceResponseEndTests.swiftiosApp/iosApp/Screens/Player/AVPlayerRoute/AVPlayerBackend.swiftiosApp/iosApp/Screens/Player/AVPlayerRoute/ISOBoxSurgery.swiftiosApp/iosApp/Screens/Player/AVPlayerRoute/LoopbackRestartCoalescer.swiftiosApp/iosApp/Screens/Player/AVPlayerRoute/LoopbackSegmentCutter.swiftiosApp/iosApp/Screens/Player/AVPlayerRoute/LoopbackSegmentPlan.swiftiosApp/iosApp/Screens/Player/AVPlayerRoute/LoopbackSegmentServer.swiftiosApp/iosApp/Screens/Player/AVPlayerRoute/LoopbackSegmentStore.swiftiosApp/iosApp/Screens/Player/AVPlayerRoute/LoopbackSegmentWriter.swiftiosApp/iosApp/Screens/Player/ApplePlaybackRouteCapabilities.swiftiosApp/iosApp/Screens/Player/ApplePlaybackRoutePlanner.swiftiosApp/iosApp/Screens/Player/CoreMedia/PlayerCore.swiftiosApp/iosApp/Screens/Player/PlaybackCoordinator.swiftiosApp/iosApp/Screens/Player/PlaybackEngine.swiftiosApp/iosApp/Screens/Player/PlaybackExecutionPlan.swiftiosApp/iosApp/Screens/Player/PlaybackSourceProxy.swiftiosApp/iosApp/Screens/Player/PlayerViewModel.swiftiosApp/iosApp/iOSApp.swift
| private static func buildUniformPlan( | ||
| keyframePts: [Int64], | ||
| timeBaseNum: Int32, | ||
| timeBaseDen: Int32, | ||
| sourceDurationSeconds: Double, | ||
| targetSegmentDurationSeconds: Double | ||
| ) -> LoopbackSegmentPlan { | ||
| let duration = max(targetSegmentDurationSeconds, sourceDurationSeconds) | ||
| let anchor = keyframePts.min() ?? 0 | ||
| let count = max(1, Int((duration / targetSegmentDurationSeconds).rounded(.up))) | ||
|
|
||
| var boundaries: [Int64] = [] | ||
| var startSeconds: [Double] = [] | ||
| boundaries.reserveCapacity(count + 1) | ||
| startSeconds.reserveCapacity(count + 1) | ||
| for index in 0..<count { | ||
| let offset = Double(index) * targetSegmentDurationSeconds | ||
| boundaries.append(anchor + ticks( | ||
| forSeconds: offset, | ||
| timeBaseNum: timeBaseNum, | ||
| timeBaseDen: timeBaseDen | ||
| )) | ||
| startSeconds.append(offset) | ||
| } | ||
| boundaries.append(anchor + ticks( | ||
| forSeconds: duration, | ||
| timeBaseNum: timeBaseNum, | ||
| timeBaseDen: timeBaseDen | ||
| )) | ||
| startSeconds.append(duration) | ||
|
|
||
| return LoopbackSegmentPlan( | ||
| boundaries: boundaries, | ||
| startSeconds: startSeconds, | ||
| anchorSourceSeconds: Double(anchor) * Double(timeBaseNum) / Double(max(1, timeBaseDen)), | ||
| usedKeyframeIndex: false | ||
| ) | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
sed -n '1,320p' iosApp/iosApp/Screens/Player/AVPlayerRoute/LoopbackSegmentPlan.swiftRepository: Silo-Server/silo-apple
Length of output: 9622
🏁 Script executed:
rg -n "totalDurationSeconds|segmentCount|boundaries|startSeconds|sourceStartSeconds|buildUniformPlan|buildKeyframePlan|LoopbackSegmentPlan" iosApp/iosApp -g '*.swift'Repository: Silo-Server/silo-apple
Length of output: 19844
🏁 Script executed:
sed -n '1,260p' iosApp/iosApp/Screens/Player/AVPlayerRoute/LoopbackSegmentPlan.swiftRepository: Silo-Server/silo-apple
Length of output: 9622
🏁 Script executed:
sed -n '650,740p' iosApp/iosApp/Screens/Player/AVPlayerRoute/LoopbackSegmentWriter.swift
sed -n '3770,3865p' iosApp/iosApp/Screens/Player/AVPlayerRoute/LoopbackSegmentWriter.swift
sed -n '500,540p' iosApp/iosApp/Screens/Player/AVPlayerRoute/LoopbackSegmentWriter.swiftRepository: Silo-Server/silo-apple
Length of output: 10910
🏁 Script executed:
sed -n '1,120p' iosApp/iosApp/Screens/Player/AVPlayerRoute/LoopbackSegmentCutter.swift
sed -n '1,220p' iosApp/iosApp/Screens/Player/AVPlayerRoute/LoopbackSegmentStore.swift
sed -n '2680,2765p' iosApp/iosApp/Screens/Player/AVPlayerRoute/LoopbackSegmentWriter.swift
sed -n '3270,3345p' iosApp/iosApp/Screens/Player/AVPlayerRoute/LoopbackSegmentWriter.swiftRepository: Silo-Server/silo-apple
Length of output: 17548
Cap buildUniformPlan to the actual source duration.
When sourceDurationSeconds < targetSegmentDurationSeconds, this path still builds a plan whose final EXTINF is the target size instead of the real media length. That makes the VOD manifest overstate short assets that fall back to uniform stride.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@iosApp/iosApp/Screens/Player/AVPlayerRoute/LoopbackSegmentPlan.swift` around
lines 179 - 216, Cap buildUniformPlan to the actual media length by using
sourceDurationSeconds as the upper bound instead of always extending to
targetSegmentDurationSeconds. Update the duration calculation and the final
boundary/startSeconds appended in LoopbackSegmentPlan so the last EXTINF
reflects the real source duration for short assets. Keep the existing uniform
stride logic, but ensure the values returned from buildUniformPlan stay within
sourceDurationSeconds.
Tail-quality follow-ups for the Stage 4 codec tail (PlayerCore software video path), per the loopback-primary plan: - Threaded decode: the software decoder now requests frame+slice threading with a bounded budget of min(activeProcessorCount, 8), configured inside setupSoftwareVideoDecoder so the mid-stream VideoToolbox->software fallback inherits it. FFmpeg intersects the request with each codec's capabilities. New [CMP] stdout line logs codec/threads/dimensions at open. - 10-bit output: enqueueSoftwareVideoFrame now checks the decoded frame's actual bit depth (av_pix_fmt_desc_get on frame format — more reliable than bits_per_raw_sample) and converts >8-bit sources (10-bit VP9/AV1, 12-bit profiles) to P010-layout biplanar CVPixelBuffers via sws_scale to AV_PIX_FMT_P010LE, picking the Full/VideoRange variant from frame.color_range like the 8-bit planar fast path. Any failure returns nil and falls through to the existing 8-bit paths, so the worst case is today's behavior rather than a black screen. 8-bit content is untouched. Display needs no changes: DecodedVideoFrameRenderer derives the format description per buffer and the existing .shouldPropagate color attachments plus dynamicRange-driven display criteria carry HDR end-to-end. - EOF drain: frame threading parks up to ~thread_count decoded frames inside the decoder, so the video feed's EOF sentinel now flushes the software decoder (send nil packet, drain receive loop) before exiting — otherwise the file's tail would silently never display. Seek-after-EOF stays correct because performSeek's avcodec_flush_buffers resets FFmpeg's draining state. The receive loop is extracted from decodeSoftwareVideoPacket and shared. New helpers (sourceBitDepth, highBitDepthOutputPixelFormat) live in VideoColorMetadata with focused tests. Deviation from the brief: the optional CVPixelBufferPool for the 10-bit path was skipped to keep the diff focused — the 8-bit fallback already creates per-frame buffers, so pooling is a separable perf follow-up. Verified: SiloTV (tvOS sim) + SiloMac builds green, iOS test suite 382/382 green (5 new). Remaining manual validation on device: 10-bit VP9/AV1 through the codec tail (HDR mode switch, threads>1 in the open log), 8-bit tail content unchanged, last frames render at EOF. Co-Authored-By: Claude Fable 5 <[email protected]>
(a) Abandoned-fetch early-exit. When AVPlayer abandons a scrub fetch and jumps elsewhere, the server's miss resolver was still parked in LoopbackSegmentStore.waitForSegment for the full 8 s deadline. The store now supersedes such waits: a waiter on segment N survives only while the newest declared consumer target T keeps N inside the producer band [T - forwardWindow, T + forwardWindow]. Outside that band the wait is provably moot — above it vodProducerMayAppend parks every producer at T + forwardWindow so N can never be filled; below it producers only march forward, and anything that could regenerate N would first re-declare a target near N. Inside the band the wait stays alive, protecting the legitimate cases: the miss's own restart seeds declareVODTarget at (or near) N, a covering producer's march delivers N (backend coverage window 8 < store band 10, so the band is a superset), and a pipelined adjacent fetch cannot kill a live neighbor. declareVODTarget already broadcasts on the NSCondition, so no new wake plumbing — the waiter just gained the supersede predicate, checked before every wait slice (including the first, covering a target already stale at entry). A new declaration counter distinguishes "a real target was declared" from the fresh-store default so non-VOD waits keep their exact previous semantics. (b) Seam decode-ramp at producer restarts — analysis, no behavior change. The produced seam data is already clean: a restarted producer seeks with warm cues to the anchor boundary, the restart pre-roll gate drops everything before the first keyframe at-or-after it, and restarted segments are byte-identical to their continuous twins (pinned by LoopbackSegmentWriterVODContinuityTests); every segment opens on an IRAP (the cutter keeps open-GOP RASL leading pictures with their CRA). The visible ramp is therefore client-side random-access decode behavior: (1) open-GOP sources — a fresh decode from a CRA cannot decode its RASL leading pictures (they reference the prior GOP), so AVPlayer drops a few leading frames; only transcoding to closed-GOP IDR starts would remove that, out of scope for a remux engine; (2) VideoToolbox decode-session re-prime plus DV P8 RPU re-lock after a flush — platform behavior; (3) thin post-seek forward buffer, already mitigated by the buffer ramp. The floated fix (pre-anchor video pre-roll in the first restarted segment) is rejected: it breaks restart byte-identity, desynchronizes the static playlist's advertised timing, and can map audio below tfdt 0. Shipped instead: zero-behavior drop counters in the restart pre-roll gate, printed once when the video gate opens, so the next hardware pass can size the seam. Co-Authored-By: Claude Fable 5 <[email protected]>
…dder The fixed 12s readiness timeout killed healthy-but-slow loopback startups (living-room DV P7 + TrueHD at a far resume) while segment GETs were flowing the whole time. Elapsed wall time is not evidence of a wedge — frozen forward progress is: a dead AVPlayer loader stops requesting within seconds, so genuine failures now fall back faster than before. - LoopbackStartupRecoveryPolicy: pure verdict (wait / escalate / failBackstop) from seconds-since-progress vs a 6s stall window, held during HDMI display-mode switches, 60s absolute backstop. - AVPlayerBackend: 1Hz watchdog feeds the policy from the loopback server's served-request counter; escalation ladder is nudge seek → in-place AVPlayerItem reload (same loopback session) → route fallback. - newErrorLogEntryNotification observer logs swallowed HLS-level errors; the -15628 loader-poison signature escalates the ladder immediately. - LoopbackSegmentServer: monotonic servedRequestCount for the freeze check. Pattern borrowed from AetherEngine's dead-consumer re-engage watchdog (progress-anchored budgets, recovery-in-place before engine fallback). Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01X52DcjS2uuvaRc8SbW2HZJ
Root cause of the DV P7 + TrueHD mid-title resume never becoming ready: the bridged-audio encoder clock (nextEncodedAudioPTS) zero-based per producer run while remuxed video rode the plan axis, so segments carried disjoint track timelines (tfdt=[1:absolute,2:0]). AVPlayer's seek target was covered by video but never by audio — it buffered forward indefinitely (600MB+) without reaching readyToPlay, then fell back to the compatibility player (HDR instead of DV). This was the plan risk table's "restart timeline continuity unvalidated" item made real. Seed the counter from the first emitted frame's session-axis timestamp (source pts minus plan.boundaries[0], rescaled to encoder ticks) — the same shift applyVODAnchorShift gives remuxed packets. Priming frames never reach the encoder, so the first emitted frame is the first muxed-bound one. Producer restarts re-seed on the same axis. Hardware-validated on the living-room Apple TV: resume at 2396s went from never-ready + 60s fallback to readyToPlay in 3.7s with AVPlayer reporting Dolby Vision P8 + FLAC 7.1. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01X52DcjS2uuvaRc8SbW2HZJ
…idation
Extend the synchronous pre-item preferredDisplayCriteria write beyond
Dolby Vision to plain HDR10/HLG HEVC loopback content (plan doc M8), and
collapse the two independent criteria paths (AVPlayerBackend inline
window-walks vs CoreMedia/TVDisplayCriteria) onto one set of primitives.
Mechanism:
- HDRDisplayCriteriaPolicy (new, platform-neutral): rollout gate
'player.apple.hdr_display_criteria_enabled' (absent = OFF), pure
videoMode + manifest videoRange ("PQ"/"HLG"/"SDR") -> criteria
selection (DV modes stay ungated and unchanged; H264/SDR select
nothing), settle-poll constants, and the preserve-across-reload rule.
- TVDisplayCriteria: setRangeCriteria (factored private-initializer DV
write; apply() delegates with its log lines byte-identical for
PlayerCore's on-device greps), setHDRFormatCriteria (public
AVDisplayCriteria(refreshRate:formatDescription:) with an HEVC
4K format description carrying BT.2020 primaries/matrix and PQ or HLG
transfer), waitForModeSwitchSettle (two-stage poll: 100x10ms for the
asynchronously-starting HDMI handshake to begin, early-exit when the
panel already reports EDR headroom > 1.001; then 50x100ms for it to
clear; hosted-HDR judged solely by post-settle headroom), and
panelIsHostingHDR.
- AVPlayerBackend: applyTVDisplayCriteriaForLoopbackIfNeeded now routes
through the policy + primitives and reports whether a settle wait is
needed; on the gated HDR path the criteria write stays synchronous
before item creation while the AVPlayerItem attach (prepare + VOD
resume pre-seek, extracted as attachLoopbackItem) defers behind a
cancellable settle task re-guarded on session/dispose/currentItem and
cancelled in teardownMediaPipeline. The post-settle hdrHosted snapshot
is logged as the panel-readiness seam: no manifest gating is required
today because the loopback route always serves AVPlayer the media
playlist, never the VIDEO-RANGE-claiming master artifact, so an SDR
panel safely tonemaps. Reload preservation now runs through the same
policy (gate off = shipped DV->DV same-rate rule exactly; gate on
additionally keeps same-range HDR10/HLG criteria so audio-track
changes don't renegotiate HDMI). Four duplicated window-walks
consolidated onto TVDisplayCriteria.activeTVWindow() with log strings
preserved.
The motivating account of tvOS 26.5 rejecting un-hostable VIDEO-RANGE
masters (-11868 pre-EXT-X-MAP, zero errorLog events) is unverified by
us, hence the default-OFF gate; DV behavior is unchanged and ungated.
Deviations from the brief: a reload that preserved criteria skips the
settle wait (identical rewrite triggers no new negotiation); the fourth
window-walk (isTVDisplayModeSwitchInProgress) was consolidated too.
SiloTV + SiloMac builds green; iOS suite 401 tests green (11 new).
Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01GjbssMwqt7r9emGaZJ68Cj
After ~50 minutes of continuous 4K DV playback the loopback producer wedged: tempSpillBytes hit the 4GB spill gate, no new segments could be stored, AVPlayer drained its buffer and froze at the playhead with endless 404s — and no recovery path applied (living-room freeze at pos=3203.7s). Root cause: the memory evictor removes a segment's name from segmentOrder when spilling it to disk, and vodPruneLocked built its inventory FROM segmentOrder — retention was structurally blind to every spilled segment and never evicted a spilled byte. Pruning ran on every append and fetch, saw only the ~8 in-memory names, and 4GB of invisible spill accumulated until the gate deadlocked the producer. Layered fix: - vodPruneLocked inventories the union of memory + spilling + spilled segments, so retention actually bounds spill (the real fix; new regression test reproduces the blindness). - LoopbackSegmentStore.makeRoomForAppend: when the append gate would still block, force-evict spilled segments farthest from the consumer's target (sparing the playhead neighborhood) — a wedged producer is strictly worse than regenerating a distant segment. Wired into the writer's capacity wait. - Retention budget hardening: resolve via the filesystem-attributes helper (the ForImportantUsage key is unavailable on tvOS and the plain key can read 0 there, which the old code passed through as a budget of 0 = retention disabled); pure clamp caps at 2GiB, floors at 512MiB, treats non-positive readings as query-broken; configureVODRetention rejects degenerate budgets; budget logged at session start. - Playhead watchdog starvation escalation: waiting on an empty buffer 30s+ with no successful segment serve in 15s falls back to the Compatibility route instead of freezing forever (the reanchor path requires generated media ahead, so producer-dead stalls never qualified for any recovery). - Backpressure log no longer prints the nonsensical cross-axis "generatedAhead" subtraction. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01X52DcjS2uuvaRc8SbW2HZJ
…GS/DVD) Bitmap-subbed content (PGS/hdmv_pgs_subtitle, dvd_subtitle/VobSub) now stays on the direct SiloPlayer path with subtitles rendered client-side, instead of forcing the compatibility route's server burn-in transcode. Notably, DV+PGS titles — which already rode loopback because the DV policy bypasses the planner's subtitle check — get visible subtitles for the first time. Mechanism (re-expressed from the AetherEngine reference, no LGPL text): - AVPlayerEmbeddedSubtitleExtractor now enumerates and decodes PGS/DVD streams (DVB stays excluded and keeps burn-in). Each SUBTITLE_BITMAP rect's PAL8 plane + [B,G,R,A] palette is cropped to its opaque bounding box (some Blu-ray→MKV remuxes ship full-frame, ~99%% transparent planes) and converted to premultiplied RGBA ((c*a+127)/255, round half up) → sRGB premultipliedLast CGImage. The codec context is seeded with the container video dimensions before open so dvd_subtitle geometry has a canvas before any in-band update; PGS composition updates in the codec ctx take precedence. A synthetic 3-byte END segment flushes PGS display sets whose END was lost in remuxing. - BitmapSubtitleCue.swift (new): pure palette/crop conversion (BitmapSubtitlePalette) and a lock-guarded, sorted BitmapSubtitleCueStore with PGS trim-on-next-event semantics (every composition, including an empty clear event, supersedes the on-screen cue), a 30s retention window, a 128-cue cap, and a monotonic revision for cheap change detection. - SubtitleSession grows slot-keyed bitmap stores riding the existing lifecycle: openBitmapTrack drops any libass track in the slot, flushOnSeek always clears bitmap stores (never live-AI), closeSlot/ teardown/track-switch paths clean up. - SubtitleOverlayView (UIKit + AppKit) gains a bitmap cue layer group above the libass contents layer: one CALayer per active cue, framed by the caller in overlay points. The AppKit host layer is geometry-flipped so both variants share top-left-origin math. - AVPlayerBackend.pumpSubtitleOverlay drives both paths off the same sync-adjusted clock; bitmap layer work is skipped while the (overlay-size, active-image-identity) key is unchanged. NOTE: the backend half of this change was inadvertently swept into 1ca9845 (the concurrent VOD spill-fix commit picked up the then-uncommitted working tree file); it is validated together with this commit. - ApplePlaybackRoutePlanner: bitmap_subtitles_require_compatibility now fires only for bitmap codecs outside the new client-rendered set (pgs/hdmv_pgs_subtitle/dvd_subtitle/vobsub); dvb_subtitle still blocks. A silo_bitmap_subtitles_client_rendered_* trace token records the new behavior. siloBitmapSubtitleCodecs is untouched so the AI transcribe menu keeps keying off it. Deviations from the scout brief: the optional SUP "PG"-prefix strip and zlib/gzip unwrapping were skipped (FFmpeg's Matroska demuxer handles container compression; noted as a fallback if a real file disproves it). No planner unit test was added — no existing planner fixture set made it cheap. Out of scope, unchanged: the compat route's EmbeddedSubtitlePipeline still drops bitmap subs (codec-tail content and the rare loopback→compat degrade keep today's behavior). Tests: BitmapSubtitlePaletteTests (premultiply rounding, BGRA→RGBA order, alpha-bbox crop + floor boundary, stride handling, buffer guards), BitmapSubtitleCueStoreTests (activity boundaries, PGS trim/clear semantics, retention prune, count cap, revision/clear, store isolation). tvOS + iOS + macOS builds green; full iOS suite green. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01GjbssMwqt7r9emGaZJ68Cj
Producer restarts (~every 9 segments in steady state) rebuild the TrueHD/MLP decoder, which silently consumes ~40ms of packets before its first major_sync — so every seam left a systematic hole in the bridged FLAC track (measured 42ms at segments 1098 and 1107 on the living-room capture; within-run continuity is sample-exact). Over eARC that periodic discontinuity is audible as an intermittent smeared/phasey blip — reported as "channels out of sync". Fix: the outgoing writer exposes the exclusive end sample of the audio it handed to the encoder (session axis); the restart path passes it to the incoming writer. When the new run's source-derived seed lands within 250ms of that end, the run anchors to it instead: a gap is filled with encoded silence (lipsync stays exact — content samples keep their source timestamps), an overlap is trimmed out of the sample FIFO before those samples are ever stamped. Deltas beyond the window are real seeks and keep source-accurate seeding. Seam decisions are logged ([CMP-AVP] vod bridged audio seam stitch ...) for on-device validation. Copy-mode audio (E-AC3 passthrough) is untouched — it never had seams. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01X52DcjS2uuvaRc8SbW2HZJ
The tvOS player HUD leaked engineering diagnostics into its casual info
surface:
- Info pane collapsed to one route line "SiloPlayer · Direct Stream"
(family displayLabel + delivery); the verbose Decision row moves out —
the full decision trace stays in the settings sheet diagnostics.
- Stats "Route" drops loopback jargon: "SiloPlayer (Dolby Vision)"
instead of "SiloPlayer Dolby Vision Loopback".
- Stats "Source" shows the origin host the media is fetched from
instead of "SiloPlayer local stream" (the loopback is an
implementation detail).
- "Dynamic range" no longer shows the placeholder "HDR output
validation required (...)": the introspected format of what AVPlayer
is actually playing wins (e.g. "Dolby Vision Profile 8 Level 6 (HDR10
compatible)"), with a plainly-worded spec-derived fallback
("Dolby Vision (Profile 7 → 8.1)").
Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01X52DcjS2uuvaRc8SbW2HZJ
…ource host The v1 seam stitch (2fd8bf9) never engaged on device: it compared the new run's seed against the previous writer's encoder counter, but the encode pipeline runs seconds ahead of the segment cutter (measured delta=-107040 samples ≈ -2.3s), so every contiguous seam was misclassified as a seek and the ~42ms audio holes — the audible glitches — persisted. Anchor to the run's own plan boundary instead, with no cross-writer state: the cutter's span-assignment invariant guarantees the previous contiguous run's stored audio ends at that boundary, and the restarted video track starts there. Gap after the boundary (MLP major_sync loss, typically ~42ms; ≤1s) is silence-filled; overlap (straddling frame; ≤250ms) is trimmed pre-timestamp. This also closes the 170-315ms audio hole at cold mid-title resume starts. The counter handoff is removed. Also: the HUD stats "Source" row showed 127.0.0.1 — the in-app source proxy / loopback address. The view model now rewrites localhost sources to the plan's true origin host for both backends. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01X52DcjS2uuvaRc8SbW2HZJ
1. VOD prune / force-evict racing an in-flight spill resurrected the segment and corrupted tempSpillBytes (LoopbackSegmentStore, 3 findings, major): finishSpillLocked now treats "name no longer in spillingSegments" as evicted-while-spilling — it deletes the freshly written file and never re-registers the segment, so a prune victim cannot come back with uncounted bytes and later double-deduct. Every legitimate completion still has the name reserved (only vodPruneLocked / makeRoomForAppend / retireSegments remove it early, and retire also marks evictedResources). Added a deterministic spill-write interlude test seam plus a regression test that reproduces the interleaving; verified the test fails against the old code. 2. waitForSegment supersede early-exit could 404 a segment its own restart would deliver (minor): a single out-of-band target observation no longer breaks the wait permanently. The waiter tolerates one out-of-band check and exits only when the band is still violated on the next bounded wakeup (~250 ms), giving the miss's own producer restart time to re-declare the target at the waited index while abandoned far fetches still exit quickly. Doc comment rewritten (the old "provably moot" claim was wrong below band). New test covers the transient far-target swing. 3. makeRoomForAppend fits criterion looser than canAppendSegment's spill projection (minor): the projection is factored into a shared appendWouldFitLocked helper used by the gate, the relief loop's stop condition, and the returned fits value, so relief can no longer report success while the writer's gate stays closed (30 s capacity-wait spin). New test pins relief => gate-open with mixed segment sizes. 4. Bitmap-only subtitle playback dispatched overlay.updateContents(nil) to main every display-link tick (2 findings, minor): the text-layer clear in pumpSubtitleOverlay is now one-shot, gated on a textOverlayMayHaveFrame flag (set while a libass track renders, reset on clear/no-track/teardown) and funneled through the render session queue so it serializes behind any in-flight render. NOTE: these AVPlayerBackend.swift edits were swept into commit 198194f by a concurrent session working in the same checkout; they are described here for traceability but carried by that commit. 5. LGPL: waitForModeSwitchSettle transcribed AetherEngine's waitForSwitch (major): re-expressed in Silo's idiom — sawSwitchStart renamed to negotiationBegan, attempt-counted for-loops restructured to budget-decrementing while-loops with hoisted cancellation handling, the tick log replaced with an elapsed-ms log, and the doc comments in TVDisplayCriteria.swift and HDRDisplayCriteriaPolicy.swift rewritten in original phrasing. Borrowed mechanism constants (100x10 ms, 50x100 ms, 1.001 floor) retained under Silo names. 6. LGPL: nudge doc comment reused AetherEngine's "rebuilds AVFoundation's loading pipeline" phrasing (minor): reworded in Silo's own voice. (Also carried by 198194f per note above.) 7. Metadata-poor HEVC defaulted to a "PQ" token, which the gated HDR criteria path would turn into a forced HDR10 HDMI switch for possibly-SDR content (minor): the .passthroughHEVC fallback in ApplePlaybackRoutePlanner.videoRange now resolves unknown transfer to "SDR" — safe because the master playlist carrying the token is never served to AVPlayer, leaving the criteria policy its only behavioral consumer. Added producer+policy composition tests (metadata-poor selects .none even gate-on; tagged PQ/HLG still select .hdr10/.hlg). Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01GjbssMwqt7r9emGaZJ68Cj
A first VOD session resuming mid-segment could never start: with cold matroska cues the BACKWARD start seek lands by linear estimate — potentially past the anchor segment's containing keyframe — so the producer generated segments from effectiveBase+1 onward while AVPlayer's resume pre-seek fetched effectiveBase, which never arrived (living-room resume at 6199.7s inside segment 1549: first produced segment was 1550, endless 404s, startup ladder correctly fell back to Compatibility). Warm the cue index (bounded mid-file seek) before the start seek when a first VOD session resumes past zero — the same cold-cue remedy the restart path already applies in prewarmVODCueIndexAndReseek — so BACKWARD lands on the true containing keyframe and the anchor segment is produced. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01X52DcjS2uuvaRc8SbW2HZJ
Flip the loopback stats badge from "HDR10" to "HDR10+" when the played HEVC bitstream actually carries SMPTE ST 2094-40 dynamic metadata, rather than labelling every PQ source "HDR10" statically. Mechanism: a latch-once scan for the ITU-T T.35 user-data-registered SEI needle (B5 00 3C 00 01 04) runs at the writer's single packet choke point (rewritePacketForOutput), so the SEI on the very first keyframe — including bootstrap-stashed packets replayed outside the main video branch — is never missed. First hit fires a one-shot main-hop callback that sets a sticky per-load flag and forces a stats re-emit; dynamicRangeLabel then reports "HDR10+". Deliberate scope: the scan is installed only for plain HEVC PQ sessions (videoMode == .passthroughHEVC, videoRange not HLG/SDR). DV Profile 8 sources keep their already-validated labels — the scan is never installed for them. The flag is reset per load() but intentionally kept sticky across VOD producer restarts (a restart builds a new writer for the same session and never calls load()), so the badge does not regress mid-title. Co-Authored-By: Claude Fable 5 <[email protected]>
The cue-warm fix (02888e9) was insufficient: seeking to the resume TIME parks the demuxer mid-GOP inside the anchor segment regardless of cue accuracy (bootstrap OK: droppedPreVideo=21 discards up to the NEXT keyframe), so the anchor segment AVPlayer's resume pre-seek fetches is still never produced — reproduced immediately at resume 6848.1s inside segment 1711, first produced segment 1712, 404 loop, ladder fallback. After the plan resolves and the effective base is computed in activateVOD — before any packet is consumed on a first session — re-seek to the anchor segment's boundary (a plan keyframe), the same contract restart producers rely on in prewarmVODCueIndexAndReseek. The video track then starts exactly at the fetched segment, and the bridged audio seed lands within the seam-stitch fill window at resume starts too. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01X52DcjS2uuvaRc8SbW2HZJ
There was a problem hiding this comment.
🧹 Nitpick comments (2)
iosApp/iosApp/Screens/Player/AVPlayerRoute/LoopbackSubtitleTap.swift (1)
105-112: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winAvoid an O(n) copy-on-write clone on every
ingest.
var cues = cuesByStream[cue.streamIndex] ?? []copies theArraystruct out of the dictionary while the dictionary still references the same backing buffer. The subsequentcues.append(cue)therefore sees a non-unique buffer and triggers a full O(n) deep copy on every ingested cue. Across a feature film (1–3k cues, re-read on producer restarts) this is O(n²) buffer churn on the writer's mux queue while holdinglock.Use the
default:subscript so libass appends in place:♻️ In-place append avoids the per-cue clone
- var cues = cuesByStream[cue.streamIndex] ?? [] - if cues.count >= Self.maxCuesPerStream { + let count = cuesByStream[cue.streamIndex]?.count ?? 0 + if count >= Self.maxCuesPerStream { lock.unlock() return } dedupKeys.insert(key) - cues.append(cue) - cuesByStream[cue.streamIndex] = cues + cuesByStream[cue.streamIndex, default: []].append(cue)🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@iosApp/iosApp/Screens/Player/AVPlayerRoute/LoopbackSubtitleTap.swift` around lines 105 - 112, The cue ingestion path in LoopbackSubtitleTap is causing an unnecessary copy-on-write array clone on every append because cues are first read into a local variable and then written back to cuesByStream. Update the ingest logic that handles cuesByStream[cue.streamIndex] so it appends directly through the dictionary’s default subscript, keeping the array uniquely referenced and avoiding the per-cue deep copy while lock is held.iosApp/iosApp/Screens/Player/Subtitles/SubtitleRenderer.swift (1)
75-83: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winTrack removal of the temporary
[CMP-SUBDIAG]/[CMP-SUB*]instrumentation before merge.These fields and the associated
print()diagnostics (here and at Lines 127-136, 402-405, 568-579, 655-658) are explicitly marked temporary and run on the per-frame render/feed paths.print()bypasses theos.Loggerused elsewhere and is unbuffered/synchronous, so leaving it in the shipping render loop adds avoidable overhead and noise. Please gate behind a debug flag or remove before merge.Want me to open a tracking issue for stripping the temporary diagnostics?
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@iosApp/iosApp/Screens/Player/Subtitles/SubtitleRenderer.swift` around lines 75 - 83, The SubtitleRenderer still contains temporary [CMP-SUBDIAG]/[CMP-SUB*] instrumentation and print() calls in the per-frame render/feed path, which should not ship. Remove these diagnostic fields and prints before merge, or guard them behind a debug-only flag so they never execute in production; use the SubtitleRenderer diagnostics blocks and the related render/feed methods where the temporary logging was added to locate and strip them.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@iosApp/iosApp/Screens/Player/AVPlayerRoute/LoopbackSubtitleTap.swift`:
- Around line 105-112: The cue ingestion path in LoopbackSubtitleTap is causing
an unnecessary copy-on-write array clone on every append because cues are first
read into a local variable and then written back to cuesByStream. Update the
ingest logic that handles cuesByStream[cue.streamIndex] so it appends directly
through the dictionary’s default subscript, keeping the array uniquely
referenced and avoiding the per-cue deep copy while lock is held.
In `@iosApp/iosApp/Screens/Player/Subtitles/SubtitleRenderer.swift`:
- Around line 75-83: The SubtitleRenderer still contains temporary
[CMP-SUBDIAG]/[CMP-SUB*] instrumentation and print() calls in the per-frame
render/feed path, which should not ship. Remove these diagnostic fields and
prints before merge, or guard them behind a debug-only flag so they never
execute in production; use the SubtitleRenderer diagnostics blocks and the
related render/feed methods where the temporary logging was added to locate and
strip them.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: f344e658-2634-4ca3-b928-b9a525bbf820
📒 Files selected for processing (5)
iosApp/iosApp/Screens/Player/AVPlayerRoute/AVPlayerBackend.swiftiosApp/iosApp/Screens/Player/AVPlayerRoute/LoopbackSegmentWriter.swiftiosApp/iosApp/Screens/Player/AVPlayerRoute/LoopbackSubtitleTap.swiftiosApp/iosApp/Screens/Player/Subtitles/AVPlayerEmbeddedSubtitleExtractor.swiftiosApp/iosApp/Screens/Player/Subtitles/SubtitleRenderer.swift
🚧 Files skipped from review as they are similar to previous changes (2)
- iosApp/iosApp/Screens/Player/Subtitles/AVPlayerEmbeddedSubtitleExtractor.swift
- iosApp/iosApp/Screens/Player/AVPlayerRoute/AVPlayerBackend.swift
…d settings UX Rendering fixes: - effectiveOutlineColorHex now always uses the user's outline color; the legacy "outline" background style borrowed the background color, which contradicted web/Android and every preview (the enabled Outline Color control silently did nothing in that mode). - Legacy "outline" background style folds into the Text Outline axis in sanitized() (backgroundStyle none + textOutline true); the enum case stays for wire-format decode compatibility. Pickers now offer Box / Drop Shadow / None only, so the UI has one outline concept. New: Match Device Settings appearance source (MediaAccessibility). SystemCaptionAppearance maps the user's Subtitles & Captioning preferences (colors, background opacity, edge style, size, font) onto SubtitleAppearance, honoring per-field .useValue behavior. Device-local toggle in PlayerSettings; effectiveSubtitleAppearance routes it to both backends; live re-apply on the MA settings-changed notification; any manual edit switches back to Silo styling. Settings UX unification across the four surfaces: - Shared SubtitleAppearancePreview (directional-shadow glyph outline) now shown in iOS/macOS Settings, the iOS player sheet, the tvOS settings pane, and the tvOS font picker (whose old preview drew "outline" as a rectangle stroke around the caption block). - tvOS adopts touch-it-and-it-applies coupling everywhere: picking an outline color enables the outline, picking background color/opacity switches to Box (previously the settings pane let you edit values the style ignored, silently doing nothing). - Selecting Box with 0% opacity bumps to the default 75%. - iOS/macOS: 24pt color swatches replaced with full-row pickers, background opacity is a slider committed on drag end, low-contrast hint for dark text without box/outline, footer notes that authored ASS and image-based subtitles keep their original appearance. All three platforms build; 474 tests pass (adds outline-migration, legibility, and MediaAccessibility mapping coverage). Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_0146hwg1Q15YdeUhd9f37NWA
…hdog tick A 3 GB Apple TV 4K capture (Run-SiloTV-2026.07.03_18-56-35) showed the loopback route memory-terminated 15 s into a 4K DV P7 + TrueHD + PGS title with nothing in the log attributing the growth. Add temporary [CMP-MEM] instrumentation to the existing 3 s watchdog telemetry: - phys_footprint via task_info(TASK_VM_INFO) — the number the per-process jetsam limit is actually enforced against (not resident_size) — plus os_proc_available_memory headroom (iOS/tvOS only; macOS reports -1). - App-managed pools alongside it: segment-store resident bytes and the source-proxy cache (injected as a closure — the proxy is owned by PlayerViewModel). Emitted on both the OSLog line and the devicectl-visible vod-state print, so a memory-termination capture shows which pool was growing as avail walks to zero. Same temporary-diagnostic convention as [CMP-SUBDIAG]/ [CMP-SEAM]; to be stripped with them before merge. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ead race The VOD producer window is segment-count based (target + 10), blind to segment size. At Blu-ray-remux sizes (~30 MB / 4 s segments) that authorizes ~300 MB of produced-ahead media, which the producer races through at wire speed — a 3 GB Apple TV 4K capture measured ~300 Mbps sustained / 460 MiB read in 14 s before jetsam killed the process (4K DV P7 + TrueHD + PGS title). Layer a byte gate on top of the count window in vodProducerMayAppend: - vodForwardByteBudget parks the producer once produced bytes ahead of the consumer target reach the budget, counting memory-resident, in-flight-spill, AND spilled segments — a spill-exempt gate would let the count window keep authorizing wire-speed reads straight to disk. - vodForwardMinSegments = 3 floor: the next segments past the target are always producible regardless of byte state, so stale forward segments retained across a backward seek can never starve the consumer. Liveness rides the existing 200 ms poll in waitForVODWindowIfNeeded. - AVPlayerBackend passes the tiered budget: 96 MiB on constrained (<=3.5 GB) tvOS devices, 192 MiB otherwise. On the crash title (~65 Mbps) produce-ahead beyond the fetch high-water drops from ~300 MB to ~96 MiB (~12 s of media); the source read rate collapses to roughly consumption rate once the pipeline fills. Low-bitrate sources never hit the byte gate — the count window remains their binding constraint, so ordinary content is unchanged. The EVENT-mode generated-ahead throttle (90/60 s) is also byte-blind but is the legacy path and untouched here. Co-Authored-By: Claude Opus 4.8 <[email protected]>
The evictor's minimumSegmentsToKeep = 8 floor is count-based and blind to segment size — the same defect class as the VOD forward window. At Blu-ray-remux sizes (~30 MB / 4 s segments) it silently overrides the memory budget: a [CMP-MEM] capture on a 3 GB Apple TV 4K showed the store steady at 210-239 MiB against its 96 MiB constrained budget, ~65% of the process's steady-state footprint. The floor is a serve-latency optimization (recent re-fetches come from RAM, not spill), not a correctness requirement. Replace the bare count check with a shared floor predicate, used by both the evictor and the append-admission simulation so relief can never satisfy a looser criterion than the gate it unblocks: - The 8-segment warm tail holds only while resident bytes stay within 1.5x the memory budget; past that, eviction continues. - A hard minimum of 2 residents (current segment + successor) holds regardless of bytes. - Small segments never feel the byte clause — the budget check terminates eviction first, so ordinary content is unchanged. On the 3 GB box this brings the store from ~240 MiB to <=144 MiB. Tests: two new floor tests (large-segment byte cap incl. spilled segments staying servable; small-segment warm tail preserved). Three existing tests had expectations incidentally coupled to the old 8-resident arithmetic (spill counts / retention-budget sums), updated to the new floor with their original invariants intact. Co-Authored-By: Claude Opus 4.8 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a60e000fab
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| reason: String = "stall" | ||
| ) { | ||
| guard case .some(.localDVLoopback(let spec)) = currentSourceStrategy, | ||
| guard case .some(.siloLoopback(let spec)) = currentSourceStrategy, |
There was a problem hiding this comment.
Keep VOD stalls on the VOD recovery path
When a .vodPlan SiloPlayer item posts AVPlayerItemPlaybackStalled after initial load and the produced playlist is still ahead, this guard admits it into the legacy loopback recovery path, which calls load(strategy: .siloLoopback(spec.reanchored(...))) and tears down the static VOD item/store instead of using the new in-place VOD recovery ladder. That regresses VOD seek/stall recovery back to full reanchor behavior for exactly the route this change is trying to keep stable; exclude .vodPlan here or dispatch to performVODStallRecovery.
Useful? React with 👍 / 👎.
| guard subPumpRendersInFlight < 2 else { | ||
| subDiagSkippedTicks += 1 | ||
| return | ||
| } |
There was a problem hiding this comment.
Keep bitmap cue updates running when text renders backlog
With both a text subtitle track and a bitmap track active, this early return skips the bitmap path below whenever libass rendering has two frames queued. On heavy text renders this can leave PGS/DVD cue layers stale or uncleared even though bitmap cue compositing is independent and cheap; skip only enqueuing the text render and continue to pumpBitmapCues so mixed subtitle playback stays in sync.
Useful? React with 👍 / 👎.
Bitmap cues rendered purely from the decoder-supplied normalizedFrame, ignoring every SubtitleAppearance preference — most visibly, no backing box while styled text sits in one. Font, text color, and outline are baked into the source pixels (unfixable without OCR), but the three geometric/compositing preferences can be honored, matching what the styled-text path gives the same settings: - Size: cues scale by the font-size ladder ratio (user preset / default), anchored to the edge the cue is authored against — dialogue grows up from its baseline, top-region signs grow down. - Position: bottom-region cues follow the placement preset (Bottom keeps authored PGS baselines; Lower Third / Top reposition). Top/mid-region cues — typically signs & typesetting whose placement is content — always stay authored. - Background: when the style is Box, each cue gets a padded, rounded backing layer in the user's background color and opacity. None / Drop Shadow keep the authored transparent look. Layout math stays in AVPlayerBackend (BitmapCueStyle + placement builder, keyed into BitmapCueRenderKey so preference changes re-render on the next pump tick); SubtitleOverlayView grows a BitmapCuePlacement type and container+image layer pairs (UIKit + AppKit). Settings footer copy updated on all four surfaces. Note: diverges from silo-android, which leaves image subs fully authored — Android alignment tracked as a follow-up. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Bitmap subtitles on the loopback route stopped rendering ~5 s after enable. The extractor's side connection has to re-download the entire source interleave just to skim subtitle packets: the first seconds come free from the shared proxy cache (the writer just read those bytes), then it hits origin fetches, falls behind realtime at Blu-ray bitrates, and cues arrive too late to display. Same failure 6e5e452 measured and fixed for text tracks — bitmap was left on the extractor. Extend the writer tap to bitmap (PGS/DVD) streams, decoded on demand: - Bitmap streams join the demuxer keep-set (their packets are a rounding error against the interleave already being read) but are only DECODED while one is selected — no persistent RGBA store, unlike the text tap; decoded cues feed the existing bounded BitmapSubtitleCueStore directly. - Decoder opens lazily on the first selected packet, seeded with the container video dimensions as canvas fallback. Decode + palette→RGBA conversion runs inline on the mux thread (milliseconds, cues seconds apart). PGS missing-END repair and trim-on-composition semantics mirror the extractor. - Selection is a thread-safe box read per packet; the backend re-applies it to every new writer so it survives producer restarts, and both read loops (main + bootstrap) tap bitmap packets. - selectSubtitleTrack routes loopback bitmap tracks to the tap ahead of the extractor branch; the extractor remains the path for sidecar and non-loopback routes. Known v1 gap: a mid-playback enable starts cues at the producer's current read position, so the first cue can lag by the produce-ahead window (~12 s at Blu-ray bitrates); enable-at-start and post-seek restarts are immediate. The extractor-as-bridge for that window is a possible follow-up. Co-Authored-By: Claude Opus 4.8 <[email protected]>
The demuxer bitmap tap decoded cues but none rendered. The cue store prunes everything older than newest_fed_cue - 30 s (tuned for the extractor, which decodes at the playhead). The tap instead feeds from the producer's read head, which the produce-ahead byte gate bounds tens of seconds ahead of the playhead (measured generatedAhead ~102 s): the store received cues stamped at the frontier and pruned every cue between the playhead and the frontier before playback reached it, so activeCues(at: playhead) was always empty. Parameterize openBitmapTrack's store (default 30 s / 128 unchanged for the extractor) and open the loopback tap's store at 300 s / 512 cues. That keeps producer-ahead cues alive until the playhead reaches them; 512 cues (sorted by start, so the cap drops oldest-behind-playhead first, never the ahead cues) bounds worst-case memory ~25 MB. Covers the common cases — subtitles on at start, resume, and post-seek all anchor the producer at the playhead so cues decode from there forward. Known gap unchanged: enabling PGS mid-playback while the producer is already far ahead leaves [playhead, frontier] undecoded until the frontier is reached. Co-Authored-By: Claude Opus 4.8 <[email protected]>
PGS only appeared many seconds into playback even when selected at start/resume: the writer's read loop races ahead of the main-thread selection call, and the tap dropped every bitmap packet read before the selection landed — cues only existed from the read head onward, so nothing rendered until playback caught up to that frontier. Fix: keep a rolling per-stream backlog of compressed bitmap-subtitle packets (360 s / 16 MiB caps, all streams, mux thread only). Every non-nil selection schedules a drain; the mux thread replays the selected stream's backlog through the decoder into the freshly opened cue store before continuing live decode. The drain also runs inside the VOD backpressure park loop, so a mid-playback enable doesn't wait for the next append slot. This closes the previously documented mid-playback [playhead, frontier] gap too — the backlog spans the produce-ahead. Also close the selection-before-availability race: a subtitle selection that arrives before onBitmapSubtitleTapTracks fell through to the extractor (which can't keep up at Blu-ray bitrates) and stayed there; the availability hop now re-routes the current selection to the tap. Plus: ease the tvOS default subtitle size — Large 63→58, between the old Large (a little too big) and Medium 51 (a little too small).
Authored Blu-ray PGS reads a notch larger and sits a broadcast-safe notch higher than the text ladder's default rung, so at the same preset bitmap cues didn't line up with SRT. Two calibrations: - Scale: 0.85 authored-size compensation across the whole bitmap ladder, so the default preset visually matches the text render. - Position: cues whose authored bottom edge falls in the bottom band (maxY >= 0.75) get their group's bottom edge shifted onto the same margin the text path uses (60/1080 tvOS, 30/1080 elsewhere). The shift is computed per composition, not per rect, so multi-rect cues keep authored line spacing; floating signs above the band keep their authored placement; Lower Third/Top presets are untouched.
Resume-time macroblocking root cause: after a matroska seek, libavformat leaves DTS unset on the first has_b_frames video packets (cold reorder buffer). The timestamp repair only fixed keyframes and the callers dropped everything else — discarding the reference P-frame right after the resume anchor's IDR, so the whole first GOP decoded against a missing reference (verified: the produced resume segment was missing the frame and ffmpeg reported "co located POCs unavailable"). Now a PTS-only follower gets its DTS crammed one tick above the previous video packet instead of being dropped; PTS is never touched. Also validate the resume segment's opener in the bitstream before the plan is published: container key flags and cue indexes can call a frame "key" that is not a real random-access point (open-GOP H.264 I-frames, stale MKV cues). H.264 requires a true IDR (VCL NAL 5), HEVC any IRAP. When validation fails, walk back to the nearest earlier true-RAP boundary and coalesce the intervening plan segments so the segment AVPlayer cold-decodes on resume opens clean — never forward, which would visibly skip content.
With "show forced subtitles" enabled and a preferred subtitle language set, the auto-resolver picked the forced (signs-only) track over the full dialogue track — subs showed a few title cards and then went silent for every dialogue scene (Agent Kim ep4, 43-track MKV). Forced tracks now only win the one case they exist for: auto mode with the audio already in the preferred language, where full subs are redundant and signs/foreign-dialogue overlays still apply (this branch also brings the resolver to parity with Android, which selects forced there instead of disabling). A language-matched full-subs pick always takes the non-forced track. Android's bestAutoSubtitleTrack has the same preferForced ordering bug and needs the matching fix.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ed7219f816
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if let trackId = selectedControlledSubtitleTrackId, | ||
| tapServesEmbeddedTrack(trackId) { | ||
| activateTapSubtitleTrack(trackId: trackId, slot: .primary) |
There was a problem hiding this comment.
Refill bitmap subtitle cues after seeks
When a SiloPlayer bitmap subtitle track is selected and the user seeks within an already-produced/cached VOD window, flushOnSeek() clears the bitmap cue stores but this resync path only re-feeds text tap tracks. Because the bitmap tap remains selected without scheduling a backlog replay, PGS/DVD cues can disappear until the producer happens to reread subtitle packets, or indefinitely for backward/cached seeks; handle bitmapTapServesEmbeddedTrack(trackId) here by reactivating the bitmap tap/draining its backlog after the seek.
Useful? React with 👍 / 👎.
An A12 Apple TV (4K 2nd gen) pegs a full core during high-bitrate 4K DV loopback playback. Per-thread CPU attribution on-device showed two addressable costs stacked on top of the pipeline's baseline: - Every subtitle cue change composited the full 3840x2160 canvas: a 33 MiB clear, a per-pixel Swift blend, a 33 MiB makeImage copy, and a full-frame texture upload — 100-290 ms per change, ~65 ms even for a cue ending. The canvas is now sized to the union of the rects libass actually painted and the overlay positions its contents layer at that rect (AppKit variant flips into bottom-left layer space). On-device: cue-start renders 100-290 ms -> 38-121 ms, cue-end clears -> ~0.2 ms, no more skipped pump ticks during dialogue. - The producer's mux queue ran at .userInitiated, contending with mediaserverd's DV decode and the UI for the two performance cores during 120-160 Mbps produce-ahead bursts. It runs 20-60 s ahead of the playhead, so it now runs at .utility and prefers the efficiency cores. Far seeks still recover in <=3 s on the A12 (~2.2x realtime refill), matching pre-change hardware numbers. Adds temporary [CMP-CPU] instrumentation (PlayerCPUDiagnostics) that emits exact per-thread CPU (dispatch-queue-label attributed) plus whole-device per-core load alongside the existing 3 s transport state line, so future captures name the hot queue instead of a total. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01QTcsvekuFPdBnpA3qd7ApF
Round two of the A12 (Apple TV 4K 2nd gen) CPU work, targeting the per-frame costs that profile7_to81 + TrueHD titles stack on the mux thread and the residual libass glyph-raster cost: - The P7->8.1 transform now compacts packets in place: BL NALs lead the packet and stay put, dropped EL NALs open a gap only behind them, and the RPU is rewritten in its slot (source bytes copied out first, so the overlapping write is safe; write never passes read because drops only widen the gap and the RPU guard checks its slot). Replaces two full-frame copies + two NAL walks + a packet alloc per video frame. The old rebuild path remains as the fallback for a converted RPU that outgrows a pristine packet's slot. - libass rasterizes at 1080p on AppleTV13,x and earlier (the 3rd-gen A15 keeps full 4K): at UI scale 2 every glyph was shaped and filled at 4x the pixel area, which dominated cue-change cost after the bounded-box compositing fix. The overlay layer upscales the smaller composite instead. - The TrueHD/FLAC bridge reuses one decoded AVFrame across frames (receive_frame unrefs it), dropping an alloc/free per decoded frame. - Segment accumulation stops realloc-thrashing: each new segment reserves the previous segment's size up front (pendingSegmentBytes otherwise re-walks the doubling ladder to ~35-45 MB every 4 s), and boxBuffer keeps its capacity across full drains. Hardware-validated on the 2nd-gen device with a 4K DV P7 + TrueHD MKV: DV engages (AVPlayer reports Profile 8 Level 6), audio bridges clean, zero mux errors, subtitle renders during dialogue dropped from avg 133 ms (max 289) at the pre-round-one baseline to avg 39 ms (max 96) with most under 20 ms, and the user confirms subs stay sharp. 483 tests pass; iOS/tvOS/macOS build. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01QTcsvekuFPdBnpA3qd7ApF
Every playback session leaked its PlaybackSourceResource and the proxy cache budget behind it (~130-250 MiB per title switch or reanchor). Deinit tracing across title switches showed the whole pipeline dying on teardown — writer, store, server, proxy, backend, view model — while the resource and cache never went: the proxy's detached serve tasks hold strong self for their whole body, nobody ever cancelled them, and a task parked in an await that outlives the session (a send withheld by TCP backpressure, a fetch racing session invalidation) kept the resource alive forever. On the A12 one switch put the app at ~1 GiB, the memory compressor saturated the E-cores the .utility producer runs on, refill lag followed, and mediaserverd eventually jetsammed out from under AVPlayer (-11819, the "loopback crash" that fell back to PlayerCore). - The resource tracks serve tasks and cancels them in stop(); a finish/registration race parks ids in a reconciliation set. - send() wraps its continuation in withTaskCancellationHandler and cancels the connection on task cancellation, so a backpressure- parked contentProcessed completion fires and the await resumes. - fetchRange() refuses to start once stopped — creating a task on an invalidated URLSession can hang its async continuation. - handle() rejects connections that race teardown. Adds temporary [CMP-LIFE] deinit tracers on the session-scoped classes and [CMP-SRV] serve start/exit pairs (an unpaired start is a parked task) for future multi-title captures. Validated on-device across title switches: full generation deinits including resource + cache, footprint 487 MiB with the second title playing (was ~957 MiB), 483 tests pass, three platforms build. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01QTcsvekuFPdBnpA3qd7ApF
|
LGTM |
DDP-Atmos (E-AC-3 + JOC) stream-copied bit-exact through the loopback was classified by AVFoundation as plain E-AC-3 5.1, so Atmos never engaged. Five stacked fixes, adapted from the retracted PR #64 after validating each against FFmpeg sources and AetherEngine's shipping Atmos path: - Rewrite the init segment's dec3 box into the ETSI TS 102 366 layout and append the TS 103 420 JOC extension AVFoundation keys on. The vendored FFmpeg 7.1 muxer writes 5 reserved bits where the spec has 3 and no extension (verified against n7.1 vs n8.1 mov_write_eac3_tag; output pinned byte-identical to FFmpeg 8.1's). Gated on copy-mode E-AC-3 with codecpar.profile == AV_PROFILE_EAC3_DDP_ATMOS. - Start AVPlayer from the master playlist: Atmos MAT output is a master-variant-level grant. Kill switch back to media-direct: player.apple.loopback_master_start_enabled = NO. - Emit RESOLUTION and always emit FRAME-RATE on the master variant (AVFoundation drops a PQ variant with no FRAME-RATE, -1002). - Clamp the HEVC CODECS declaration to Main tier with no constraint suffix; a faithful High-tier string is variant-filtered. - Extend the pre-item display-mode settle wait to fresh DV criteria applies: tvOS 26.5 validates the master's VIDEO-RANGE against the panel's current mode synchronously (-11868 mid-switch). Also declares setSupportsMultichannelContent(true) on the playback audio session (AetherEngine parity; PlayerCore already does). 7 new tests pin the dec3 rewrite bit-for-bit, including the FFmpeg 8.1 ground-truth vector for the on-device streaming-Atmos payload. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01RdnjmQmP9WuJdCKa4yKt6L
…lass Opening the player menu spiked CPU on the A12 Apple TV: the HUD panels (.regularMaterial) and control capsules (.ultraThinMaterial) are backdrop-sampling effects, so the render server re-samples and re-blurs the covered video region on every video frame for as long as the menu is up — pure per-frame overhead on a 4K surface. All player-over-video glass (HUD panels, control capsules, hold-seek pill, notice overlay, PlayerView chrome) now routes through one siloPlayerGlass modifier: low-power Apple TVs draw a non-sampling translucent fill (visually close over dark video, free), everything else renders Silo's Liquid Glass via the existing siloGlass path — which also moves the player off the last legacy materials. The AppleTV14,x cutoff moves into a shared DevicePower helper, now used by both this gate and the subtitle raster cap. 490 tests pass; iOS/tvOS/macOS build. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01QTcsvekuFPdBnpA3qd7ApF
Cluster-by-cluster comparison of AetherEngine's fixed defects against the silo-apple loopback + PlayerCore stack: 18 gaps (1 high, 15 medium, 2 low) where AE enforces an invariant we don't, each with the AE symptom, our concrete exposure scenario, and a fix naming our files/functions. Produced by a 5-phase agent workflow (mine 277 AE fixes → cluster → audit vs our code → adversarial verify); 15 gaps verified, 3 marked unverified. Markdown for review + a self-contained HTML report for sharing. Excludes today's moov-wedge fix (359d20c) and the PR #52/#66/#68 stack as landed. Co-Authored-By: Claude Fable 5 <[email protected]>
Summary
Inverts the Apple playback engine hierarchy: the AVPlayer loopback — now named SiloPlayer — becomes the primary engine for all H.264/HEVC direct play (SDR included), serving a static VOD playlist from a load-time segment plan instead of the growing EVENT playlist, with demand-driven producer restarts behind a stable player item. PlayerCore becomes the codec-tail fallback (its codec gate is now open: VP9/VP8, AV1, MPEG-4 ASP, VC-1 play in-process). Server transcode remains the last resort.
Direction and mechanisms derive from the loopback-primary plan written after reviewing AetherEngine (LGPL — patterns and constants ported, no source copied), which demonstrated that the loopback's historical startup/stall reliability problems are solvable and worth solving rather than abandoning the route.
What changed, by stage
[CMP-TTFF]startup telemetry on both engines; premature source EOF classified into the outage-recovery path (pure, tested classifier).LoopbackSegmentPlan(keyframe-index trust gates: largest gap ≤ max(4×target, 30 s) AND coverage ≥ target; uniform-stride fallback; first-keyframe anchoring),LoopbackSegmentCutter(decode-order, PTS-keyed keyframe-gated cuts; RASL-safe),LoopbackRestartCoalescer(one in-flight + one settled pending target; authoritative recovery re-bases own the slot).+empty_moov+default_base_moof+frag_custom+delay_moov+frag_discont,use_editlist=0,avoid_negative_ts=disabled; explicit plan-driven fragment cuts; plan-indexed segment naming; one static VOD playlist per session.h264/hevc-sdr_loopback_startup_unreliableblockers lift under the gate (the VOD model removes the growing-playlist startup dependency they existed for).player.apple.siloplayer_primary_enabled; explicitfalse= kill switch to the EVENT path) + full rename:siloPlayerLoopbackroute,LoopbackSegmentWriter/Store/Server. In-memory identifiers only; no persisted keys or wire strings changed.avcodec_find_decoderprobe → existing software path. Known limits documented in-code (8-bit SW output, single-threaded decode).Validation
Rollback
Set
player.apple.siloplayer_primary_enabled = falseto return to the EVENT serving path and pre-existing routing; the planner fallback trail (SiloPlayer → PlayerCore → server transcode) is unchanged and exercised.Follow-ups (tracked, non-blocking)
10-bit (P010) software output + decode threading for the codec tail; display criteria for non-DV HDR on tvOS 26.5; producer-session seam decode-ramp polish; abandoned-fetch resolver early-exit.
🤖 Generated with Claude Code
https://claude.ai/code/session_01GjbssMwqt7r9emGaZJ68Cj
Summary by CodeRabbit