Skip to content

fix(live): preserve replay evidence across native and software recovery - #747

Merged
superuser404notfound merged 4 commits into
superuser404notfound:mainfrom
yucelokan:fix/live-replay-recovery
Oct 13, 2026
Merged

superuser404notfound merged 4 commits into
superuser404notfound:mainfrom
yucelokan:fix/live-replay-recovery

Conversation

@yucelokan

@yucelokan yucelokan commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Keep live source replay from showing already-admitted pictures or damaging the reference chain at a truncated transport boundary. Preserve source, viewing position and DVR identity through recovery, and repair sustained native video stalls independently of advancing audio.

What changed

  • Verify bounded, paired-track compressed-packet identity before remux, recording, software clock folding or DVR storage; preserve unrelated timestamp resets and ambiguous media.
  • Retain exact history and cached playback through source renewal. Expose liveSourceReplayExhausted / retryLiveSourceRecovery() so applications own retry timing.
  • Quarantine damaged outgoing PES packets across queued pictures before rollback. After verification, reconcile unflagged partial/returning video copies at both original DTS and PTS, and restore decode order.
  • Keep untimed fragments behind the same damaged boundary. They previously escaped quarantine, acquired synthetic timestamps and caused the intact returning reference picture to be discarded.
  • Add numeric boundary/replacement diagnostics and optional SDR native decoded-output observation, with PiP/background/external-playback exclusions.
  • Recover a previously visible but persistently unready layer with bounded current-position consumer repair. Separately opt into ready-but-stalled decoded-output repair using nativeVideoFrameRecovery (default off); diagnostics alone remain observational. Require fresh evidence and healthy pictures to rearm; exclude short gaps, seeks, pause, hidden layers and starvation.
  • Keep these dependent corrections together because admission, retained-history recovery, observation lifecycle and same-position consumer repair share state. Shipping one without the others could release a damaged boundary, admit cached media twice or lose the viewer's position. Application UI, logging projections, retry delays and resource budgets remain downstream.

Test plan

  • Local device / OS: Apple M1 Pro, macOS 27.0.1 (26A434), Xcode 27.0 / Swift 6.4. Standalone PR based on main 23f548c0, FFmpegBuild 3.7.1.
  • Functional revision 48c6aafd (current head adds validation documentation only): swift build and complete swift test passed: 781 XCTest cases (one optional skip), 4,376 Swift Testing tests in 603 suites, zero failures. The complete local strict-pool run also passed all 4,376 Swift Testing tests.
  • Regression media: generated MPEG-TS, H.264 High 32×32 / 25 fps / SDR, ten-second closed GOPs and two B-frames, AAC-LC stereo 44.1 kHz. Five seam variants include flagged intact bytes and actual predicted-picture/keyframe truncation at two byte offsets. All 800 software-decoded pictures match the clean source; native VideoToolbox decoding of the actual remuxed stream matches all 800 BGRA picture hashes and presentation timestamps.
  • Failing-before / passing-after: a truncated unflagged access unit previously produced 801 packets instead of 800 and native decoder error -8969. A separate untimed-fragment reproduction produced missing references and FFmpeg decode-error flags. Both are fixed on native and software admission paths; an unverified boundary still preserves every packet.
  • Actual AVPlayer experiment on integrated develop: generated 45 s MPEG-TS, H.264 High 320×180 / 25 fps / 600 kb/s / SDR, ten-second GOPs, two B-frames, AAC-LC stereo 44.1 kHz. Truncate an outgoing access unit at 24.76 s and append an earlier source prefix. Before correction, decoded output paused for 5.310 s until the next IDR. After correction, a 38 s local HTTP/native-HLS run had no decoded-output gap; all 1,125 VideoToolbox-decoded pictures/timestamps matched the clean source. The headless layer was ineligible for recovery, isolating the packet fix.
  • Recovery policy: short observed device gaps do not seek; sustained advancing-clock stalls enter the bounded nudge/reload ladder. Tests cover unavailable/stale sampling, sparse video, stopped clocks, seeks, exhausted budgets, healthy rearming and temporary waits during repair.
  • Physical-device evidence before this follow-up: WUW TV, the downstream application, was tested at app version 1.1.15, app build 13, using the AetherEngine 7.35.1-based fork at commit a7933553, on a Mac running the iPad-compatible app (macOS 27.0.1), iPhone/iOS 26.6.1, iPad/iPadOS 26.6.1 and Apple TV/tvOS 27.0. The 26 archived parts contained 8,465 records; 219 older-build records were excluded. Live H.264 High 720p/1080p25 MPEG-TS + AAC-LC and MKV H.264 Main 1920×800/23.976 + AAC-LC 5.1 were exercised, including seeking, resume and five PiP return paths. There were 27 verified replay removals with no unsolicited sampled backward clock movement. Remaining video-output gaps exposed the two admission cases and the ready-layer recovery blind spot fixed here.
  • Coverage boundary: the four-device run above exercised the earlier integrated fork at a7933553. The final corrections at functional revision 48c6aafd were developed from those logs and subsequently validated by the local decoder/playback regressions and CI described above; that final revision has not yet been tested on all four physical devices. The application version/build identifies the field-test session, not the engine release or the final PR revision. A decoded-output gap is not itself proof of an identical screen freeze. Private raw packets were unavailable, so the deterministic reproductions do not establish the cause of every field gap.

