use of com.google.android.exoplayer2.extractor.ExtractorInput in project ExoPlayer by google.
the class FlvExtractor method readTagData.
/**
* Reads the body of a tag from the provided {@link ExtractorInput}.
*
* @param input The {@link ExtractorInput} from which to read.
* @return True if the data was consumed by a reader. False if it was skipped.
* @throws IOException If an error occurred reading or parsing data from the source.
*/
@RequiresNonNull("extractorOutput")
private boolean readTagData(ExtractorInput input) throws IOException {
boolean wasConsumed = true;
boolean wasSampleOutput = false;
long timestampUs = getCurrentTimestampUs();
if (tagType == TAG_TYPE_AUDIO && audioReader != null) {
ensureReadyForMediaOutput();
wasSampleOutput = audioReader.consume(prepareTagData(input), timestampUs);
} else if (tagType == TAG_TYPE_VIDEO && videoReader != null) {
ensureReadyForMediaOutput();
wasSampleOutput = videoReader.consume(prepareTagData(input), timestampUs);
} else if (tagType == TAG_TYPE_SCRIPT_DATA && !outputSeekMap) {
wasSampleOutput = metadataReader.consume(prepareTagData(input), timestampUs);
long durationUs = metadataReader.getDurationUs();
if (durationUs != C.TIME_UNSET) {
extractorOutput.seekMap(new IndexSeekMap(metadataReader.getKeyFrameTagPositions(), metadataReader.getKeyFrameTimesUs(), durationUs));
outputSeekMap = true;
}
} else {
input.skipFully(tagDataSize);
wasConsumed = false;
}
if (!outputFirstSample && wasSampleOutput) {
outputFirstSample = true;
mediaTagTimestampOffsetUs = metadataReader.getDurationUs() == C.TIME_UNSET ? -tagTimestampUs : 0;
}
// There's a 4 byte previous tag size before the next header.
bytesToNextTagHeader = 4;
state = STATE_SKIPPING_TO_TAG_HEADER;
return wasConsumed;
}
use of com.google.android.exoplayer2.extractor.ExtractorInput in project ExoPlayer by google.
the class MatroskaExtractor method writeSampleData.
/**
* Writes data for a single sample to the track output.
*
* @param input The input from which to read sample data.
* @param track The track to output the sample to.
* @param size The size of the sample data on the input side.
* @return The final size of the written sample.
* @throws IOException If an error occurs reading from the input.
*/
@RequiresNonNull("#2.output")
private int writeSampleData(ExtractorInput input, Track track, int size) throws IOException {
if (CODEC_ID_SUBRIP.equals(track.codecId)) {
writeSubtitleSampleData(input, SUBRIP_PREFIX, size);
return finishWriteSampleData();
} else if (CODEC_ID_ASS.equals(track.codecId)) {
writeSubtitleSampleData(input, SSA_PREFIX, size);
return finishWriteSampleData();
} else if (CODEC_ID_VTT.equals(track.codecId)) {
writeSubtitleSampleData(input, VTT_PREFIX, size);
return finishWriteSampleData();
}
TrackOutput output = track.output;
if (!sampleEncodingHandled) {
if (track.hasContentEncryption) {
// If the sample is encrypted, read its encryption signal byte and set the IV size.
// Clear the encrypted flag.
blockFlags &= ~C.BUFFER_FLAG_ENCRYPTED;
if (!sampleSignalByteRead) {
input.readFully(scratch.getData(), 0, 1);
sampleBytesRead++;
if ((scratch.getData()[0] & 0x80) == 0x80) {
throw ParserException.createForMalformedContainer("Extension bit is set in signal byte", /* cause= */
null);
}
sampleSignalByte = scratch.getData()[0];
sampleSignalByteRead = true;
}
boolean isEncrypted = (sampleSignalByte & 0x01) == 0x01;
if (isEncrypted) {
boolean hasSubsampleEncryption = (sampleSignalByte & 0x02) == 0x02;
blockFlags |= C.BUFFER_FLAG_ENCRYPTED;
if (!sampleInitializationVectorRead) {
input.readFully(encryptionInitializationVector.getData(), 0, ENCRYPTION_IV_SIZE);
sampleBytesRead += ENCRYPTION_IV_SIZE;
sampleInitializationVectorRead = true;
// Write the signal byte, containing the IV size and the subsample encryption flag.
scratch.getData()[0] = (byte) (ENCRYPTION_IV_SIZE | (hasSubsampleEncryption ? 0x80 : 0x00));
scratch.setPosition(0);
output.sampleData(scratch, 1, TrackOutput.SAMPLE_DATA_PART_ENCRYPTION);
sampleBytesWritten++;
// Write the IV.
encryptionInitializationVector.setPosition(0);
output.sampleData(encryptionInitializationVector, ENCRYPTION_IV_SIZE, TrackOutput.SAMPLE_DATA_PART_ENCRYPTION);
sampleBytesWritten += ENCRYPTION_IV_SIZE;
}
if (hasSubsampleEncryption) {
if (!samplePartitionCountRead) {
input.readFully(scratch.getData(), 0, 1);
sampleBytesRead++;
scratch.setPosition(0);
samplePartitionCount = scratch.readUnsignedByte();
samplePartitionCountRead = true;
}
int samplePartitionDataSize = samplePartitionCount * 4;
scratch.reset(samplePartitionDataSize);
input.readFully(scratch.getData(), 0, samplePartitionDataSize);
sampleBytesRead += samplePartitionDataSize;
short subsampleCount = (short) (1 + (samplePartitionCount / 2));
int subsampleDataSize = 2 + 6 * subsampleCount;
if (encryptionSubsampleDataBuffer == null || encryptionSubsampleDataBuffer.capacity() < subsampleDataSize) {
encryptionSubsampleDataBuffer = ByteBuffer.allocate(subsampleDataSize);
}
encryptionSubsampleDataBuffer.position(0);
encryptionSubsampleDataBuffer.putShort(subsampleCount);
// Loop through the partition offsets and write out the data in the way ExoPlayer
// wants it (ISO 23001-7 Part 7):
// 2 bytes - sub sample count.
// for each sub sample:
// 2 bytes - clear data size.
// 4 bytes - encrypted data size.
int partitionOffset = 0;
for (int i = 0; i < samplePartitionCount; i++) {
int previousPartitionOffset = partitionOffset;
partitionOffset = scratch.readUnsignedIntToInt();
if ((i % 2) == 0) {
encryptionSubsampleDataBuffer.putShort((short) (partitionOffset - previousPartitionOffset));
} else {
encryptionSubsampleDataBuffer.putInt(partitionOffset - previousPartitionOffset);
}
}
int finalPartitionSize = size - sampleBytesRead - partitionOffset;
if ((samplePartitionCount % 2) == 1) {
encryptionSubsampleDataBuffer.putInt(finalPartitionSize);
} else {
encryptionSubsampleDataBuffer.putShort((short) finalPartitionSize);
encryptionSubsampleDataBuffer.putInt(0);
}
encryptionSubsampleData.reset(encryptionSubsampleDataBuffer.array(), subsampleDataSize);
output.sampleData(encryptionSubsampleData, subsampleDataSize, TrackOutput.SAMPLE_DATA_PART_ENCRYPTION);
sampleBytesWritten += subsampleDataSize;
}
}
} else if (track.sampleStrippedBytes != null) {
// If the sample has header stripping, prepare to read/output the stripped bytes first.
sampleStrippedBytes.reset(track.sampleStrippedBytes, track.sampleStrippedBytes.length);
}
if (track.maxBlockAdditionId > 0) {
blockFlags |= C.BUFFER_FLAG_HAS_SUPPLEMENTAL_DATA;
blockAdditionalData.reset(/* limit= */
0);
// If there is supplemental data, the structure of the sample data is:
// sample size (4 bytes) || sample data || supplemental data
scratch.reset(/* limit= */
4);
scratch.getData()[0] = (byte) ((size >> 24) & 0xFF);
scratch.getData()[1] = (byte) ((size >> 16) & 0xFF);
scratch.getData()[2] = (byte) ((size >> 8) & 0xFF);
scratch.getData()[3] = (byte) (size & 0xFF);
output.sampleData(scratch, 4, TrackOutput.SAMPLE_DATA_PART_SUPPLEMENTAL);
sampleBytesWritten += 4;
}
sampleEncodingHandled = true;
}
size += sampleStrippedBytes.limit();
if (CODEC_ID_H264.equals(track.codecId) || CODEC_ID_H265.equals(track.codecId)) {
// TODO: Deduplicate with Mp4Extractor.
// Zero the top three bytes of the array that we'll use to decode nal unit lengths, in case
// they're only 1 or 2 bytes long.
byte[] nalLengthData = nalLength.getData();
nalLengthData[0] = 0;
nalLengthData[1] = 0;
nalLengthData[2] = 0;
int nalUnitLengthFieldLength = track.nalUnitLengthFieldLength;
int nalUnitLengthFieldLengthDiff = 4 - track.nalUnitLengthFieldLength;
// start codes as we encounter them.
while (sampleBytesRead < size) {
if (sampleCurrentNalBytesRemaining == 0) {
// Read the NAL length so that we know where we find the next one.
writeToTarget(input, nalLengthData, nalUnitLengthFieldLengthDiff, nalUnitLengthFieldLength);
sampleBytesRead += nalUnitLengthFieldLength;
nalLength.setPosition(0);
sampleCurrentNalBytesRemaining = nalLength.readUnsignedIntToInt();
// Write a start code for the current NAL unit.
nalStartCode.setPosition(0);
output.sampleData(nalStartCode, 4);
sampleBytesWritten += 4;
} else {
// Write the payload of the NAL unit.
int bytesWritten = writeToOutput(input, output, sampleCurrentNalBytesRemaining);
sampleBytesRead += bytesWritten;
sampleBytesWritten += bytesWritten;
sampleCurrentNalBytesRemaining -= bytesWritten;
}
}
} else {
if (track.trueHdSampleRechunker != null) {
checkState(sampleStrippedBytes.limit() == 0);
track.trueHdSampleRechunker.startSample(input);
}
while (sampleBytesRead < size) {
int bytesWritten = writeToOutput(input, output, size - sampleBytesRead);
sampleBytesRead += bytesWritten;
sampleBytesWritten += bytesWritten;
}
}
if (CODEC_ID_VORBIS.equals(track.codecId)) {
// Vorbis decoder in android MediaCodec [1] expects the last 4 bytes of the sample to be the
// number of samples in the current page. This definition holds good only for Ogg and
// irrelevant for Matroska. So we always set this to -1 (the decoder will ignore this value if
// we set it to -1). The android platform media extractor [2] does the same.
// [1]
// https://android.googlesource.com/platform/frameworks/av/+/lollipop-release/media/libstagefright/codecs/vorbis/dec/SoftVorbis.cpp#314
// [2]
// https://android.googlesource.com/platform/frameworks/av/+/lollipop-release/media/libstagefright/NuMediaExtractor.cpp#474
vorbisNumPageSamples.setPosition(0);
output.sampleData(vorbisNumPageSamples, 4);
sampleBytesWritten += 4;
}
return finishWriteSampleData();
}
use of com.google.android.exoplayer2.extractor.ExtractorInput in project ExoPlayer by google.
the class FlacMetadataReaderTest method readSeekTableMetadataBlock_returnsCorrectSeekPoints.
@Test
public void readSeekTableMetadataBlock_returnsCorrectSeekPoints() throws Exception {
ExtractorInput input = buildExtractorInput("media/flac/bear.flac");
// Skip to seek table block.
input.skipFully(FlacConstants.STREAM_MARKER_SIZE + FlacConstants.STREAM_INFO_BLOCK_SIZE);
int seekTableBlockSize = 598;
ParsableByteArray scratch = new ParsableByteArray(seekTableBlockSize);
input.read(scratch.getData(), 0, seekTableBlockSize);
FlacStreamMetadata.SeekTable seekTable = FlacMetadataReader.readSeekTableMetadataBlock(scratch);
assertThat(seekTable.pointOffsets[0]).isEqualTo(0);
assertThat(seekTable.pointSampleNumbers[0]).isEqualTo(0);
assertThat(seekTable.pointOffsets[31]).isEqualTo(160602);
assertThat(seekTable.pointSampleNumbers[31]).isEqualTo(126976);
}
use of com.google.android.exoplayer2.extractor.ExtractorInput in project ExoPlayer by google.
the class ExtractorUtilTest method peekFullyQuietly_endNotReached_isTrueAndPeeksData.
@Test
public void peekFullyQuietly_endNotReached_isTrueAndPeeksData() throws Exception {
FakeDataSource testDataSource = new FakeDataSource();
testDataSource.getDataSet().newDefaultData().appendReadData(Arrays.copyOf(TEST_DATA, 3)).appendReadData(Arrays.copyOfRange(TEST_DATA, 3, 6)).appendReadData(Arrays.copyOfRange(TEST_DATA, 6, 9));
testDataSource.open(new DataSpec(Uri.parse(TEST_URI)));
ExtractorInput input = new DefaultExtractorInput(testDataSource, 0, C.LENGTH_UNSET);
byte[] target = new byte[TEST_DATA.length];
int offset = 2;
int length = 4;
boolean hasRead = ExtractorUtil.peekFullyQuietly(input, target, offset, length, /* allowEndOfInput= */
false);
assertThat(hasRead).isTrue();
assertThat(input.getPeekPosition()).isEqualTo(length);
assertThat(Arrays.copyOfRange(target, offset, offset + length)).isEqualTo(Arrays.copyOf(TEST_DATA, length));
}
use of com.google.android.exoplayer2.extractor.ExtractorInput in project ExoPlayer by google.
the class ExtractorUtilTest method readFullyQuietly_endReached_isFalse.
@Test
public void readFullyQuietly_endReached_isFalse() throws Exception {
FakeDataSource testDataSource = new FakeDataSource();
testDataSource.getDataSet().newDefaultData().appendReadData(Arrays.copyOf(TEST_DATA, 3));
testDataSource.open(new DataSpec(Uri.parse(TEST_URI)));
ExtractorInput input = new DefaultExtractorInput(testDataSource, 0, C.LENGTH_UNSET);
byte[] target = new byte[TEST_DATA.length];
int offset = 0;
int length = TEST_DATA.length + 1;
boolean hasRead = ExtractorUtil.readFullyQuietly(input, target, offset, length);
assertThat(hasRead).isFalse();
assertThat(input.getPosition()).isEqualTo(0);
}
Aggregations