Skip to content

Handle secondary and recursive SeekHead elements in MatroskaExtractor (updated) - #3579

Open
TharathielCB wants to merge 9 commits into
androidx:mainfrom
TharathielCB:fix-recursive-seekhead-mkv
Open

TharathielCB wants to merge 9 commits into
androidx:mainfrom
TharathielCB:fix-recursive-seekhead-mkv

Conversation

@TharathielCB

@TharathielCB TharathielCB commented Nov 24, 2026 •

Copy link
Copy Markdown

Based on PR: #3479 by https://github.com/rashidekbal
Adressed Issue: #1143

Original problem description:

Problem

Certain Matroska (.mkv) files, especially large WEB-DL and high-definition encodes created by mkvmerge, place their Cues element reference inside a secondary (chained/recursive) SeekHead rather than the primary SeekHead at the beginning of the file.

When reading these files, MatroskaExtractor only recorded ID_CUES and ID_TRACKS seek entries from the primary SeekHead. It ignored ID_SEEK_HEAD entries. Consequently, cuesContentPosition remained unset (C.INDEX_UNSET). When buildSeekMap() was invoked, MatroskaExtractor concluded that the file lacked cues and initialized an unseekable SeekMap.Unseekable(durationUs), rendering the media non-seekable despite valid cues existing in the container.

Solution

Detect Chained SeekHead: In MatroskaExtractor.endMasterElement(), check for seekEntryId == ID_SEEK_HEAD. When cuesContentPosition == C.INDEX_UNSET, record secondarySeekHeadPosition = seekEntryPosition.
Execute Secondary SeekHead Read: If cuesContentPosition has not been located but secondarySeekHeadPosition is known, initiate a seek via maybeSeekForSecondarySeekHead() to parse the secondary SeekHead and discover the true cuesContentPosition.
Defer SeekMap Fallback: Update buildSeekMap() and early format emission guards so that seeking is not prematurely disabled as unseekable before attempting to parse the secondary SeekHead.
Position Restoration: After reading the secondary SeekHead, restore the input position back to the previous track reading offset.
Testing
Verified with Matroska WEB-DL files (1080p / 4K) containing secondary SeekHead pointing to Cues.
Confirmed that cuesContentPosition is successfully resolved, Cues are parsed, seek map entries are built, and seeking functions accurately without regression.

Addition in this PR:

Changes:

Updated acc. to the review: #3479 (comment) by https://github.com/FongMi

Addressed both points:

  1. SeekHead and Cues jumps now share a single attempt budget (MAX_INDEX_SEEKS). Every index seek is recorded, and once the budget is exhausted no further seek is returned; the extractor outputs an unseekable SeekMap and continues from the original position.
  2. Index seek targets are validated against the Segment bounds and the known input length before returning RESULT_SEEK. Out of range SeekHead targets are skipped; an out of range Cues target falls back to unseekable.

Added tests for the budget at capacity (Cues chain through more SeekHeads than the budget), a Cues offset beyond the input length, and a Cues offset beyond the Segment end. Existing tests that append SeekHeads after the original Segment now update the Segment size accordingly. All 14 tests in MatroskaExtractorNonParameterizedTest and all tests in androidx.media3.extractor.mkv.* pass locally.

Thank you for the review!

Note:

Claude helped me out, here and there.

When resolving secondary SeekHead elements, format emission was delayed
until Cues were parsed. If the secondary SeekHead pointed directly to
Cues or contained only Cluster entries, the extractor returned directly
to the saved Cluster position without scheduling Cues or completing the
no-Cues fallback first, causing samples to be emitted before track formats.

This commit updates the index-resolution flow to:
- Properly schedule Cues parsing or complete the no-Cues fallback (emitting
  track formats and unseekable SeekMap) before returning to sample reading.
- Support multi-hop SeekHead traversal up to a bounded depth (16 hops).
- Detect and prevent cycles using visited and pending position tracking.
- Reset index traversal state when an explicit seek to position 0 occurs
  before the seek map is finalized.
- Add regression test coverage in MatroskaExtractorNonParameterizedTest
  for single-hop, multi-hop, Cluster-only secondary SeekHead, cycles, and
  seek resets.

Fixes androidx#1143
When resolving the index (via secondary SeekHead or Cues):
- If a Cues reference points to a Cluster, encountering ID_CLUSTER during
  index resolution could cause maybePrepareSeekMap() to repeatedly schedule
  seeks to the same position. Now, encountering ID_CLUSTER while
  seekPositionAfterBuildingCues is set completes index resolution fallback
  (emitting unseekable SeekMap, track formats, and clearing index flags),
  and avoids redundant seeks if already at the saved Cluster position.
