diff --git a/libraries/extractor/src/main/java/androidx/media3/extractor/mkv/MatroskaExtractor.java b/libraries/extractor/src/main/java/androidx/media3/extractor/mkv/MatroskaExtractor.java index 2b9037cdfbe..a94b8fb853d 100644 --- a/libraries/extractor/src/main/java/androidx/media3/extractor/mkv/MatroskaExtractor.java +++ b/libraries/extractor/src/main/java/androidx/media3/extractor/mkv/MatroskaExtractor.java @@ -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; @@ -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> perTrackCues; @@ -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. @@ -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(); @@ -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(); @@ -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; + } + } switch (id) { case ID_SEGMENT: if (segmentContentPosition != C.INDEX_UNSET && segmentContentPosition != contentPosition) { @@ -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(); @@ -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) { @@ -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: @@ -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: @@ -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); @@ -1126,6 +1170,9 @@ protected void endMasterElement(int id) throws ParserException { } } } + if (maybeSendFormatsEarly) { + sentTrackFormats = true; + } if (defaultVideoTrackNumber != C.INDEX_UNSET) { primarySeekTrackNumber = defaultVideoTrackNumber; @@ -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 @@ -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; @@ -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; @@ -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() { diff --git a/libraries/extractor/src/test/java/androidx/media3/extractor/mkv/MatroskaExtractorNonParameterizedTest.java b/libraries/extractor/src/test/java/androidx/media3/extractor/mkv/MatroskaExtractorNonParameterizedTest.java index 6255a1b76b9..2e1bab3e539 100644 --- a/libraries/extractor/src/test/java/androidx/media3/extractor/mkv/MatroskaExtractorNonParameterizedTest.java +++ b/libraries/extractor/src/test/java/androidx/media3/extractor/mkv/MatroskaExtractorNonParameterizedTest.java @@ -15,6 +15,7 @@ */ package androidx.media3.extractor.mkv; +import static androidx.media3.extractor.Extractor.RESULT_END_OF_INPUT; import static androidx.media3.extractor.Extractor.RESULT_SEEK; import static com.google.common.truth.Truth.assertThat; import static org.mockito.AdditionalAnswers.delegatesTo; @@ -37,6 +38,7 @@ import androidx.test.ext.junit.runners.AndroidJUnit4; import com.google.common.collect.Iterables; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; @@ -114,4 +116,171 @@ public SubtitleParser create(Format format) { verify(subtitleParser).reset(); } + + @Test + public void read_chainedSeekHeadWithDisableSeekForCuesFlag_doesNotSeekAndEmitsUnseekable() + throws Exception { + byte[] fileBytes = + TestUtil.getByteArray( + ApplicationProvider.getApplicationContext(), + "media/mkv/sample_with_chained_seek_head.mkv"); + MatroskaExtractor extractor = + new MatroskaExtractor( + SubtitleParser.Factory.UNSUPPORTED, MatroskaExtractor.FLAG_DISABLE_SEEK_FOR_CUES); + + FakeExtractorOutput output = extractAllSamplesWithoutSeeking(extractor, fileBytes); + + assertThat(output.seekMap).isNotNull(); + assertThat(output.seekMap.isSeekable()).isFalse(); + assertThat(output.tracksEnded).isTrue(); + output.trackOutputs.get(1).assertSampleCount(30); + output.trackOutputs.get(2).assertSampleCount(29); + } + + @Test + public void read_chainedSeekHeadPointingToCluster_doesNotLoopAndEmitsUnseekable() + throws Exception { + byte[] fileBytes = + TestUtil.getByteArray( + ApplicationProvider.getApplicationContext(), + "media/mkv/sample_with_chained_seek_head.mkv"); + // Patch SeekHead #1's SeekPosition for the secondary SeekHead (bytes 70..72 = 0x01A7C4) to + // point to Cluster #1 (offset 0x001586 relative to Segment content). + assertThat(fileBytes[70]).isEqualTo((byte) 0x01); + assertThat(fileBytes[71]).isEqualTo((byte) 0xA7); + assertThat(fileBytes[72]).isEqualTo((byte) 0xC4); + fileBytes[70] = 0x00; + fileBytes[71] = 0x15; + fileBytes[72] = (byte) 0x86; + + FakeExtractorOutput output = + TestUtil.extractAllSamplesFromByteArray( + new MatroskaExtractor(SubtitleParser.Factory.UNSUPPORTED), fileBytes); + + assertThat(output.seekMap).isNotNull(); + assertThat(output.seekMap.isSeekable()).isFalse(); + assertThat(output.tracksEnded).isTrue(); + output.trackOutputs.get(1).assertSampleCount(30); + output.trackOutputs.get(2).assertSampleCount(29); + } + + @Test + public void read_chainedSeekHeadPointingPastSegmentEnd_ignoresPointerAndEmitsUnseekable() + throws Exception { + byte[] fileBytes = + TestUtil.getByteArray( + ApplicationProvider.getApplicationContext(), + "media/mkv/sample_with_chained_seek_head.mkv"); + // Patch SeekHead #1's SeekPosition for the secondary SeekHead (bytes 70..72 = 0x01A7C4) to + // point past the end of the Segment (0x7FFFFF). + assertThat(fileBytes[70]).isEqualTo((byte) 0x01); + assertThat(fileBytes[71]).isEqualTo((byte) 0xA7); + assertThat(fileBytes[72]).isEqualTo((byte) 0xC4); + fileBytes[70] = 0x7F; + fileBytes[71] = (byte) 0xFF; + fileBytes[72] = (byte) 0xFF; + + FakeExtractorOutput output = + extractAllSamplesWithoutSeeking( + new MatroskaExtractor(SubtitleParser.Factory.UNSUPPORTED), fileBytes); + + assertThat(output.seekMap).isNotNull(); + assertThat(output.seekMap.isSeekable()).isFalse(); + assertThat(output.tracksEnded).isTrue(); + output.trackOutputs.get(1).assertSampleCount(30); + output.trackOutputs.get(2).assertSampleCount(29); + } + + @Test + public void read_chainedSeekHeadWithoutCues_emitsUnseekableAndEndsTracks() throws Exception { + byte[] fileBytes = + TestUtil.getByteArray( + ApplicationProvider.getApplicationContext(), + "media/mkv/sample_with_chained_seek_head.mkv"); + // Patch SeekHead #2's Cues entry ID (bytes 108577..108580 = 0x1C53BB6B) to Chapters + // (0x1043A770) so the secondary SeekHead contains no Cues reference. + assertThat(fileBytes[108577]).isEqualTo((byte) 0x1C); + assertThat(fileBytes[108578]).isEqualTo((byte) 0x53); + assertThat(fileBytes[108579]).isEqualTo((byte) 0xBB); + assertThat(fileBytes[108580]).isEqualTo((byte) 0x6B); + fileBytes[108577] = 0x10; + fileBytes[108578] = 0x43; + fileBytes[108579] = (byte) 0xA7; + fileBytes[108580] = 0x70; + + FakeExtractorOutput output = + TestUtil.extractAllSamplesFromByteArray( + new MatroskaExtractor(SubtitleParser.Factory.UNSUPPORTED), fileBytes); + + assertThat(output.seekMap).isNotNull(); + assertThat(output.seekMap.isSeekable()).isFalse(); + assertThat(output.tracksEnded).isTrue(); + output.trackOutputs.get(1).assertSampleCount(30); + output.trackOutputs.get(2).assertSampleCount(29); + } + + @Test + public void read_chainedSeekHeadPointingToTrackEntry_ignoresElementAndEmitsUnseekable() + throws Exception { + byte[] fileBytes = + TestUtil.getByteArray( + ApplicationProvider.getApplicationContext(), + "media/mkv/sample_with_chained_seek_head.mkv"); + // Patch SeekHead #1's SeekPosition for the secondary SeekHead (bytes 70..72 = 0x01A7C4) to + // point to a TrackEntry element (offset 0x001085 relative to Segment content). + assertThat(fileBytes[70]).isEqualTo((byte) 0x01); + assertThat(fileBytes[71]).isEqualTo((byte) 0xA7); + assertThat(fileBytes[72]).isEqualTo((byte) 0xC4); + fileBytes[70] = 0x00; + fileBytes[71] = 0x10; + fileBytes[72] = (byte) 0x85; + + FakeExtractorOutput output = + TestUtil.extractAllSamplesFromByteArray( + new MatroskaExtractor(SubtitleParser.Factory.UNSUPPORTED), fileBytes); + + assertThat(output.seekMap).isNotNull(); + assertThat(output.seekMap.isSeekable()).isFalse(); + assertThat(output.tracksEnded).isTrue(); + output.trackOutputs.get(1).assertSampleCount(30); + output.trackOutputs.get(2).assertSampleCount(29); + } + + @Test + public void read_chainedSeekHeadTruncatedAtEof_recoversAndEmitsUnseekable() throws Exception { + byte[] fullBytes = + TestUtil.getByteArray( + ApplicationProvider.getApplicationContext(), + "media/mkv/sample_with_chained_seek_head.mkv"); + // Truncate inside SeekHead #2 right after its first Seek entry (byte 108556) so EOF is hit + // before endMasterElement(ID_SEEK_HEAD) runs. + byte[] fileBytes = Arrays.copyOf(fullBytes, 108556); + + FakeExtractorOutput output = + TestUtil.extractAllSamplesFromByteArray( + new MatroskaExtractor(SubtitleParser.Factory.UNSUPPORTED), fileBytes); + + assertThat(output.seekMap).isNotNull(); + assertThat(output.seekMap.isSeekable()).isFalse(); + assertThat(output.tracksEnded).isTrue(); + output.trackOutputs.get(1).assertSampleCount(30); + output.trackOutputs.get(2).assertSampleCount(29); + } + + private static FakeExtractorOutput extractAllSamplesWithoutSeeking( + MatroskaExtractor extractor, byte[] data) throws Exception { + FakeExtractorOutput output = new FakeExtractorOutput(); + extractor.init(output); + FakeExtractorInput input = new FakeExtractorInput.Builder().setData(data).build(); + PositionHolder positionHolder = new PositionHolder(); + + while (true) { + int result = extractor.read(input, positionHolder); + assertThat(result).isNotEqualTo(RESULT_SEEK); + if (result == RESULT_END_OF_INPUT) { + break; + } + } + return output; + } } diff --git a/libraries/extractor/src/test/java/androidx/media3/extractor/mkv/MatroskaExtractorTest.java b/libraries/extractor/src/test/java/androidx/media3/extractor/mkv/MatroskaExtractorTest.java index 1762af4c363..c4a13eb63dd 100644 --- a/libraries/extractor/src/test/java/androidx/media3/extractor/mkv/MatroskaExtractorTest.java +++ b/libraries/extractor/src/test/java/androidx/media3/extractor/mkv/MatroskaExtractorTest.java @@ -354,6 +354,17 @@ public void mkvSampleLastCluster() throws Exception { simulationConfig); } + @Test + public void mkvSample_withChainedSeekHead() throws Exception { + ExtractorAsserts.assertBehavior( + getExtractorFactory(subtitlesParsedDuringExtraction), + "media/mkv/sample_with_chained_seek_head.mkv", + new ExtractorAsserts.AssertionConfig.Builder() + .setDumpFilesPrefix("extractordumps/mkv/sample.mkv") + .build(), + simulationConfig); + } + private static ExtractorAsserts.ExtractorFactory getExtractorFactory( boolean subtitlesParsedDuringExtraction) { SubtitleParser.Factory subtitleParserFactory; diff --git a/libraries/test_data/src/test/assets/media/mkv/sample_with_chained_seek_head.mkv b/libraries/test_data/src/test/assets/media/mkv/sample_with_chained_seek_head.mkv new file mode 100644 index 00000000000..ad7995dc616 Binary files /dev/null and b/libraries/test_data/src/test/assets/media/mkv/sample_with_chained_seek_head.mkv differ