Detailed, sanitized device matrix, timeline correlation, reproduction and limits: validation report. No private media, provider addresses, credentials or support identifiers are published.

CI follow-up

The first CI attempt passed the normal macOS suite, all new native-decoder cases in both modes, iOS/release CLI, tvOS/visionOS and docs. Its strict-pool suite had one failure in the unchanged SourcePrewarmAdoptionTests.fullyWarmedSourceOpensWithNoConnection (two HTTP requests instead of one). A complete local strict-pool rerun passed. No unrelated prewarm code or assertion was changed or disabled; the documentation-only follow-up records this. The fresh run passed all four checks at efd30fce, including the full normal and strict-pool macOS suites: CI run. The original intermittent result remains documented.

Checklist

  • CHANGELOG.md updated
  • Conventional Commit messages
  • Engine defects fixed in the engine
  • Intentional public API changes documented

Retain source identity, cached media and transport intent through replay
recovery. Verify paired-track overlap before admission, including damaged
outgoing PES boundaries and clean pictures queued before timestamp rollback.
Keep intact replacements once in video decode order and preserve unverified
fresh media under bounded cadence-aware lookahead.

Apply the same admission before software clock folding, recording and DVR
append. Expose explicit retry ownership to hosts and opt-in SDR native output
diagnostics that remain scoped to the session across item swaps.

Packet identity, retained recovery and diagnostic cadence share these
primitives, so this is one independently buildable correction rather than
partially released dependent fixes. Document the public contracts and include
encoded MPEG-TS, cancellation, recovery and observation regressions.