- If EOF is reached while resolving the index (such as a Cues pointer
  referencing an element at or past the end of input), the extractor now
  executes terminal fallback by emitting an unseekable SeekMap and track
  formats, and restores position to the saved Cluster to resume media playback.
- Add regression tests in MatroskaExtractorNonParameterizedTest covering
  both cases.

Fixes androidx#1143
- Consume cuesContentPosition upon scheduling seek and record target
  position in visitedSeekHeadPositions to prevent repeated seeks and
  cyclic Cues references.
- Reject Cues entries pointing to already-visited SeekHead positions.
- Guard visitedSeekHeadPositions array bounds against MAX_SEEK_HEAD_HOPS.
- Ensure seekMap and track formats are emitted if EOF is reached before
  seek map is sent.
- Validate seekEntryPosition in integerElement against negative values.
- Add regression tests in MatroskaExtractorNonParameterizedTest for
  Cues pointing to non-Cues SeekHead and mutual cyclic Cues references.

Fixes androidx#1143
@google-cla

google-cla Bot commented Nov 24, 2026

Copy link
Copy Markdown

Thanks for your pull request! It looks like this may be your first contribution to a Google open source project. Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA).

View this failed invocation of the CLA check for more information.

For the most up to date status, view the checks section at the bottom of the pull request.

@TharathielCB

TharathielCB commented Nov 26, 2026 •

Copy link
Copy Markdown
Author

Hi @sahuadarsh0 Thank you for your review! Both points are addressed in the latest commit:

  1. Stale EBML reader state on the EOF fallback: read() now calls reader.reset() before returning RESULT_SEEK to seekPositionAfterBuildingCues, so no master elements from a truncated SeekHead or Cues remain on DefaultEbmlReader's stack. As you noted, the Segment bounds are already stored in segmentContentPosition/segmentContentSize, and endMasterElement() has no handling for ID_SEGMENT or ID_CLUSTER, so clearing the stack there is safe. I kept the reset out of abandonIndexResolution() because that method is also called from maybePrepareSeekMap() while startMasterElement(ID_CLUSTER) is being processed, where resetting would drop the current Cluster frame.
  2. Duplicated fallback cleanup: The fallback blocks in read() and maybePrepareSeekMap() now call abandonIndexResolution(), so the cleanup lives in one place and is guarded by if (!sentSeekMap). I applied the same change to the else branch in endMasterElement(ID_SEEK_HEAD), which contained a third copy of the same logic.

When Claude looked over my changes he suggest to add a seperate test for that. So I added read_withTruncatedSecondarySeekHeadAtEndOfInput_seeksBackAndOutputsSamples. It uses a secondary SeekHead whose Seek element is truncated at the end of the input, and verifies that the extractor seeks back to the original position, outputs an unseekable SeekMap and continues extracting samples.

And I also removed some explanatory comments I had added for myself in the previous revision.

@sahuadarsh0 sahuadarsh0 left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Looks good now, thanks for adding the truncated SeekHead test too.

@TharathielCB

Copy link
Copy Markdown
Author

OK. Thank you. merge conflicts are closed aswell. We are good to go.

@FongMi

FongMi commented Nov 27, 2026

Copy link
Copy Markdown

Thanks for adding the shared seek budget and bounds checks. I rechecked 308f85f and found one remaining EOF path while loading the optional index.

The new truncation test ends between child elements, so reader.read() returns false and the extractor can seek back. In a focused host test with sample.mkv, I ended the secondary SeekHead partway through the SeekPosition payload. DefaultEbmlReader throws EOFException from readFully() in that case, so MatroskaExtractor.read() exits before publishing a seek map, returning to the saved Cluster position, or emitting any samples.

Could an EOFException during the optional index read use the same fallback and reader reset? A regression test that cuts a field payload mid-read and verifies that sample output resumes would cover this path.

@TharathielCB

Copy link
Copy Markdown
Author

Thank you for your review @FongMi . An EOFException thrown while reading the optional index (secondary SeekHead or Cues) now uses the same fallback as reaching end of input: index resolution is abandoned, the EBML reader is reset, and extraction seeks back to the saved Cluster position. EOFs outside index resolution are still propagated unchanged. Both paths share a single helper.

Added read_withSecondarySeekHeadTruncatedInsideSeekPosition_seeksBackAndOutputsSamples, which cuts the secondary SeekHead inside the SeekPosition payload and verifies that an unseekable SeekMap is output and samples resume from the first Cluster.

One Point Claude hinted me to:
The regression test file ends inside the truncated SeekHead, so once linear extraction reaches that tail it still throws EOFException, the same as any other file truncated mid-element and unchanged by this PR. The test verifies that the seek map is published and samples are output before that point.

@icbaker icbaker self-assigned this Dec 1, 2026
@icbaker

icbaker commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator

See #3588 (comment)

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants