Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,8 @@ public static ExtractorsFactory newFactory(SubtitleParser.Factory subtitleParser
private static final String TAG = "MatroskaExtractor";

private static final int UNSET_ENTRY_ID = -1;
// 8-byte EBML unknown-size VINT (0x01FFFFFFFFFFFFFF) with the length marker bit removed.
private static final long UNKNOWN_SEGMENT_SIZE = 0x00FFFFFFFFFFFFFFL;

private static final int BLOCK_STATE_START = 0;
private static final int BLOCK_STATE_HEADER = 1;
Expand Down Expand Up @@ -494,6 +496,13 @@ public static ExtractorsFactory newFactory(SubtitleParser.Factory subtitleParser
// Master seek entry related elements.
private int seekEntryId;
private long seekEntryPosition;
private long secondarySeekHeadPosition = C.INDEX_UNSET;
private boolean seekForSecondarySeekHead;
private boolean attemptedSecondarySeekHead;
private boolean awaitingSecondarySeekHead;
private long seekPositionAfterReadingSeekHead = C.INDEX_UNSET;
private boolean readSecondarySeekHead;
private int ignoredSecondarySeekHeadElementId = UNSET_ENTRY_ID;

// Cue related elements.
private final SparseArray<List<MatroskaSeekMap.CuePointData>> perTrackCues;
Expand All @@ -510,6 +519,7 @@ public static ExtractorsFactory newFactory(SubtitleParser.Factory subtitleParser
private boolean seekForTracks;
private long seekPositionAfterReadingTracks = C.INDEX_UNSET;
private boolean readTracks;
private boolean sentTrackFormats;
private long clusterTimecodeUs = C.TIME_UNSET;

// Reading state.
Expand Down Expand Up @@ -641,11 +651,19 @@ public void seek(long position, long timeUs) {
currentCueTrackNumber = C.INDEX_UNSET;
currentCueClusterPosition = C.INDEX_UNSET;
currentCueRelativePosition = C.INDEX_UNSET;
ignoredSecondarySeekHeadElementId = UNSET_ENTRY_ID;
// To prevent creating duplicate cue points on a re-parse, clear any existing cue data if the
// seek map has not yet been sent. Once sent, the cue data is considered final, and subsequent
// Cues elements will be ignored by the parsing logic.
if (!sentSeekMap) {
perTrackCues.clear();
// Reset pending SeekHead state alongside Cues so pre-seekMap retries re-run discovery, while
// leaving Tracks and SegmentInfo state intact as before.
seekForSecondarySeekHead = false;
attemptedSecondarySeekHead = false;
awaitingSecondarySeekHead = false;
readSecondarySeekHead = false;
seekPositionAfterReadingSeekHead = C.INDEX_UNSET;
}
for (int i = 0; i < tracks.size(); i++) {
tracks.valueAt(i).reset();
Expand All @@ -666,13 +684,18 @@ public final int read(ExtractorInput input, PositionHolder seekPosition) throws
boolean continueReading = true;
while (continueReading && !haveOutputSample) {
continueReading = reader.read(input);
if (continueReading
&& (maybeSeekForTracks(seekPosition, input.getPosition())
|| maybeSeekForCues(seekPosition, input.getPosition()))) {
if (continueReading && maybeSeek(seekPosition, input.getPosition())) {
return Extractor.RESULT_SEEK;
}
}
if (!continueReading) {
if (seekPositionAfterReadingSeekHead != C.INDEX_UNSET) {
awaitingSecondarySeekHead = false;
finishSecondarySeekHead();
if (maybeSeek(seekPosition, input.getPosition())) {
return Extractor.RESULT_SEEK;
}
}
for (int i = 0; i < tracks.size(); i++) {
Track track = tracks.valueAt(i);
track.assertOutputInitialized();
Expand Down Expand Up @@ -841,6 +864,16 @@ protected boolean isLevel1Element(int id) {
protected void startMasterElement(int id, long contentPosition, long contentSize)
throws ParserException {
assertInitialized();
if (awaitingSecondarySeekHead) {
awaitingSecondarySeekHead = false;
if (id != ID_SEEK_HEAD) {
// The secondary SeekHead pointer landed on a non-SeekHead element; stop retrying and
// proceed with tracks/seek-map setup so the extractor returns to the Cluster.
ignoredSecondarySeekHeadElementId = id;
finishSecondarySeekHead();
return;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

When id != ID_SEEK_HEAD, control still falls through into switch (id) for the unexpected element, so a bogus pointer landing on ID_SEGMENT, ID_TRACK_ENTRY, or ID_CHAPTER_ATOM can throw or mutate parser state before seeking back. Returning early after finishSecondarySeekHead() avoids running switch (id) on that element, though DefaultEbmlReader will still have pushed that master element onto its stack until its end position is passed.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

In startMasterElement / endMasterElement I added an early return after finishSecondarySeekHead() when id != ID_SEEK_HEAD, and tracked ignoredSecondarySeekHeadElementId so endMasterElement skips the matching pop from DefaultEbmlReader's stack (which otherwise caused ID_TRACK_ENTRY to hit checkNotNull(this.currentTrack)).

}
switch (id) {
case ID_SEGMENT:
if (segmentContentPosition != C.INDEX_UNSET && segmentContentPosition != contentPosition) {
Expand Down Expand Up @@ -874,7 +907,9 @@ protected void startMasterElement(int id, long contentPosition, long contentSize
}
break;
case ID_CLUSTER:
if (tracksContentPosition != C.INDEX_UNSET && !readTracks) {
if (shouldSeekForSecondarySeekHead()) {
seekForSecondarySeekHead = true;
} else if (tracksContentPosition != C.INDEX_UNSET && !readTracks) {
seekForTracks = true;
} else {
maybePrepareSeekMap();
Expand Down Expand Up @@ -914,6 +949,10 @@ protected void startMasterElement(int id, long contentPosition, long contentSize
@CallSuper
protected void endMasterElement(int id) throws ParserException {
assertInitialized();
if (ignoredSecondarySeekHeadElementId == id) {
ignoredSecondarySeekHeadElementId = UNSET_ENTRY_ID;
return;
}
switch (id) {
case ID_SEGMENT_INFO:
if (timecodeScale == C.TIME_UNSET) {
Expand All @@ -933,6 +972,16 @@ protected void endMasterElement(int id) throws ParserException {
cuesContentPosition = seekEntryPosition;
} else if (seekEntryId == ID_TRACKS) {
tracksContentPosition = seekEntryPosition;
} else if (seekEntryId == ID_SEEK_HEAD
&& secondarySeekHeadPosition == C.INDEX_UNSET
&& isWithinSegmentBounds(seekEntryPosition)) {
// Per RFC 9559 Section 6.3, a Segment may reference a single secondary SeekHead.
secondarySeekHeadPosition = seekEntryPosition;
}
break;
case ID_SEEK_HEAD:
if (seekPositionAfterReadingSeekHead != C.INDEX_UNSET) {
finishSecondarySeekHead();
}
break;
case ID_CUES:
Expand Down Expand Up @@ -962,15 +1011,7 @@ protected void endMasterElement(int id) throws ParserException {
}
sentSeekMap = true;
inCuesElement = false;
for (int i = 0; i < tracks.size(); i++) {
Track track = tracks.valueAt(i);
if (!track.waitingForDtsAnalysis) {
updateTrackFormatWithMetadata(track);
track.assertOutputInitialized();
track.output.format(checkNotNull(track.format));
}
}
maybeEndTracks();
sendTrackFormats();
}
break;
case ID_CUE_TRACK_POSITIONS:
Expand Down Expand Up @@ -1093,10 +1134,13 @@ protected void endMasterElement(int id) throws ParserException {
int defaultAudioTrackNumber = C.INDEX_UNSET;
int firstAudioTrackNumber = C.INDEX_UNSET;

// If we're not going to seek for cues, or we have already processed them, output the
// formats immediately.
boolean maybeSendFormatsEarly =
!seekForCuesEnabled || cuesContentPosition == C.INDEX_UNSET || sentSeekMap;
// If we're not going to seek for cues (directly or via a secondary SeekHead), or we have
// already processed them, output the formats immediately.
boolean maySeekForCues =
seekForCuesEnabled
&& (cuesContentPosition != C.INDEX_UNSET
|| (secondarySeekHeadPosition != C.INDEX_UNSET && !readSecondarySeekHead));
boolean maybeSendFormatsEarly = !maySeekForCues || sentSeekMap;

for (int i = 0; i < tracks.size(); i++) {
Track trackItem = tracks.valueAt(i);
Expand Down Expand Up @@ -1126,6 +1170,9 @@ protected void endMasterElement(int id) throws ParserException {
}
}
}
if (maybeSendFormatsEarly) {
sentTrackFormats = true;
}

if (defaultVideoTrackNumber != C.INDEX_UNSET) {
primarySeekTrackNumber = defaultVideoTrackNumber;
Expand Down Expand Up @@ -2195,6 +2242,62 @@ private int writeToOutput(ExtractorInput input, TrackOutput output, int length)
return bytesWritten;
}

private boolean isWithinSegmentBounds(long position) {
if (segmentContentPosition == C.INDEX_UNSET
|| segmentContentSize <= 0
|| segmentContentSize == UNKNOWN_SEGMENT_SIZE) {
return false;
}
return position >= segmentContentPosition
&& position - segmentContentPosition < segmentContentSize;
}

private void finishSecondarySeekHead() {
readSecondarySeekHead = true;
if (tracksContentPosition != C.INDEX_UNSET && !readTracks) {
seekForTracks = true;
} else {
maybePrepareSeekMap();
}
}

private boolean shouldSeekForSecondarySeekHead() {
if (secondarySeekHeadPosition == C.INDEX_UNSET
|| readSecondarySeekHead
|| attemptedSecondarySeekHead) {
return false;
}
boolean needsTracks = !readTracks && tracksContentPosition == C.INDEX_UNSET;
boolean needsCues = !sentSeekMap && seekForCuesEnabled && cuesContentPosition == C.INDEX_UNSET;
return needsTracks || needsCues;
}

private boolean maybeSeek(PositionHolder seekPosition, long currentPosition) {
return maybeSeekForSeekHead(seekPosition, currentPosition)
|| maybeSeekForTracks(seekPosition, currentPosition)
|| maybeSeekForCues(seekPosition, currentPosition);
}

private boolean maybeSeekForSeekHead(PositionHolder seekPosition, long currentPosition) {
if (seekForSecondarySeekHead) {
seekPositionAfterReadingSeekHead = currentPosition;
seekPosition.position = secondarySeekHeadPosition;
seekForSecondarySeekHead = false;
attemptedSecondarySeekHead = true;
awaitingSecondarySeekHead = true;
return true;
}
if (readSecondarySeekHead
&& seekPositionAfterReadingSeekHead != C.INDEX_UNSET
&& !seekForTracks
&& !seekForCues) {
seekPosition.position = seekPositionAfterReadingSeekHead;
seekPositionAfterReadingSeekHead = C.INDEX_UNSET;
return true;
}
return false;
}

/**
* Updates the position of the holder to Cues element's position if the extractor configuration
* permits use of master seek entry. After building Cues sets the holder's position back to where
Expand All @@ -2206,7 +2309,11 @@ private int writeToOutput(ExtractorInput input, TrackOutput output, int length)
*/
private boolean maybeSeekForCues(PositionHolder seekPosition, long currentPosition) {
if (seekForCues) {
seekPositionAfterBuildingCues = currentPosition;
seekPositionAfterBuildingCues =
seekPositionAfterReadingSeekHead != C.INDEX_UNSET
? seekPositionAfterReadingSeekHead
: currentPosition;
seekPositionAfterReadingSeekHead = C.INDEX_UNSET;
seekPosition.position = cuesContentPosition;
seekForCues = false;
return true;
Expand All @@ -2223,7 +2330,11 @@ private boolean maybeSeekForCues(PositionHolder seekPosition, long currentPositi

private boolean maybeSeekForTracks(PositionHolder seekPosition, long currentPosition) {
if (seekForTracks) {
seekPositionAfterReadingTracks = currentPosition;
seekPositionAfterReadingTracks =
seekPositionAfterReadingSeekHead != C.INDEX_UNSET
? seekPositionAfterReadingSeekHead
: currentPosition;
seekPositionAfterReadingSeekHead = C.INDEX_UNSET;
seekPosition.position = tracksContentPosition;
seekForTracks = false;
return true;
Expand Down Expand Up @@ -2320,7 +2431,23 @@ private void maybePrepareSeekMap() {
// playback, but disable seeking.
checkNotNull(extractorOutput).seekMap(new SeekMap.Unseekable(durationUs));
sentSeekMap = true;
if (readTracks && !sentTrackFormats) {
sendTrackFormats();
}
}
}

private void sendTrackFormats() {
sentTrackFormats = true;
for (int i = 0; i < tracks.size(); i++) {
Track track = tracks.valueAt(i);
if (!track.waitingForDtsAnalysis) {
updateTrackFormatWithMetadata(track);
track.assertOutputInitialized();
track.output.format(checkNotNull(track.format));
}
}
maybeEndTracks();
}

private void maybeEndTracks() {
Expand Down
Loading