Validation: complete macOS build and tests, 778 XCTest cases (one optional
skip), 4,361 Swift Testing cases, 99 strict-pool regressions, and iOS/tvOS
library builds passed. Integrated physical-device sessions are documented in
the PR; the final lookahead adjustment has reproducible regression coverage.
@yucelokan
yucelokan force-pushed the fix/live-replay-recovery branch from 596e931 to 1b0cb2d Compare October 12, 2026 15:29
Reconcile verified returning access units before timestamp repair and quarantine untimed fragments with the damaged boundary. Preserve ambiguous source data. Add opt-in bounded native video-progress recovery, privacy-safe seam diagnostics and native-decoder regression coverage. Document four-device evidence and the failing-before/passing-after reproductions.
superuser404notfound pushed a commit that referenced this pull request Oct 13, 2026
…SourceReset (#747)

The verified-replay exhaustion from #747 published only the new
liveSourceReplayExhausted subject. A host that never subscribed to it (every
existing integrator, Sodalite on a Jellyfin transcode respawn among them) held
the last frame for good, where it used to retune on liveSourceReset. The new
subject now fires only under LoadOptions.hostRetriesExhaustedLiveReplay; by
default the session reports the exhaustion through onLiveSourceReset.

The layer-unready presentation repair was wired for every native session,
VOD included, and an in-place swap that joins audio-first while video waits
for its IDR could earn it a nudge and an item replacement. It now runs only
under nativeVideoFrameRecovery, like the decoded-output half.

CHANGELOG: the PR's entries collapsed into one under Unreleased; three of them
had landed under 7.35.0.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01WJcXkGQrMiBPixVEFTSBJS
@superuser404notfound
superuser404notfound merged commit 397dcf7 into superuser404notfound:main Oct 13, 2026
4 checks passed
@superuser404notfound

Copy link
Copy Markdown
Owner

Merged in 397dcf7, thanks a lot @yucelokan. The replay identity work, the truncated-PES regressions and the validation report are excellent, and the long-GOP fixtures that compare every decoded picture are a real gain for the test suite.

Two defaults changed in the follow-up 7a6fc2f, both so that a host that does nothing new behaves as before:

  1. Exhausted verified replay reaches existing hosts again. As merged, the exhaustion published only liveSourceReplayExhausted. A host that never subscribed to it (every current integrator, including Sodalite on a Jellyfin transcode respawn) would hold the last frame for good, where it used to retune on liveSourceReset. The new subject now fires only under the new LoadOptions.hostRetriesExhaustedLiveReplay (default false); without it the same exhaustion publishes liveSourceReset. The in-engine reopen that keeps cache and history runs either way. WUW TV would set the flag to keep the retained-history retry.
  2. Layer-unready presentation repair is opt-in. It was wired for every native session, VOD included. An in-place swap keeps hasPresentedVideo and the attempt count, so a live item that joins audio-first while video waits for its IDR could earn a nudge and then an item replacement. It now runs only under nativeVideoFrameRecovery, together with the decoded-output half, and the [NativeVideoHealth] lines follow either flag.

The CHANGELOG entries are collapsed into one under Unreleased (three had landed under 7.35.0 after the release cut). Full suite green on both runners (XCTest 764, Swift Testing 4412). Not released yet.

superuser404notfound pushed a commit that referenced this pull request Oct 13, 2026
…aylist when a GOP outgrows the seal

Conflicts with #747 resolved by keeping both: the reopen/exhaustion handlers and the renewal handler
are registered side by side, and reloadStalledConsumerItem takes both preserveLivePosition (#747
presentation repair) and replacementURL (renewal); preserveLivePosition still wins the rejoin.
The CHANGELOG line moved from 7.35.0 to Unreleased.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01WJcXkGQrMiBPixVEFTSBJS
@yucelokan

Copy link
Copy Markdown
Contributor Author

Thank you for building and maintaining AetherEngine, and for taking the time to review and merge our contributions!

I’m happy to be using it in WUW TV and glad I could give something back to the project. Really appreciate your work and everything you’re sharing with the community! 🙌 @superuser404notfound

@cmcpherson274

Copy link
Copy Markdown

A data point from an Apple TV for the truncated-boundary work in this PR, which reached us in 7.36.0: it removed the repeated seconds we could stage on a reconnect, and on one cut of three the returning picture did not supersede the outgoing copy.

Setup. Apple TV 4K (3rd generation, AppleTV14,1), tvOS 26.6, Debug builds of our app, our loopback route. A multiview tile plays a live news channel from Jellyfin as a plain MPEG-TS URL, read by the engine's own HTTP reader. A pass-through relay of ours closes the tile's connection once, about 60 s after its first byte (115 to 117 MB in); the reader reconnects, its first new data arrives 86 to 114 ms after it opens the new connection, and the server re-serves about 5 s it had already sent. Three cuts on each of 7.35.1 and 7.36.0, in one sitting on 15 October, each in a fresh process.

cut 7.35.1 7.36.0
1 overlap unconfirmed: track diverged after 307 video + 240 audio matches, then video timeline rebase (live): jumpTicks=-460960 and a [DISCONTINUITY] segment: the re-served 5.12 s muxed again damaged packet held, [ReplayVideoBoundary] … superseded=1, overlap resolved: removed 298 video + 234 audio packets across 4.95s: nothing muxed again
2 overlap resolved: removed 293 video + 231 audio packets across 4.87s, then video dts non-monotonic at source: orig=5714584 lastValid=5716085 … → bumped to 5716086 damaged packet held, [ReplayVideoBoundary] … superseded=0, overlap resolved: removed 293 video + 232 audio packets across 4.87s, then video dts non-monotonic at source: orig=5693563 lastValid=5693563 … → bumped to 5693564
3 overlap unconfirmed: track diverged after 298 video + 233 audio matches, jumpTicks=-447447, [DISCONTINUITY]: 4.97 s muxed again damaged packet held, superseded=1, resolved across 4.95 s: nothing muxed again

On all three 7.36.0 cuts FFmpeg's Packet corrupt warning names a video dts one frame (1501 or 1502 ticks) after the packet the guard held (flagged 5737106, 5693563 and 5711581; held 5735605, 5692061 and 5710079). On cuts 1 and 3 the returning picture superseded the outgoing copy. On cut 2 it did not (superseded=0), and a second picture at the flagged dts was bumped, the outcome the comment at LivePacketReplayGuard.swift:414-417 warns of ("Publishing both and bumping the second DTS poisons Apple's reference chain until the next IDR"; at 7.36.0, and the file is unchanged in 7.37.0, which we have not run). Cut 2 also differs in three lines: its overlap candidate line comes before the Packet corrupt warning (after it on cuts 1 and 3), it logs no live damaged boundary held line, and its boundary line reads retained=2 (3 on cuts 1 and 3). On 7.35.1, cut 2's last video dts before the bump was the flagged one (lastValid=5716085), and the returning picture behind it was bumped. 7.36.0, cut 2, in order (date and level prefix cut, nothing else changed):

20:10:19.153 [HLSSegmentProducer] live source overlap candidate: exact packet match after timestamp rollback; checking both tracks before output
20:10:19.153 [mpegts @ 0x124ee8900] [warning] Packet corrupt (stream = 0, dts = 5693563).
20:10:19.154 [HLSSegmentProducer] live damaged packet: stream=video action=held count=1 dts=5692061 pts=5695064 keyframe=false
20:10:19.268 [ReplayVideoBoundary] route=native damaged=1 replaced=1 unreplaced=0 retained=2 keyframes=0 superseded=0 untimed=0
20:10:19.268 [HLSSegmentProducer] live damaged packet: stream=video action=discarded count=1 dts=5692061 pts=5695064 keyframe=false
20:10:19.268 [HLSSegmentProducer] live source overlap resolved: removed 293 video + 232 audio packets across 4.87s; first new packet continues the existing timeline
20:10:19.269 [HLSSegmentProducer] video dts non-monotonic at source: orig=5693563 lastValid=5693563 pts=5702572 → bumped to 5693564

No reopen, host reset, stall or leaked server stream on either engine. We have no recording of the tile, so we cannot say what the bump did to the picture.

7.35.1 is our app's engine pin as of today (2026-10-16); 7.36.0 is the candidate, measured beside it.

@superuser404notfound

Copy link
Copy Markdown
Owner

Thank you, @cmcpherson274, this is a precise report, and the three lines in which cut 2 differs were exactly what located it.

What happened on cut 2. The returning connection's audio rolled back first and opened the replay check (overlap candidate before Packet corrupt). On cuts 1 and 3 the flagged video packet arrived before any returning match, so it opened a held damaged boundary, and the pictures behind it raised the retained video frontier. On cut 2 the check was already open, so that path never ran (hence no live damaged boundary held line). The flagged picture (5692061) and its unflagged, truncated successor (5693563) were buffered, but the retained frontier stayed at the last admitted picture. The returning copy of 5692061 was therefore the first returning video packet past the frontier and committed the batch (retained=2: the truncated outgoing 5693563 and the returning 5692061, superseded=0). The returning copy of 5693563 came one read later, outside the verified batch, and was bumped.

The one-frame offset you saw on all three cuts is FFmpeg's: Packet corrupt is logged on the truncated PES itself (libavformat/demux.c:587), and the parser then ORs that packet's CORRUPT flag onto the access unit it completes from it (demux.c:1291), which is the previous picture. So the flag lands one frame early and the truncated picture itself arrives unflagged, the case the comment at LivePacketReplayGuard.swift:414 describes.

Fix. 5aca553 on main: while the check is open and no returning video has matched yet, a video packet past the retained frontier is treated as an outgoing straggler. It raises the frontier and joins the pending set, bounded like a held boundary (0.5 s or two frame intervals, at most 64 packets). The returning copies of both pictures then land in the verified batch, and the returning picture replaces the truncated one. A new test replays your cut 2 order and fails on the previous code at the same point (finished on the returning copy of the flagged picture). Full suite green on both runners (XCTest 771, Swift Testing 4927). Not released yet.

On a retest, a cut of the cut 2 shape should log superseded=1 and no video dts non-monotonic at source line whose orig equals its lastValid.

@cmcpherson274

Copy link
Copy Markdown

Our retest of cut 2 on the device, against your criterion above: a cut of the cut 2 shape should log superseded=1 and no video dts non-monotonic at source line whose orig equals its lastValid. We ran 7.44.0, which carries 5aca553 unchanged (LivePacketReplayGuard.swift is the same file at 7.38.0 and 7.44.0), beside 7.36.0. The criterion held on all three 7.44.0 cuts of that shape. The one 7.36.0 cut of that shape in the same sitting did not show the miss, so these runs show the criterion holding on 7.44.0, not a difference between the two versions.

Setup. As in our comment above, but now on tvOS 27.0 (24J361); those runs were on tvOS 26.6. Apple TV 4K (3rd generation, AppleTV14,1), Debug builds of our app, 7.44.0 with none of its optional traits enabled; FFmpegBuild also differs between the two (3.7.1 and 3.9.0). A multiview tile plays a live news channel from Jellyfin as a plain MPEG-TS URL, read by the engine's own HTTP reader. A pass-through relay of ours closes the tile's connection once, 60 s after its first byte (115.3 to 116.8 MB in); the reader logs the connection's end 2 to 14 ms after the cut (the two machines' clocks, uncorrected), and the relay accepts the new connection 11 to 18 ms after the cut. Six cuts per version on the night of 20 to 21 October (US Eastern), the six 7.36.0 cuts first, each in a fresh process. We read a seam as the cut 2 shape when overlap candidate comes before Packet corrupt and no live damaged boundary held line is logged, and as the cut 1 shape (cuts 1 and 3 of our first comment) when Packet corrupt comes first and that line is logged.

