Skip to content

feat(demux): surface container (Matroska/MP4) chapters as mediaChapters - #179

Merged
superuser404notfound merged 1 commit into
superuser404notfound:mainfrom
natedogg058:feat/container-chapters
Jul 29, 2026
Merged

superuser404notfound merged 1 commit into
superuser404notfound:mainfrom
natedogg058:feat/container-chapters

Conversation

@natedogg058

Copy link
Copy Markdown

Reads AVFormatContext.chapters in the probe demuxer and publishes them as
engine.mediaChapters, giving hosts a chapter list for ordinary file/URL
sources to build chapter navigation UI on - previously only disc
(DVD/Blu-ray) sources exposed chapters via discChapters.

  • Demuxer.mediaChapterInfos(): sorted by start, re-ided sequentially,
    "Chapter N" fallback naming (matching the disc naming). Declared end
    times are trusted only for the last entry - real-world MKV muxes
    routinely write end == start - earlier durations run to the next start.
  • Suppressed for disc sources: those keep their playlist/IFO chapters on
    discChapters with title-relative seek semantics; both lists never
    populate at once, so hosts can bind one picker.
  • Wiped in both engine reset paths; preserved across the audio-switch /
    background reload seam via a pre-stopInternal snapshot (the source URL
    is unchanged, so re-probing would be waste), while disc chapters keep
    their existing reopened-demuxer recapture (a title switch legitimately
    changes them).

startSeconds values are content timestamps a host passes straight to
seek(to:). Shipped in a production tvOS consumer driving a chapter rail
on both this engine and a libmpv twin.

Co-Authored-By: Claude Fable 5 noreply@anthropic.com


Validated: builds for generic tvOS Simulator (arm64) against this repo's own manifest; running in a production tvOS consumer (custom chapter-rail UI over this API alongside a libmpv twin reading chapter-list, so the surface was designed engine-agnostic).

Reads AVFormatContext.chapters in the probe demuxer and publishes them as
engine.mediaChapters, giving hosts a chapter list for ordinary file/URL
sources to build chapter navigation UI on - previously only disc
(DVD/Blu-ray) sources exposed chapters via discChapters.

- Demuxer.mediaChapterInfos(): sorted by start, re-ided sequentially,
  "Chapter N" fallback naming (matching the disc naming). Declared end
  times are trusted only for the last entry - real-world MKV muxes
  routinely write end == start - earlier durations run to the next start.
- Suppressed for disc sources: those keep their playlist/IFO chapters on
  discChapters with title-relative seek semantics; both lists never
  populate at once, so hosts can bind one picker.
- Wiped in both engine reset paths; preserved across the audio-switch /
  background reload seam via a pre-stopInternal snapshot (the source URL
  is unchanged, so re-probing would be waste), while disc chapters keep
  their existing reopened-demuxer recapture (a title switch legitimately
  changes them).

startSeconds values are content timestamps a host passes straight to
seek(to:). Shipped in a production tvOS consumer driving a chapter rail
on both this engine and a libmpv twin.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

@superuser404notfound superuser404notfound left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this, and for the careful writeup. The quality here is well above the usual first PR: the disc suppression gate, the end-times-are-lies handling for real-world MKV muxes, and the naming parity with the disc chapters all match how this codebase thinks. I verified the core semantic claim before reviewing the mechanics: for non-disc sources sourcePresentationOrigin is 0, so seek(to:) and currentTime run on the container source-PTS axis on both backends, which is exactly the axis AVChapter starts live on (including sources with a non-zero start_time). "Pass straight to seek(to:)" holds generally, not just for the common start-at-zero case. I also ran the full suite on this branch merged onto current main (933/933 green) and approved the CI run, which is green as well.

One structural change request, then two smaller asks.

