Skip to content

fix(video): rebuild the presentation axis an MP4 dropped with its ctts table (#409) - #413

Merged
superuser404notfound merged 2 commits into
mainfrom
fix/409-h264-composition-offsets
Aug 24, 2026
Merged

superuser404notfound merged 2 commits into
mainfrom
fix/409-h264-composition-offsets

Conversation

@superuser404notfound

@superuser404notfound superuser404notfound commented Aug 24, 2026 •

Copy link
Copy Markdown
Owner

Summary

Repairs progressive H.264 MP4 whose writer omitted the composition-offset table while the bitstream still reorders pictures. The repair sits at the demuxer boundary and rebuilds the timestamps a correct muxer would have written, so the source keeps the native path and hardware decode.

Supersedes the remedy in #411 (same defect, same reporter, and that PR's fixture pair is this one's regression test). See the measurements posted on #409 and #411 for why the best_effort_timestamp axis was not usable.

Reported in #409. The reporter's retest on the affected asset is what settles that issue, so it stays open past this merge.

The defect, measured on the Apple decoder

With ctts absent, every sample reports PTS == DTS, so decode order is handed out as presentation order and the native stream-copy carries that into fMP4 unchanged. Decoding @orut34iop's twin pair through AVAssetReader (VideoToolbox) and matching frame content against the healthy twin:

healthy twin ctts removed
pictures shown at a time belonging to a different picture 0 of 66 45 of 66
backward steps in the content order presented 0 30

Per B-group the pattern is a repeating +67 ms / -100 ms shuffle, which is the reported judder.

What changed

  • H264CompositionOffsetRepair: a fail-closed head sample (twelve pictures at most) and the packet rewrite. Picture order comes from libavcodec's H.264 parser, which reads the slice header without decoding a pixel and takes MP4's length-prefixed AVCC payload directly, so no decode and no Annex-B conversion sit in the packet path.

    PTS = (decode time of the picture that opened this coded video sequence) + shift + rank * step
    DTS = DTS + shift - reorderDelay * step
    

    Both forms are relative to the packet's own timestamps, never to a counter, so a demuxer that starts mid-file and one that starts at byte 0 produce the same axis for the same picture. Pulling DTS back by the reorder delay is what keeps PTS >= DTS; a healthy file carries the same negative head.

  • shift is 0 or one reorder delay, depending on whether the writer left the ladder on the presentation axis or kept the edit list that trims the reorder head. It is read from the container (AVStream.start_time against the first index entry) and clamped to [0, decodeLead], so both writer shapes land on the same axis and a malformed header cannot drag the picture off its audio.

  • The sample holds the packets it consumed instead of rewinding: no second fetch, and a custom source that cannot be reopened is not excluded.

  • The container's own index is folded onto the repaired ladder, because the segment plan is built from index entries and then filled with these packets.

  • The verdict is settled in HLSVideoEngine.prepare while the demuxer still stands at the head. Sampling later would take the sample wherever the cue prewarm left the source and hand the producer a head six seconds into the file (measured, before this ordering was fixed).

  • Live, still-extraction and video-discarded demuxers never sample.

Why not route to software decode

Routing the session to the software host and scheduling on best_effort_timestamp (the approach in #411) does remove the shuffle, but the axis it lands on is not the presentation axis. Measured on the same twin pair, best_effort_timestamp is pkt_dts of the packet being fed, so it is the decode ladder shifted by the reorder delay:

  • +2002 ticks (2 frames, 67 ms) on 63 of 66 pictures: a permanent lip-sync error, and 100 ms at 30 fps for a 3-frame delay.
  • the first interval is 3 frame durations instead of 1.
  • at EOF the flush regresses: ..., 65065, 59059, 65065, a backward step of 4004 ticks and a duplicate. The probe's own bestEffortRegressions == 0 criterion is measured over the first 64 packets, so it structurally cannot see that tail.

It also costs hardware decode for what is a container metadata defect.

Verification

  • 432 packets across three fixture pairs (both edit-list shapes, seven IDR boundaries, @orut34iop's pair included): every repaired packet matches its healthy twin's PTS and DTS exactly.
  • Served output: the loopback fMP4 for the repaired source presents all 301 frames at the same times as the healthy twin's output does (0 of 301 mismatched, 0 backward steps, matched by frame content hash through AVAssetReader).
  • aetherctl segverify: 3/3 segments independently decodable on both arms.
  • aetherctl seektest --seeks 10: 13 seeks, all landed on target, 0 stalled, 0 unpaired, identical tallies on both arms (this is what exercises the post-seek re-anchoring).
  • Healthy files are untouched: no repair armed, timestamps delivered exactly as the container wrote them.
  • swift test 2026/2026 green in 288 suites. xcodebuild -scheme AetherEngine -destination 'generic/platform=tvOS' clean.

Checklist

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

🤖 Generated with Claude Code

https://claude.ai/code/session_01RbWZLwBVLGM1xUVXa9NeJ1

…s table (#409)

A writer that omits the composition-offset table while the H.264 bitstream still
reorders pictures makes every sample report PTS == DTS, so the container hands
decode order out as presentation order and the native stream-copy carries it into
fMP4 unchanged. Measured through AVFoundation's own decoder on a twin pair (one
encode, muxed twice, ctts removed from one): 45 of 66 pictures presented at a time
belonging to a different picture, content order stepping backwards 30 times.

The container lost the information, the bitstream did not. libavcodec's H.264
parser reads each access unit's picture order count without decoding a pixel and
takes MP4's length-prefixed payload directly, so the demuxer rewrites the packet to
what the muxer should have written: presentation by display rank, decode pulled back
by the reorder delay, which is also what keeps PTS >= DTS. The shift between the
sampled ladder and the presentation timeline is read from the container (start_time
against the first index entry) and clamped to one reorder delay, so both writer
shapes land on the same axis and a malformed header cannot drag the picture off its
audio.

Repairing at the demuxer boundary keeps one axis for every consumer (fMP4 producer,
segment plan, software decoder, still extractor) and keeps hardware decode: a
container defect no longer costs the native path. The container's index is folded
onto the same ladder, because the segment plan is built from index entries and then
filled with these packets; the verdict is settled while the demuxer still stands at
the head, since sampling after the cue prewarm would hand the producer a head six
seconds into the file.

Detection is fail-closed and nearly free on healthy files: the first real PTS-DTS
offset ends the sample. A source is repaired only when every sampled pair is equal,
the decode ladder is uniform, the picture order regresses, and the ranks it produces
are distinct and fill the sampled window. Live, still-extraction and video-discarded
demuxers never sample at all.

Verified: 432 packets across three fixture pairs (both edit-list shapes, seven IDR
boundaries) match their healthy twin exactly; the served output presents all 301
frames at the same times as the healthy twin's; segments stay independently
decodable; a 13-seek burst lands identically on both arms. Suite 2026/2026 green.

Reported by @orut34iop (#409), whose fixture pair is the regression test.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01RbWZLwBVLGM1xUVXa9NeJ1
A picture order count is computed against the previous picture's, so a parser
that carried its state across a jump can answer for the sequence that was left
behind. libavformat closes the stream parser on its own seeks
(`ff_read_frame_flush`); the repair now does the same on the packet path.

Landing on an IDR hid this, because the parser resets its own state there, which
is what a seek normally reaches. An open-GOP entry point does not.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01RbWZLwBVLGM1xUVXa9NeJ1
@superuser404notfound
superuser404notfound merged commit f08db21 into main Aug 24, 2026
4 checks passed
@superuser404notfound
superuser404notfound deleted the fix/409-h264-composition-offsets branch August 24, 2026 21:03
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.

1 participant