cut 7.36.0 7.44.0
1 no overlap check: the server answered the reconnect after 3.17 s with timestamps starting again (video timeline rebase (live): jumpTicks=-5569064 srcDts=126000 …, then a [DISCONTINUITY] segment); AVPlayer logged playbackStalled 2.6 s after the cut and was playing for good 4.8 s after that cut 1 shape: retained=3, superseded=1, resolved across 4.99 s
2 cut 1 shape: retained=3, superseded=1, 5.01 s no overlap check: answered after 3.19 s, jumpTicks=-5593088 srcDts=126000, [DISCONTINUITY]; playbackStalled 2.5 s after the cut, playing for good 3.8 s after that
3 cut 2 shape: retained=2, superseded=1, 4.94 s cut 2 shape: retained=3, superseded=1, 4.85 s
4 cut 1 shape: retained=3, superseded=1, 4.90 s cut 2 shape: retained=3, superseded=1, 5.00 s
5 cut 1 shape: retained=3, superseded=1, 5.02 s cut 1 shape: retained=3, superseded=1, 4.95 s
6 cut 1 shape: retained=3, superseded=1, 5.09 s cut 2 shape: retained=3, superseded=1, 5.02 s

Cut 2 shape: 1 cut of 6 on 7.36.0, 3 of 6 on 7.44.0. No video dts non-monotonic at source line at all in any of the twelve sessions. On the ten resolved cuts the reconnect's first data came 81 to 136 ms after the new request and AVPlayer logged no stall; our app's own stall watchdog fired on no cut. 7.44.0, cut 3 (date, level and our log's own prefix cut, nothing else changed):

00:24:36.638 [AVIOReader] pump gen=2 first data after 90ms
00:24:36.654 [HLSSegmentProducer] live source overlap candidate: exact packet match after timestamp rollback; checking both tracks before output
00:24:36.654 [mpegts @ 0x12886a400] [warning] Packet corrupt (stream = 0, dts = 5720590).
00:24:36.655 [HLSSegmentProducer] live damaged packet: stream=video action=held count=1 dts=5719088 pts=5728097 keyframe=false
00:24:36.742 [ReplayVideoBoundary] route=native damaged=1 replaced=1 unreplaced=0 retained=3 keyframes=0 superseded=1 untimed=0
00:24:36.742 [HLSSegmentProducer] live damaged packet: stream=video action=discarded count=1 dts=5719088 pts=5728097 keyframe=false
00:24:36.743 [HLSSegmentProducer] live source overlap resolved: removed 292 video + 230 audio packets across 4.85s; first new packet continues the existing timeline

The 7.36.0 cut of that shape (cut 3) logged the same sequence with retained=2 keyframes=0 superseded=1, and no bump. We have no recording of the tile, so nothing here is about the picture beyond AVPlayer's stall lines.

7.44.0 is our app's engine pin as of today (2026-10-21).

@superuser404notfound

Copy link
Copy Markdown
Owner

Thank you, @cmcpherson274, for running the retest against the exact criterion and for keeping the 7.36.0 arm beside it. The three 7.44.0 seams of the cut 2 shape all committing with retained=3 superseded=1 and no bump is what the change was meant to produce: the outgoing straggler now raises the frontier, so the returning copies of both pictures land in the verified batch. For the record, 5aca553 first shipped in 7.38.0.

Your reading of the 7.36.0 arm is right, and worth keeping: whether the old code missed depended on whether the truncated successor was read before the returning copy of the flagged picture, so a single cut 2 shape that happened to commit cleanly says nothing either way. The test added with the fix pins the order that missed.

On the two cuts with no overlap check (7.36.0 cut 1, 7.44.0 cut 2): srcDts=126000 is 1.4 s at 90 kHz, where a freshly started FFmpeg MPEG-TS mux begins its timestamps, so on those reconnects the server answered with a new stream after about 3.2 s rather than re-serving the old one. There is nothing to deduplicate then, and the rebase plus [DISCONTINUITY] is the intended path; the AVPlayer stall covers the gap in which no data arrived. That is outside what this PR touches.

I'm treating the cut 2 case as confirmed on device. Thanks again for the careful runs.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants