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 @@ -67,6 +67,8 @@
import androidx.media3.extractor.text.SubtitleParser;
import androidx.media3.extractor.text.SubtitleTranscodingExtractorOutput;
import com.google.common.collect.ImmutableList;
import com.google.common.io.ByteStreams;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
Expand All @@ -84,6 +86,8 @@
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;
import org.checkerframework.checker.nullness.qual.EnsuresNonNull;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
import org.checkerframework.checker.nullness.qual.RequiresNonNull;
Expand Down Expand Up @@ -263,6 +267,9 @@ public static ExtractorsFactory newFactory(SubtitleParser.Factory subtitleParser
private static final int ID_CONTENT_COMPRESSION = 0x5034;
private static final int ID_CONTENT_COMPRESSION_ALGORITHM = 0x4254;
private static final int ID_CONTENT_COMPRESSION_SETTINGS = 0x4255;
private static final int CONTENT_COMPRESSION_ZLIB = 0;
private static final int CONTENT_COMPRESSION_HEADER_STRIPPING = 3;
private static final int MAX_INFLATED_SUBTITLE_SIZE = 1024 * 1024;
private static final int ID_CONTENT_ENCRYPTION = 0x5035;
private static final int ID_CONTENT_ENCRYPTION_ALGORITHM = 0x47E1;
private static final int ID_CONTENT_ENCRYPTION_KEY_ID = 0x47E2;
Expand Down Expand Up @@ -887,6 +894,9 @@ protected void startMasterElement(int id, long contentPosition, long contentSize
case ID_CONTENT_ENCODING:
// TODO: check and fail if more than one content encoding is present.
break;
case ID_CONTENT_COMPRESSION:
getCurrentTrack(id).contentCompressionAlgorithm = CONTENT_COMPRESSION_ZLIB;
break;
case ID_CONTENT_ENCRYPTION:
getCurrentTrack(id).hasContentEncryption = true;
break;
Expand Down Expand Up @@ -1062,7 +1072,9 @@ protected void endMasterElement(int id) throws ParserException {
break;
case ID_CONTENT_ENCODINGS:
assertInTrackEntry(id);
if (currentTrack.hasContentEncryption && currentTrack.sampleStrippedBytes != null) {
if (currentTrack.hasContentEncryption
&& (currentTrack.sampleStrippedBytes != null
|| currentTrack.contentCompressionAlgorithm != C.INDEX_UNSET)) {
throw ParserException.createForMalformedContainer(
"Combining encryption and compression is not supported", /* cause= */ null);
}
Expand All @@ -1073,7 +1085,21 @@ protected void endMasterElement(int id) throws ParserException {
throw ParserException.createForMalformedContainer(
"CodecId is missing in TrackEntry element", /* cause= */ null);
} else {
if (isCodecSupported(currentTrack.codecId)) {
boolean zlibCompressed =
currentTrack.contentCompressionAlgorithm == CONTENT_COMPRESSION_ZLIB;
if (zlibCompressed && currentTrack.type != C.TRACK_TYPE_TEXT) {
throw ParserException.createForUnsupportedContainerFeature(
"Zlib compression is only supported for subtitle tracks");
}
boolean hasCompressionSettings =
currentTrack.sampleStrippedBytes != null
&& currentTrack.sampleStrippedBytes.length != 0;
if (zlibCompressed
&& (!supportsZlibCompression(currentTrack.codecId) || hasCompressionSettings)) {
Log.w(
TAG,
"Skipping unsupported zlib-compressed subtitle track: " + currentTrack.codecId);
} else if (isCodecSupported(currentTrack.codecId)) {
currentTrack.initializeFormat(currentTrack.number);
currentTrack.output = extractorOutput.track(currentTrack.number, currentTrack.type);
tracks.put(currentTrack.number, currentTrack);
Expand Down Expand Up @@ -1286,11 +1312,11 @@ protected void integerElement(int id, long value) throws ParserException {
}
break;
case ID_CONTENT_COMPRESSION_ALGORITHM:
// This extractor only supports header stripping.
if (value != 3) {
if (value != CONTENT_COMPRESSION_ZLIB && value != CONTENT_COMPRESSION_HEADER_STRIPPING) {
throw ParserException.createForMalformedContainer(
"ContentCompAlgo " + value + " not supported", /* cause= */ null);
}
getCurrentTrack(id).contentCompressionAlgorithm = (int) value;
break;
case ID_CONTENT_ENCRYPTION_ALGORITHM:
// Only the value 5 (AES) is allowed according to the WebM specification.
Expand Down Expand Up @@ -1547,7 +1573,7 @@ protected void binaryElement(int id, int contentSize, ExtractorInput input) thro
break;
case ID_CONTENT_COMPRESSION_SETTINGS:
assertInTrackEntry(id);
// This extractor only supports header stripping, so the payload is the stripped bytes.
// For header stripping, the payload is the stripped bytes.
currentTrack.sampleStrippedBytes = new byte[contentSize];
input.readFully(currentTrack.sampleStrippedBytes, 0, contentSize);
break;
Expand Down Expand Up @@ -1793,10 +1819,7 @@ private void commitSampleToOutput(
track.trueHdSampleRechunker.sampleMetadata(
track.output, timeUs, flags, size, offset, track.cryptoData);
} else {
if (CODEC_ID_SUBRIP.equals(track.codecId)
|| CODEC_ID_ASS.equals(track.codecId)
|| CODEC_ID_SSA.equals(track.codecId)
|| CODEC_ID_VTT.equals(track.codecId)) {
if (isTextSubtitleCodec(track.codecId)) {
if (blockSampleCount > 1) {
Log.w(TAG, "Skipping subtitle sample in laced block.");
} else if (blockDurationUs == C.TIME_UNSET) {
Expand Down Expand Up @@ -1866,13 +1889,13 @@ private void readScratch(ExtractorInput input, int requiredLength) throws IOExce
private int writeSampleData(ExtractorInput input, Track track, int size, boolean isBlockGroup)
throws IOException {
if (CODEC_ID_SUBRIP.equals(track.codecId)) {
writeSubtitleSampleData(input, SUBRIP_PREFIX, size);
writeSubtitleSampleData(input, SUBRIP_PREFIX, size, track);
return finishWriteSampleData();
} else if (CODEC_ID_ASS.equals(track.codecId) || CODEC_ID_SSA.equals(track.codecId)) {
writeSubtitleSampleData(input, SSA_PREFIX, size);
writeSubtitleSampleData(input, SSA_PREFIX, size, track);
return finishWriteSampleData();
} else if (CODEC_ID_VTT.equals(track.codecId)) {
writeSubtitleSampleData(input, VTT_PREFIX, size);
writeSubtitleSampleData(input, VTT_PREFIX, size, track);
return finishWriteSampleData();
}

Expand Down Expand Up @@ -2085,8 +2108,8 @@ private void resetWriteSampleData() {
sampleStrippedBytes.reset(/* limit= */ 0);
}

private void writeSubtitleSampleData(ExtractorInput input, byte[] samplePrefix, int size)
throws IOException {
private void writeSubtitleSampleData(
ExtractorInput input, byte[] samplePrefix, int size, Track track) throws IOException {
int sizeWithPrefix = samplePrefix.length + size;
if (subtitleSample.capacity() < sizeWithPrefix) {
// Initialize subripSample to contain the required prefix and have space to hold a subtitle
Expand All @@ -2096,12 +2119,45 @@ private void writeSubtitleSampleData(ExtractorInput input, byte[] samplePrefix,
System.arraycopy(samplePrefix, 0, subtitleSample.getData(), 0, samplePrefix.length);
}
input.readFully(subtitleSample.getData(), samplePrefix.length, size);
if (track.contentCompressionAlgorithm == CONTENT_COMPRESSION_ZLIB) {
byte[] inflated = inflateSubtitleSample(subtitleSample.getData(), samplePrefix.length, size);
sizeWithPrefix = samplePrefix.length + inflated.length;
subtitleSample.ensureCapacity(sizeWithPrefix);
System.arraycopy(inflated, 0, subtitleSample.getData(), samplePrefix.length, inflated.length);
}
subtitleSample.setPosition(0);
subtitleSample.setLimit(sizeWithPrefix);
// Defer writing the data to the track output. We need to modify the sample data by setting
// the correct end timecode, which we might not have yet.
}

private static byte[] inflateSubtitleSample(byte[] data, int offset, int length)
throws ParserException {
byte[] inflated;
boolean finished;
Inflater inflater = new Inflater();
try (InflaterInputStream stream =
new InflaterInputStream(new ByteArrayInputStream(data, offset, length), inflater)) {
inflated =
ByteStreams.toByteArray(ByteStreams.limit(stream, MAX_INFLATED_SUBTITLE_SIZE + 1L));
finished = inflater.finished();
} catch (IOException e) {
throw ParserException.createForMalformedContainer("Invalid zlib subtitle sample", e);
} finally {
inflater.end();
}
if (inflated.length > MAX_INFLATED_SUBTITLE_SIZE) {
throw ParserException.createForUnsupportedContainerFeature(
"Inflated subtitle sample exceeds " + MAX_INFLATED_SUBTITLE_SIZE + " bytes");
}
if (!finished) {
// InflaterInputStream also returns EOF when the stream requires a preset dictionary.
throw ParserException.createForMalformedContainer(
"Invalid zlib subtitle sample", /* cause= */ null);
}
return inflated;
}

/**
* Overwrites the end timecode in {@code subtitleData} with the correctly formatted time derived
* from {@code durationUs}.
Expand Down Expand Up @@ -2244,6 +2300,20 @@ private long scaleTimecodeToUs(long unscaledTimecode) throws ParserException {
return Util.scaleLargeTimestamp(unscaledTimecode, timecodeScale, 1000);
}

private static boolean supportsZlibCompression(String codecId) {
// PGS and VobSub handle compressed samples in their subtitle parsers.
return isTextSubtitleCodec(codecId)
|| CODEC_ID_PGS.equals(codecId)
|| CODEC_ID_VOBSUB.equals(codecId);
}

private static boolean isTextSubtitleCodec(String codecId) {
return CODEC_ID_SUBRIP.equals(codecId)
|| CODEC_ID_ASS.equals(codecId)
|| CODEC_ID_SSA.equals(codecId)
|| CODEC_ID_VTT.equals(codecId);
}

private static boolean isCodecSupported(String codecId) {
switch (codecId) {
case CODEC_ID_VP8:
Expand Down Expand Up @@ -2430,6 +2500,7 @@ protected static final class Track {
public int defaultSampleDurationNs;
public int maxBlockAdditionId;
private int blockAddIdType;
public int contentCompressionAlgorithm = C.INDEX_UNSET;
public boolean hasContentEncryption;
public byte @MonotonicNonNull [] sampleStrippedBytes;
public TrackOutput.@MonotonicNonNull CryptoData cryptoData;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,21 +17,27 @@

import static androidx.media3.extractor.Extractor.RESULT_SEEK;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertThrows;
import static org.mockito.AdditionalAnswers.delegatesTo;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;

import android.content.Context;
import androidx.media3.common.C;
import androidx.media3.common.Format;
import androidx.media3.common.ParserException;
import androidx.media3.extractor.PositionHolder;
import androidx.media3.extractor.SeekPoint;
import androidx.media3.extractor.TrackAwareSeekMap;
import androidx.media3.extractor.text.CueDecoder;
import androidx.media3.extractor.text.CuesWithTiming;
import androidx.media3.extractor.text.DefaultSubtitleParserFactory;
import androidx.media3.extractor.text.ForwardingSubtitleParserFactory;
import androidx.media3.extractor.text.SubtitleParser;
import androidx.media3.test.utils.DumpFileAsserts;
import androidx.media3.test.utils.FakeExtractorInput;
import androidx.media3.test.utils.FakeExtractorOutput;
import androidx.media3.test.utils.FakeTrackOutput;
import androidx.media3.test.utils.TestUtil;
import androidx.test.core.app.ApplicationProvider;
import androidx.test.ext.junit.runners.AndroidJUnit4;
Expand All @@ -45,6 +51,64 @@
@RunWith(AndroidJUnit4.class)
public class MatroskaExtractorNonParameterizedTest {

@Test
public void read_explicitZlibSubtitle_outputsCue() throws Exception {
assertZlibSubtitleCue("sample_with_zlib_subtitle.mkv");
}

@Test
public void read_defaultZlibSubtitleWithSmallerWindow_outputsCue() throws Exception {
assertZlibSubtitleCue("sample_with_default_zlib_subtitle.mkv");
}

@Test
public void read_truncatedZlibSubtitle_throwsParserException() {
ParserException exception =
assertThrows(
ParserException.class,
() -> readZlibSubtitleFile("sample_with_truncated_zlib_subtitle.mkv"));
assertThat(exception).hasMessageThat().contains("Invalid zlib subtitle sample");
}

@Test
public void read_zlibSubtitleRequiringDictionary_throwsParserException() {
ParserException exception =
assertThrows(
ParserException.class,
() -> readZlibSubtitleFile("sample_with_zlib_dictionary_subtitle.mkv"));
assertThat(exception).hasMessageThat().contains("Invalid zlib subtitle sample");
}

@Test
public void read_oversizedZlibSubtitle_throwsParserException() {
ParserException exception =
assertThrows(
ParserException.class,
() -> readZlibSubtitleFile("sample_with_oversized_zlib_subtitle.mkv"));
assertThat(exception).hasMessageThat().contains("Inflated subtitle sample exceeds");
}

private static void assertZlibSubtitleCue(String fileName) throws Exception {
FakeExtractorOutput output = readZlibSubtitleFile(fileName);
FakeTrackOutput track =
Iterables.getOnlyElement(output.getTrackOutputsForType(C.TRACK_TYPE_TEXT));
assertThat(track.getSampleCount()).isEqualTo(1);
byte[] sample = track.getSampleData(0);
CuesWithTiming cues =
new CueDecoder().decode(track.getSampleTimeUs(0), sample, 0, sample.length);
assertThat(cues.startTimeUs).isEqualTo(250_000);
assertThat(cues.durationUs).isEqualTo(875_000);
assertThat(Iterables.getOnlyElement(cues.cues).text.toString())
.isEqualTo("One compressed subtitle cue.");
}

private static FakeExtractorOutput readZlibSubtitleFile(String fileName) throws Exception {
return TestUtil.extractAllSamplesFromFile(
new MatroskaExtractor(new DefaultSubtitleParserFactory()),
ApplicationProvider.getApplicationContext(),
"media/mkv/" + fileName);
}

@Test
public void seek_afterSeekMapSent_seekMapRemainsValid() throws Exception {
String fileName = "media/mkv/sample.mkv";
Expand Down
Loading