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 599d0c20315..d0047ff0f2d 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 @@ -503,9 +503,15 @@ public static ExtractorsFactory newFactory(SubtitleParser.Factory subtitleParser private long currentCueClusterPosition = C.INDEX_UNSET; private long currentCueRelativePosition = C.INDEX_UNSET; private int primarySeekTrackNumber = C.INDEX_UNSET; + private static final int MAX_SEEK_HEAD_HOPS = 16; + private final long[] pendingSeekHeadPositions = new long[MAX_SEEK_HEAD_HOPS]; + private int pendingSeekHeadCount; + private final long[] visitedSeekHeadPositions = new long[MAX_SEEK_HEAD_HOPS]; + private int visitedSeekHeadCount; private boolean seekForCues; private long cuesContentPosition = C.INDEX_UNSET; private long seekPositionAfterBuildingCues = C.INDEX_UNSET; + private boolean seekForSecondarySeekHead; private long tracksContentPosition = C.INDEX_UNSET; private boolean seekForTracks; private long seekPositionAfterReadingTracks = C.INDEX_UNSET; @@ -642,6 +648,14 @@ public void seek(long position, long timeUs) { // Cues elements will be ignored by the parsing logic. if (!sentSeekMap) { perTrackCues.clear(); + seekForCues = false; + seekForSecondarySeekHead = false; + seekPositionAfterBuildingCues = C.INDEX_UNSET; + if (position == 0) { + cuesContentPosition = C.INDEX_UNSET; + pendingSeekHeadCount = 0; + visitedSeekHeadCount = 0; + } } for (int i = 0; i < tracks.size(); i++) { tracks.valueAt(i).reset(); @@ -661,11 +675,31 @@ public final int read(ExtractorInput input, PositionHolder seekPosition) throws continueReading = reader.read(input); if (continueReading && (maybeSeekForTracks(seekPosition, input.getPosition()) + || maybeSeekForSecondarySeekHead(seekPosition, input.getPosition()) || maybeSeekForCues(seekPosition, input.getPosition()))) { return Extractor.RESULT_SEEK; } } if (!continueReading) { + if (seekPositionAfterBuildingCues != C.INDEX_UNSET) { + checkNotNull(extractorOutput).seekMap(new SeekMap.Unseekable(durationUs)); + sentSeekMap = true; + outputTrackFormats(); + maybeEndTracks(); + seekPosition.position = seekPositionAfterBuildingCues; + seekPositionAfterBuildingCues = C.INDEX_UNSET; + seekForCues = false; + seekForSecondarySeekHead = false; + cuesContentPosition = C.INDEX_UNSET; + pendingSeekHeadCount = 0; + return Extractor.RESULT_SEEK; + } + if (!sentSeekMap) { + checkNotNull(extractorOutput).seekMap(new SeekMap.Unseekable(durationUs)); + sentSeekMap = true; + outputTrackFormats(); + maybeEndTracks(); + } for (int i = 0; i < tracks.size(); i++) { Track track = tracks.valueAt(i); track.assertOutputInitialized(); @@ -908,15 +942,38 @@ protected void endMasterElement(int id) throws ParserException { durationUs = scaleTimecodeToUs(durationTimecode); } break; + case ID_SEEK_HEAD: + if (seekPositionAfterBuildingCues != C.INDEX_UNSET) { + if (cuesContentPosition != C.INDEX_UNSET) { + seekForCues = true; + } else if (pendingSeekHeadCount > 0) { + seekForSecondarySeekHead = true; + } else { + checkNotNull(extractorOutput).seekMap(new SeekMap.Unseekable(durationUs)); + sentSeekMap = true; + outputTrackFormats(); + maybeEndTracks(); + } + } + break; case ID_SEEK: if (seekEntryId == UNSET_ENTRY_ID || seekEntryPosition == C.INDEX_UNSET) { throw ParserException.createForMalformedContainer( "Mandatory element SeekID or SeekPosition not found", /* cause= */ null); } if (seekEntryId == ID_CUES) { - cuesContentPosition = seekEntryPosition; + if (!arrayContains(visitedSeekHeadPositions, visitedSeekHeadCount, seekEntryPosition)) { + cuesContentPosition = seekEntryPosition; + pendingSeekHeadCount = 0; + } } else if (seekEntryId == ID_TRACKS) { tracksContentPosition = seekEntryPosition; + } else if (seekEntryId == ID_SEEK_HEAD && cuesContentPosition == C.INDEX_UNSET) { + if (!arrayContains(visitedSeekHeadPositions, visitedSeekHeadCount, seekEntryPosition) + && !arrayContains(pendingSeekHeadPositions, pendingSeekHeadCount, seekEntryPosition) + && visitedSeekHeadCount + pendingSeekHeadCount < MAX_SEEK_HEAD_HOPS) { + pendingSeekHeadPositions[pendingSeekHeadCount++] = seekEntryPosition; + } } break; case ID_CUES: @@ -946,14 +1003,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)); - } - } + outputTrackFormats(); maybeEndTracks(); } break; @@ -1080,7 +1130,9 @@ protected void endMasterElement(int id) throws ParserException { // 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; + !seekForCuesEnabled + || (cuesContentPosition == C.INDEX_UNSET && pendingSeekHeadCount == 0) + || sentSeekMap; for (int i = 0; i < tracks.size(); i++) { Track trackItem = tracks.valueAt(i); @@ -1101,14 +1153,6 @@ protected void endMasterElement(int id) throws ParserException { firstAudioTrackNumber = trackItem.number; } } - - if (maybeSendFormatsEarly) { - if (!trackItem.waitingForDtsAnalysis) { - updateTrackFormatWithMetadata(trackItem); - trackItem.assertOutputInitialized(); - trackItem.output.format(checkNotNull(trackItem.format)); - } - } } if (defaultVideoTrackNumber != C.INDEX_UNSET) { @@ -1128,6 +1172,7 @@ protected void endMasterElement(int id) throws ParserException { maybePrepareSeekMap(); } if (maybeSendFormatsEarly) { + outputTrackFormats(); maybeEndTracks(); } break; @@ -1161,7 +1206,11 @@ protected void integerElement(int id, long value) throws ParserException { case ID_SEEK_POSITION: // Seek Position is the relative offset beginning from the Segment. So to get absolute // offset from the beginning of the file, we need to add segmentContentPosition to it. - seekEntryPosition = value + segmentContentPosition; + if (value < 0 || segmentContentPosition == C.INDEX_UNSET) { + seekEntryPosition = C.INDEX_UNSET; + } else { + seekEntryPosition = value + segmentContentPosition; + } break; case ID_TIMECODE_SCALE: timecodeScale = value; @@ -2179,6 +2228,45 @@ private int writeToOutput(ExtractorInput input, TrackOutput output, int length) return bytesWritten; } + private boolean maybeSeekForSecondarySeekHead( + PositionHolder seekPosition, long currentPosition) { + if (seekForSecondarySeekHead) { + seekForSecondarySeekHead = false; + if (pendingSeekHeadCount > 0) { + if (seekPositionAfterBuildingCues == C.INDEX_UNSET) { + seekPositionAfterBuildingCues = currentPosition; + } + long targetPosition = removePendingSeekHeadPosition(); + if (visitedSeekHeadCount < MAX_SEEK_HEAD_HOPS) { + visitedSeekHeadPositions[visitedSeekHeadCount++] = targetPosition; + } + seekPosition.position = targetPosition; + return true; + } + } + return false; + } + + private long removePendingSeekHeadPosition() { + if (pendingSeekHeadCount == 0) { + return C.INDEX_UNSET; + } + long position = pendingSeekHeadPositions[0]; + pendingSeekHeadCount--; + System.arraycopy( + pendingSeekHeadPositions, 1, pendingSeekHeadPositions, 0, pendingSeekHeadCount); + return position; + } + + private static boolean arrayContains(long[] array, int count, long value) { + for (int i = 0; i < count; i++) { + if (array[i] == value) { + 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 @@ -2190,17 +2278,27 @@ private int writeToOutput(ExtractorInput input, TrackOutput output, int length) */ private boolean maybeSeekForCues(PositionHolder seekPosition, long currentPosition) { if (seekForCues) { - seekPositionAfterBuildingCues = currentPosition; + if (seekPositionAfterBuildingCues == C.INDEX_UNSET) { + seekPositionAfterBuildingCues = currentPosition; + } seekPosition.position = cuesContentPosition; + if (visitedSeekHeadCount < MAX_SEEK_HEAD_HOPS) { + visitedSeekHeadPositions[visitedSeekHeadCount++] = cuesContentPosition; + } + cuesContentPosition = C.INDEX_UNSET; seekForCues = false; return true; } - // After parsing Cues, seek back to original position if available. We will not do this unless - // we seeked to get to the Cues in the first place. + // After parsing Cues or concluding index resolution, seek back to original position if + // available. We will not do this unless we seeked to get to the Cues or secondary SeekHead in + // the first place. if (sentSeekMap && seekPositionAfterBuildingCues != C.INDEX_UNSET) { - seekPosition.position = seekPositionAfterBuildingCues; + if (seekPositionAfterBuildingCues != currentPosition) { + seekPosition.position = seekPositionAfterBuildingCues; + seekPositionAfterBuildingCues = C.INDEX_UNSET; + return true; + } seekPositionAfterBuildingCues = C.INDEX_UNSET; - return true; } return false; } @@ -2295,10 +2393,24 @@ private void maybePrepareSeekMap() { if (sentSeekMap) { return; // Already evaluated } + if (seekPositionAfterBuildingCues != C.INDEX_UNSET) { + checkNotNull(extractorOutput).seekMap(new SeekMap.Unseekable(durationUs)); + sentSeekMap = true; + outputTrackFormats(); + maybeEndTracks(); + cuesContentPosition = C.INDEX_UNSET; + pendingSeekHeadCount = 0; + seekForCues = false; + seekForSecondarySeekHead = false; + return; + } // We need to build cues before parsing the cluster. if (seekForCuesEnabled && cuesContentPosition != C.INDEX_UNSET) { // We know where the Cues element is located. Seek to request it. seekForCues = true; + } else if (seekForCuesEnabled && pendingSeekHeadCount > 0) { + // We know where the secondary SeekHead is located. Seek to read it for cues. + seekForSecondarySeekHead = true; } else { // We don't know where the Cues element is located. It's most likely omitted. Allow // playback, but disable seeking. @@ -2307,6 +2419,17 @@ private void maybePrepareSeekMap() { } } + private void outputTrackFormats() { + 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)); + } + } + } + private void maybeEndTracks() { if (!pendingEndTracks) { return; 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 5df042682bd..50a110e6c54 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 @@ -18,6 +18,7 @@ import static androidx.media3.extractor.Extractor.RESULT_SEEK; import static com.google.common.truth.Truth.assertThat; +import androidx.media3.extractor.Extractor; import androidx.media3.extractor.PositionHolder; import androidx.media3.extractor.SeekPoint; import androidx.media3.extractor.TrackAwareSeekMap; @@ -27,6 +28,8 @@ import androidx.media3.test.utils.TestUtil; import androidx.test.core.app.ApplicationProvider; import androidx.test.ext.junit.runners.AndroidJUnit4; +import java.util.ArrayList; +import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; @@ -67,4 +70,353 @@ public void seek_afterSeekMapSent_seekMapRemainsValid() throws Exception { assertThat(trackAwareSeekMap.getSeekPoints(timeStampUs, videoTrackId).first) .isEqualTo(expectedTrackSpecificSeekPoint); } + + private static final int SEGMENT_CONTENT_POSITION = 52; + private static final int PRIMARY_SEEK_ENTRY_CUES_ID_OFFSET = 93; + private static final int PRIMARY_SEEK_ENTRY_CUES_POS_OFFSET = 100; + private static final long CUES_FILE_POSITION = 107445; + private static final long CLUSTER_FILE_POSITION = 5562; + private static final long CLUSTER_CONTENT_POSITION = 5569; + + private static final byte[] ID_SEEK_HEAD_BYTES = new byte[] {0x11, 0x4D, (byte) 0x9B, 0x74}; + private static final byte[] ID_CUES_BYTES = new byte[] {0x1C, 0x53, (byte) 0xBB, 0x6B}; + private static final byte[] ID_CLUSTER_BYTES = new byte[] {0x1F, 0x43, (byte) 0xB6, 0x75}; + + private static byte[] buildSeekHead(byte[] targetId, long targetFilePosition) { + long relativePosition = targetFilePosition - SEGMENT_CONTENT_POSITION; + byte[] seekPos = + new byte[] { + 0x53, + (byte) 0xAC, + (byte) 0x83, + (byte) ((relativePosition >> 16) & 0xFF), + (byte) ((relativePosition >> 8) & 0xFF), + (byte) (relativePosition & 0xFF) + }; + byte[] seekId = + new byte[] { + 0x53, (byte) 0xAB, (byte) 0x84, targetId[0], targetId[1], targetId[2], targetId[3] + }; + int seekContentLen = seekId.length + seekPos.length; + byte[] seek = new byte[2 + 1 + seekContentLen]; + seek[0] = 0x4D; + seek[1] = (byte) 0xBB; + seek[2] = (byte) (0x80 | seekContentLen); + System.arraycopy(seekId, 0, seek, 3, seekId.length); + System.arraycopy(seekPos, 0, seek, 3 + seekId.length, seekPos.length); + + byte[] seekHead = new byte[4 + 1 + seek.length]; + seekHead[0] = 0x11; + seekHead[1] = 0x4D; + seekHead[2] = (byte) 0x9B; + seekHead[3] = 0x74; + seekHead[4] = (byte) (0x80 | seek.length); + System.arraycopy(seek, 0, seekHead, 5, seek.length); + return seekHead; + } + + private static void updatePrimarySeekHeadTarget( + byte[] fileBytes, byte[] targetId, long targetFilePosition) { + System.arraycopy(targetId, 0, fileBytes, PRIMARY_SEEK_ENTRY_CUES_ID_OFFSET, 4); + long relativePosition = targetFilePosition - SEGMENT_CONTENT_POSITION; + fileBytes[PRIMARY_SEEK_ENTRY_CUES_POS_OFFSET] = (byte) ((relativePosition >> 16) & 0xFF); + fileBytes[PRIMARY_SEEK_ENTRY_CUES_POS_OFFSET + 1] = (byte) ((relativePosition >> 8) & 0xFF); + fileBytes[PRIMARY_SEEK_ENTRY_CUES_POS_OFFSET + 2] = (byte) (relativePosition & 0xFF); + } + + private static byte[] concat(byte[] first, byte[]... rest) { + int totalLength = first.length; + for (byte[] b : rest) { + totalLength += b.length; + } + byte[] result = new byte[totalLength]; + System.arraycopy(first, 0, result, 0, first.length); + int offset = first.length; + for (byte[] b : rest) { + System.arraycopy(b, 0, result, offset, b.length); + offset += b.length; + } + return result; + } + + private static void readToEnd(MatroskaExtractor extractor, FakeExtractorInput input) + throws Exception { + PositionHolder positionHolder = new PositionHolder(); + int readResult = Extractor.RESULT_CONTINUE; + while (readResult != Extractor.RESULT_END_OF_INPUT) { + readResult = extractor.read(input, positionHolder); + if (readResult == Extractor.RESULT_SEEK) { + input.setPosition((int) positionHolder.position); + } + } + } + + private static void updateSegmentSize(byte[] fileBytes) { + long segmentDataLength = fileBytes.length - SEGMENT_CONTENT_POSITION; + fileBytes[48] = (byte) ((segmentDataLength >> 24) & 0xFF); + fileBytes[49] = (byte) ((segmentDataLength >> 16) & 0xFF); + fileBytes[50] = (byte) ((segmentDataLength >> 8) & 0xFF); + fileBytes[51] = (byte) (segmentDataLength & 0xFF); + } + + private static List readToEndAndRecordSeeks( + MatroskaExtractor extractor, FakeExtractorInput input) throws Exception { + List seeks = new ArrayList<>(); + PositionHolder positionHolder = new PositionHolder(); + int readResult = Extractor.RESULT_CONTINUE; + int maxSeeks = 1000; + while (readResult != Extractor.RESULT_END_OF_INPUT && maxSeeks-- > 0) { + readResult = extractor.read(input, positionHolder); + if (readResult == Extractor.RESULT_SEEK) { + seeks.add(positionHolder.position); + input.setPosition((int) positionHolder.position); + } + } + return seeks; + } + + @Test + public void read_withSecondarySeekHeadPointingToCues_formatsEmittedBeforeSamplesAndSeekMapIsSeekable() + throws Exception { + byte[] baseData = + TestUtil.getByteArray(ApplicationProvider.getApplicationContext(), "media/mkv/sample.mkv"); + long secondarySeekHeadPos = baseData.length; + byte[] secondarySeekHead = buildSeekHead(ID_CUES_BYTES, CUES_FILE_POSITION); + updatePrimarySeekHeadTarget(baseData, ID_SEEK_HEAD_BYTES, secondarySeekHeadPos); + byte[] testData = concat(baseData, secondarySeekHead); + + MatroskaExtractor extractor = new MatroskaExtractor(SubtitleParser.Factory.UNSUPPORTED); + FakeExtractorOutput output = new FakeExtractorOutput(); + extractor.init(output); + FakeExtractorInput input = new FakeExtractorInput.Builder().setData(testData).build(); + + readToEnd(extractor, input); + + assertThat(output.seekMap).isNotNull(); + assertThat(output.seekMap.isSeekable()).isTrue(); + assertThat(output.numberOfTracks).isGreaterThan(0); + } + + @Test + public void read_withMultipleSecondarySeekHeadHops_resolvesCuesSuccessfully() + throws Exception { + byte[] baseData = + TestUtil.getByteArray(ApplicationProvider.getApplicationContext(), "media/mkv/sample.mkv"); + long posA = baseData.length; + byte[] seekHeadA = buildSeekHead(ID_SEEK_HEAD_BYTES, 0); + long posB = posA + seekHeadA.length; + byte[] seekHeadB = buildSeekHead(ID_SEEK_HEAD_BYTES, 0); + long posC = posB + seekHeadB.length; + byte[] seekHeadC = buildSeekHead(ID_CUES_BYTES, CUES_FILE_POSITION); + + seekHeadB = buildSeekHead(ID_SEEK_HEAD_BYTES, posC); + seekHeadA = buildSeekHead(ID_SEEK_HEAD_BYTES, posB); + updatePrimarySeekHeadTarget(baseData, ID_SEEK_HEAD_BYTES, posA); + + byte[] testData = concat(baseData, seekHeadA, seekHeadB, seekHeadC); + + MatroskaExtractor extractor = new MatroskaExtractor(SubtitleParser.Factory.UNSUPPORTED); + FakeExtractorOutput output = new FakeExtractorOutput(); + extractor.init(output); + FakeExtractorInput input = new FakeExtractorInput.Builder().setData(testData).build(); + + readToEnd(extractor, input); + + assertThat(output.seekMap).isNotNull(); + assertThat(output.seekMap.isSeekable()).isTrue(); + assertThat(output.numberOfTracks).isGreaterThan(0); + } + + @Test + public void read_withSecondarySeekHeadContainingOnlyClusterEntries_playsWithoutError() + throws Exception { + byte[] baseData = + TestUtil.getByteArray(ApplicationProvider.getApplicationContext(), "media/mkv/sample.mkv"); + long secondarySeekHeadPos = baseData.length; + byte[] secondarySeekHead = buildSeekHead(ID_CLUSTER_BYTES, CLUSTER_FILE_POSITION); + updatePrimarySeekHeadTarget(baseData, ID_SEEK_HEAD_BYTES, secondarySeekHeadPos); + byte[] testData = concat(baseData, secondarySeekHead); + + MatroskaExtractor extractor = new MatroskaExtractor(SubtitleParser.Factory.UNSUPPORTED); + FakeExtractorOutput output = new FakeExtractorOutput(); + extractor.init(output); + FakeExtractorInput input = new FakeExtractorInput.Builder().setData(testData).build(); + + readToEnd(extractor, input); + + assertThat(output.seekMap).isNotNull(); + assertThat(output.seekMap.isSeekable()).isFalse(); + assertThat(output.numberOfTracks).isGreaterThan(0); + } + + @Test + public void read_withCyclicSeekHeads_terminatesSafelyAndCompletesPlayback() + throws Exception { + byte[] baseData = + TestUtil.getByteArray(ApplicationProvider.getApplicationContext(), "media/mkv/sample.mkv"); + long posA = baseData.length; + byte[] seekHeadA = buildSeekHead(ID_SEEK_HEAD_BYTES, 0); + long posB = posA + seekHeadA.length; + byte[] seekHeadB = buildSeekHead(ID_SEEK_HEAD_BYTES, posA); + seekHeadA = buildSeekHead(ID_SEEK_HEAD_BYTES, posB); + updatePrimarySeekHeadTarget(baseData, ID_SEEK_HEAD_BYTES, posA); + + byte[] testData = concat(baseData, seekHeadA, seekHeadB); + + MatroskaExtractor extractor = new MatroskaExtractor(SubtitleParser.Factory.UNSUPPORTED); + FakeExtractorOutput output = new FakeExtractorOutput(); + extractor.init(output); + FakeExtractorInput input = new FakeExtractorInput.Builder().setData(testData).build(); + + readToEnd(extractor, input); + + assertThat(output.seekMap).isNotNull(); + assertThat(output.seekMap.isSeekable()).isFalse(); + assertThat(output.numberOfTracks).isGreaterThan(0); + } + + @Test + public void seek_beforeSeekMapSent_resetsTraversalStateAndAllowsReExtraction() + throws Exception { + byte[] baseData = + TestUtil.getByteArray(ApplicationProvider.getApplicationContext(), "media/mkv/sample.mkv"); + long secondarySeekHeadPos = baseData.length; + byte[] secondarySeekHead = buildSeekHead(ID_CUES_BYTES, CUES_FILE_POSITION); + updatePrimarySeekHeadTarget(baseData, ID_SEEK_HEAD_BYTES, secondarySeekHeadPos); + byte[] testData = concat(baseData, secondarySeekHead); + + MatroskaExtractor extractor = new MatroskaExtractor(SubtitleParser.Factory.UNSUPPORTED); + FakeExtractorOutput output = new FakeExtractorOutput(); + extractor.init(output); + FakeExtractorInput input = new FakeExtractorInput.Builder().setData(testData).build(); + + PositionHolder positionHolder = new PositionHolder(); + int readResult = extractor.read(input, positionHolder); + if (readResult == Extractor.RESULT_SEEK) { + input.setPosition((int) positionHolder.position); + } + assertThat(output.seekMap).isNull(); + + // Reset before seek map was sent + extractor.seek(0, 0); + input.setPosition(0); + + // Re-extract from beginning + readToEnd(extractor, input); + + assertThat(output.seekMap).isNotNull(); + assertThat(output.seekMap.isSeekable()).isTrue(); + assertThat(output.numberOfTracks).isGreaterThan(0); + } + + @Test + public void read_withCuesReferencePointingToCluster_terminatesSeeksAndOutputsSamples() + throws Exception { + byte[] baseData = + TestUtil.getByteArray(ApplicationProvider.getApplicationContext(), "media/mkv/sample.mkv"); + long secondarySeekHeadPos = baseData.length; + byte[] secondarySeekHead = buildSeekHead(ID_CUES_BYTES, CLUSTER_FILE_POSITION); + updatePrimarySeekHeadTarget(baseData, ID_SEEK_HEAD_BYTES, secondarySeekHeadPos); + byte[] testData = concat(baseData, secondarySeekHead); + updateSegmentSize(testData); + + MatroskaExtractor extractor = new MatroskaExtractor(SubtitleParser.Factory.UNSUPPORTED); + FakeExtractorOutput output = new FakeExtractorOutput(); + extractor.init(output); + FakeExtractorInput input = new FakeExtractorInput.Builder().setData(testData).build(); + + List seeks = readToEndAndRecordSeeks(extractor, input); + + assertThat(seeks).containsExactly(secondarySeekHeadPos, CLUSTER_FILE_POSITION).inOrder(); + assertThat(output.seekMap).isNotNull(); + assertThat(output.seekMap.isSeekable()).isFalse(); + assertThat(output.numberOfTracks).isGreaterThan(0); + assertThat(output.trackOutputs.get(1).getSampleCount()).isGreaterThan(0); + assertThat(output.trackOutputs.get(1).getSampleTimeUs(0)).isEqualTo(67_000); + } + + @Test + public void read_withCuesReferenceReachingEof_terminatesFallbackAndOutputsSamples() + throws Exception { + byte[] baseData = + TestUtil.getByteArray(ApplicationProvider.getApplicationContext(), "media/mkv/sample.mkv"); + long secondarySeekHeadPos = baseData.length; + long voidPos = secondarySeekHeadPos + 21; // 108557 + byte[] secondarySeekHead = buildSeekHead(ID_CUES_BYTES, voidPos); + byte[] voidElement = new byte[] {(byte) 0xEC, (byte) 0x80}; // Empty Void element + updatePrimarySeekHeadTarget(baseData, ID_SEEK_HEAD_BYTES, secondarySeekHeadPos); + byte[] testData = concat(baseData, secondarySeekHead, voidElement); + updateSegmentSize(testData); + + MatroskaExtractor extractor = new MatroskaExtractor(SubtitleParser.Factory.UNSUPPORTED); + FakeExtractorOutput output = new FakeExtractorOutput(); + extractor.init(output); + FakeExtractorInput input = new FakeExtractorInput.Builder().setData(testData).build(); + + List seeks = readToEndAndRecordSeeks(extractor, input); + + assertThat(seeks).contains(voidPos); + assertThat(output.seekMap).isNotNull(); + assertThat(output.seekMap.isSeekable()).isFalse(); + assertThat(output.numberOfTracks).isGreaterThan(0); + assertThat(output.trackOutputs.get(1).getSampleCount()).isGreaterThan(0); + assertThat(output.trackOutputs.get(1).getSampleTimeUs(0)).isEqualTo(67_000); + } + + @Test + public void read_withCuesReferencePointingToSecondarySeekHeadWithoutCues_terminatesAndOutputsSamples() + throws Exception { + byte[] baseData = + TestUtil.getByteArray(ApplicationProvider.getApplicationContext(), "media/mkv/sample.mkv"); + long posA = baseData.length; + long posB = posA + 21; + byte[] seekHeadA = buildSeekHead(ID_CUES_BYTES, posB); + byte[] seekHeadB = buildSeekHead(ID_CLUSTER_BYTES, CLUSTER_FILE_POSITION); + updatePrimarySeekHeadTarget(baseData, ID_SEEK_HEAD_BYTES, posA); + byte[] testData = concat(baseData, seekHeadA, seekHeadB); + updateSegmentSize(testData); + + MatroskaExtractor extractor = new MatroskaExtractor(SubtitleParser.Factory.UNSUPPORTED); + FakeExtractorOutput output = new FakeExtractorOutput(); + extractor.init(output); + FakeExtractorInput input = new FakeExtractorInput.Builder().setData(testData).build(); + + List seeks = readToEndAndRecordSeeks(extractor, input); + + assertThat(seeks).containsExactly(posA, posB, CLUSTER_CONTENT_POSITION).inOrder(); + assertThat(output.seekMap).isNotNull(); + assertThat(output.seekMap.isSeekable()).isFalse(); + assertThat(output.numberOfTracks).isGreaterThan(0); + assertThat(output.trackOutputs.get(1).getSampleCount()).isGreaterThan(0); + assertThat(output.trackOutputs.get(1).getSampleTimeUs(0)).isEqualTo(67_000); + } + + @Test + public void read_withCyclicCuesReferences_terminatesSafelyAndOutputsSamples() + throws Exception { + byte[] baseData = + TestUtil.getByteArray(ApplicationProvider.getApplicationContext(), "media/mkv/sample.mkv"); + long posA = baseData.length; + long posB = posA + 21; + byte[] seekHeadA = buildSeekHead(ID_CUES_BYTES, posB); + byte[] seekHeadB = buildSeekHead(ID_CUES_BYTES, posA); + updatePrimarySeekHeadTarget(baseData, ID_SEEK_HEAD_BYTES, posA); + byte[] testData = concat(baseData, seekHeadA, seekHeadB); + updateSegmentSize(testData); + + MatroskaExtractor extractor = new MatroskaExtractor(SubtitleParser.Factory.UNSUPPORTED); + FakeExtractorOutput output = new FakeExtractorOutput(); + extractor.init(output); + FakeExtractorInput input = new FakeExtractorInput.Builder().setData(testData).build(); + + List seeks = readToEndAndRecordSeeks(extractor, input); + + assertThat(seeks).containsExactly(posA, posB, CLUSTER_CONTENT_POSITION).inOrder(); + assertThat(output.seekMap).isNotNull(); + assertThat(output.seekMap.isSeekable()).isFalse(); + assertThat(output.numberOfTracks).isGreaterThan(0); + assertThat(output.trackOutputs.get(1).getSampleCount()).isGreaterThan(0); + assertThat(output.trackOutputs.get(1).getSampleTimeUs(0)).isEqualTo(67_000); + } } +