The stopInternal wipe + snapshot loses chapters across the iOS background seam. Your snapshot in reloadWithAudioOverride covers the audio-switch reload, where stopInternal runs inside the helper. But on iOS, teardownVideoForBackground (and the #127 expiration backstop expireBackgroundGraceNow) call stopInternal directly, outside the reload helper, and the designed resume path is reloadAtCurrentPosition() on foreground return. By the time that reload takes its snapshot, mediaChapters is already empty, so the restore restores nothing and the chapter list is gone after every background round trip. Your tvOS consumer can't see this because that teardown path is iOS-only.

The engine already has a pattern for exactly this situation, spelled out in the stop() comment for fontAttachments: session-scoped source-descriptive state "must survive stopInternal", because reload seams skip the probe. audioTracks, subtitleTracks, metadata, and duration all follow it; the disc lists are the deliberate exception because a title switch legitimately changes them, which does not apply to container chapters of an unchanged URL. So:

  • drop mediaChapters = [] from stopInternal
  • add mediaChapters = [] to the clear block in stop() instead (next to fontAttachments)
  • keep the wipe in the load() prep block as you have it
  • delete both +Loading.swift hunks (snapshot and restore), they become unnecessary

Net effect: smaller diff, the iOS seam fixed for free, and the chapter rail stays published during background/PiP the same way the track lists do.

Tests. The mapping logic (NOPTS/timebase guards, sort, sequential re-id, trust-end-only-for-last, title fallback) is pure and deserves fixture-free coverage. The precedent is Demuxer.resolveBitrate plus DemuxerBitrateTests: factor the raw-entries-to-ChapterInfo mapping into a static helper on Demuxer and test it directly. While you are in there, tb.num >= 0 should be tb.num > 0: a zero numerator currently collapses the entry to start 0 instead of skipping it.

Docs. mediaChapters should join the published-property list in the README (next to $discChapters) and get a sentence in the chapters section of docs/formats.md, including the axis contrast with selectChapter. The ChapterInfo doc comment ("offset from the title's start") is now too narrow with a second producer of the type; worth a line covering both semantics. No CHANGELOG action needed, that is handled at release time.

One optional thought, no action required: with end == start on the last entry the final chapter gets durationSeconds 0. If you would rather not fall back to the container duration there, documenting 0 as "runs to end of file" on the property would also do.

Happy to merge once the stopInternal restructure and tests are in.

superuser404notfound pushed a commit that referenced this pull request Jul 29, 2026
Changelog only: the #246 Fixed block and the #179 Added block both landed
under [Unreleased].
superuser404notfound pushed a commit that referenced this pull request Jul 29, 2026
Merge #179 (container chapters) and keep them across every reopen
@superuser404notfound
superuser404notfound merged commit bf52a43 into superuser404notfound:main Jul 29, 2026
3 checks passed
superuser404notfound pushed a commit that referenced this pull request Jul 29, 2026
Changelog only: the #180 Added bullet joins the #179 one under the same
heading, below main's Fixed section.
@superuser404notfound

Copy link
Copy Markdown
Owner

Merged, thanks for this. Chapters for ordinary containers were a real gap, the read side is right where it belongs, and suppressing them for disc sources so exactly one of the two publishers is ever populated is the detail that makes the API honest rather than ambiguous.

I merged it and then pushed the review points myself rather than sending it back, since the fix turned out to shrink the diff:

The wipe moved from stopInternal to stop(). The snapshot/restore pair around the reload helper covered the audio-switch path, but teardownVideoForBackground and the #127 expiry call stopInternal outside that helper, so an iOS background roundtrip emptied the list for the rest of the session and the foreground reload then snapshotted the already-emptied list. Container chapters belong to the source URL rather than to the pipeline, which is the same rule fontAttachments follows, so both +Loading hunks came back out. tvOS was never affected, which is why the field validation passed cleanly.

tb.num >= 0 became > 0. A zero numerator scales every timestamp to zero and collapses the whole list onto 0 s.

The last chapter falls back to the container duration when its declared end is degenerate. That is the same mux bug the next-start rule already handles, landing on the one entry the rule cannot cover, and it showed up as a zero-length chapter in a host UI.

The mapping is now a pure function over the values read off AVChapter, following the Demuxer.resolveBitrate precedent, with ContainerChapterMappingTests covering ordering, ids, naming and all three duration rules. ChapterInfo documents both time axes now, and README / docs/formats.md describe the publisher.

One thing I deliberately left alone: selectChapter(id:) stays disc-only and no-ops for a container chapter id. Extending it means adding the right content-start base, and whether a non-disc source needs one differs by backend, so that wants a device test rather than a same-commit convenience. It is documented as disc-only for now.

Shipping in the next release.

ijuniorfu pushed a commit to ijuniorfu/AetherEngine that referenced this pull request Jul 29, 2026
…ource (superuser404notfound#179)

Follow-up to the merged PR. The chapter wipe sat in stopInternal with a
snapshot/restore pair around the reload helper, but the iOS background
teardown and the superuser404notfound#127 expiry call stopInternal outside that helper, so a
background roundtrip published an empty list for the rest of the session and
the foreground reload then snapshotted the already-emptied list.

Container chapters belong to the source URL, not to the pipeline, which is
exactly the fontAttachments rule: the wipe moves to stop()'s clear block and
both reload hunks are dropped, so every reopen of the same source keeps them
without carrying state across the seam.

Also hardened:

- tb.num == 0 is rejected. It scaled every timestamp to zero and collapsed the
  whole list onto 0 s; only a positive numerator is a usable time base.
- The last chapter falls back to the container duration when its declared end
  is degenerate. That is the same mux bug the next-start rule already handles,
  landing on the one entry the rule cannot cover, and it read as a zero-length
  chapter in a host UI.
- The mapping is a pure function over the values read off AVChapter, covered by
  ContainerChapterMappingTests (ordering, ids, naming, all three duration
  rules), matching the fixture-free Demuxer helper precedent.
- ChapterInfo now documents both time axes, and README / docs/formats.md cover
  the new publisher plus the disc-only scope of selectChapter(id:).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01At1agC2qU2Y2MX2BKLdT4N
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.

2 participants