com.google.android.exoplayer2.extractor.TrackOutput Java Examples

The following examples show how to use com.google.android.exoplayer2.extractor.TrackOutput. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SeiReader.java    From Telegram-FOSS with GNU General Public License v2.0 6 votes vote down vote up
public void createTracks(ExtractorOutput extractorOutput, TrackIdGenerator idGenerator) {
  for (int i = 0; i < outputs.length; i++) {
    idGenerator.generateNewId();
    TrackOutput output = extractorOutput.track(idGenerator.getTrackId(), C.TRACK_TYPE_TEXT);
    Format channelFormat = closedCaptionFormats.get(i);
    String channelMimeType = channelFormat.sampleMimeType;
    Assertions.checkArgument(MimeTypes.APPLICATION_CEA608.equals(channelMimeType)
        || MimeTypes.APPLICATION_CEA708.equals(channelMimeType),
        "Invalid closed caption mime type provided: " + channelMimeType);
    String formatId = channelFormat.id != null ? channelFormat.id : idGenerator.getFormatId();
    output.format(
        Format.createTextSampleFormat(
            formatId,
            channelMimeType,
            /* codecs= */ null,
            /* bitrate= */ Format.NO_VALUE,
            channelFormat.selectionFlags,
            channelFormat.language,
            channelFormat.accessibilityChannel,
            /* drmInitData= */ null,
            Format.OFFSET_SAMPLE_RELATIVE,
            channelFormat.initializationData));
    outputs[i] = output;
  }
}
 
Example #2
Source File: HlsSampleStreamWrapper.java    From Telegram with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns the {@link TrackOutput} for the provided {@code type} and {@code id}, or null if none
 * has been created yet.
 *
 * <p>If a {@link SampleQueue} for {@code type} has been created and is mapped, but it has a
 * different ID, then return a {@link DummyTrackOutput} that does nothing.
 *
 * <p>If a {@link SampleQueue} for {@code type} has been created but is not mapped, then map it to
 * this {@code id} and return it. This situation can happen after a call to {@link #init} with
 * {@code reusingExtractor=false}.
 *
 * @param id The ID of the track.
 * @param type The type of the track, must be one of {@link #MAPPABLE_TYPES}.
 * @return The the mapped {@link TrackOutput}, or null if it's not been created yet.
 */
@Nullable
private TrackOutput getMappedTrackOutput(int id, int type) {
  Assertions.checkArgument(MAPPABLE_TYPES.contains(type));
  int sampleQueueIndex = sampleQueueIndicesByType.get(type, C.INDEX_UNSET);
  if (sampleQueueIndex == C.INDEX_UNSET) {
    return null;
  }

  if (sampleQueueMappingDoneByType.add(type)) {
    sampleQueueTrackIds[sampleQueueIndex] = id;
  }
  return sampleQueueTrackIds[sampleQueueIndex] == id
      ? sampleQueues[sampleQueueIndex]
      : createDummyTrackOutput(id, type);
}
 
Example #3
Source File: FragmentedMp4Extractor.java    From TelePlus-Android with GNU General Public License v2.0 6 votes vote down vote up
private void maybeInitExtraTracks() {
  if (emsgTrackOutputs == null) {
    emsgTrackOutputs = new TrackOutput[2];
    int emsgTrackOutputCount = 0;
    if (additionalEmsgTrackOutput != null) {
      emsgTrackOutputs[emsgTrackOutputCount++] = additionalEmsgTrackOutput;
    }
    if ((flags & FLAG_ENABLE_EMSG_TRACK) != 0) {
      emsgTrackOutputs[emsgTrackOutputCount++] =
          extractorOutput.track(trackBundles.size(), C.TRACK_TYPE_METADATA);
    }
    emsgTrackOutputs = Arrays.copyOf(emsgTrackOutputs, emsgTrackOutputCount);

    for (TrackOutput eventMessageTrackOutput : emsgTrackOutputs) {
      eventMessageTrackOutput.format(EMSG_FORMAT);
    }
  }
  if (cea608TrackOutputs == null) {
    cea608TrackOutputs = new TrackOutput[closedCaptionFormats.size()];
    for (int i = 0; i < cea608TrackOutputs.length; i++) {
      TrackOutput output = extractorOutput.track(trackBundles.size() + 1 + i, C.TRACK_TYPE_TEXT);
      output.format(closedCaptionFormats.get(i));
      cea608TrackOutputs[i] = output;
    }
  }
}
 
Example #4
Source File: TrackEncryptionBox.java    From Telegram with GNU General Public License v2.0 6 votes vote down vote up
/**
 * @param isEncrypted See {@link #isEncrypted}.
 * @param schemeType See {@link #schemeType}.
 * @param perSampleIvSize See {@link #perSampleIvSize}.
 * @param keyId See {@link TrackOutput.CryptoData#encryptionKey}.
 * @param defaultEncryptedBlocks See {@link TrackOutput.CryptoData#encryptedBlocks}.
 * @param defaultClearBlocks See {@link TrackOutput.CryptoData#clearBlocks}.
 * @param defaultInitializationVector See {@link #defaultInitializationVector}.
 */
public TrackEncryptionBox(
    boolean isEncrypted,
    @Nullable String schemeType,
    int perSampleIvSize,
    byte[] keyId,
    int defaultEncryptedBlocks,
    int defaultClearBlocks,
    @Nullable byte[] defaultInitializationVector) {
  Assertions.checkArgument(perSampleIvSize == 0 ^ defaultInitializationVector == null);
  this.isEncrypted = isEncrypted;
  this.schemeType = schemeType;
  this.perSampleIvSize = perSampleIvSize;
  this.defaultInitializationVector = defaultInitializationVector;
  cryptoData = new TrackOutput.CryptoData(schemeToCryptoMode(schemeType), keyId,
      defaultEncryptedBlocks, defaultClearBlocks);
}
 
Example #5
Source File: OggExtractor.java    From Telegram-FOSS with GNU General Public License v2.0 6 votes vote down vote up
@Override
public int read(ExtractorInput input, PositionHolder seekPosition)
    throws IOException, InterruptedException {
  if (streamReader == null) {
    if (!sniffInternal(input)) {
      throw new ParserException("Failed to determine bitstream type");
    }
    input.resetPeekPosition();
  }
  if (!streamReaderInitialized) {
    TrackOutput trackOutput = output.track(0, C.TRACK_TYPE_AUDIO);
    output.endTracks();
    streamReader.init(output, trackOutput);
    streamReaderInitialized = true;
  }
  return streamReader.read(input, seekPosition);
}
 
Example #6
Source File: DvbSubtitleReader.java    From MediaSDK with Apache License 2.0 6 votes vote down vote up
@Override
public void createTracks(ExtractorOutput extractorOutput, TrackIdGenerator idGenerator) {
  for (int i = 0; i < outputs.length; i++) {
    DvbSubtitleInfo subtitleInfo = subtitleInfos.get(i);
    idGenerator.generateNewId();
    TrackOutput output = extractorOutput.track(idGenerator.getTrackId(), C.TRACK_TYPE_TEXT);
    output.format(
        Format.createImageSampleFormat(
            idGenerator.getFormatId(),
            MimeTypes.APPLICATION_DVBSUBS,
            null,
            Format.NO_VALUE,
            0,
            Collections.singletonList(subtitleInfo.initializationData),
            subtitleInfo.language,
            null));
    outputs[i] = output;
  }
}
 
Example #7
Source File: DvbSubtitleReader.java    From MediaSDK with Apache License 2.0 6 votes vote down vote up
@Override
public void consume(ParsableByteArray data) {
  if (writingSample) {
    if (bytesToCheck == 2 && !checkNextByte(data, 0x20)) {
      // Failed to check data_identifier
      return;
    }
    if (bytesToCheck == 1 && !checkNextByte(data, 0x00)) {
      // Check and discard the subtitle_stream_id
      return;
    }
    int dataPosition = data.getPosition();
    int bytesAvailable = data.bytesLeft();
    for (TrackOutput output : outputs) {
      data.setPosition(dataPosition);
      output.sampleData(data, bytesAvailable);
    }
    sampleBytesWritten += bytesAvailable;
  }
}
 
Example #8
Source File: TrackEncryptionBox.java    From MediaSDK with Apache License 2.0 6 votes vote down vote up
/**
 * @param isEncrypted See {@link #isEncrypted}.
 * @param schemeType See {@link #schemeType}.
 * @param perSampleIvSize See {@link #perSampleIvSize}.
 * @param keyId See {@link TrackOutput.CryptoData#encryptionKey}.
 * @param defaultEncryptedBlocks See {@link TrackOutput.CryptoData#encryptedBlocks}.
 * @param defaultClearBlocks See {@link TrackOutput.CryptoData#clearBlocks}.
 * @param defaultInitializationVector See {@link #defaultInitializationVector}.
 */
public TrackEncryptionBox(
    boolean isEncrypted,
    @Nullable String schemeType,
    int perSampleIvSize,
    byte[] keyId,
    int defaultEncryptedBlocks,
    int defaultClearBlocks,
    @Nullable byte[] defaultInitializationVector) {
  Assertions.checkArgument(perSampleIvSize == 0 ^ defaultInitializationVector == null);
  this.isEncrypted = isEncrypted;
  this.schemeType = schemeType;
  this.perSampleIvSize = perSampleIvSize;
  this.defaultInitializationVector = defaultInitializationVector;
  cryptoData = new TrackOutput.CryptoData(schemeToCryptoMode(schemeType), keyId,
      defaultEncryptedBlocks, defaultClearBlocks);
}
 
Example #9
Source File: UserDataReader.java    From TelePlus-Android with GNU General Public License v2.0 6 votes vote down vote up
public void createTracks(
    ExtractorOutput extractorOutput, TsPayloadReader.TrackIdGenerator idGenerator) {
  for (int i = 0; i < outputs.length; i++) {
    idGenerator.generateNewId();
    TrackOutput output = extractorOutput.track(idGenerator.getTrackId(), C.TRACK_TYPE_TEXT);
    Format channelFormat = closedCaptionFormats.get(i);
    String channelMimeType = channelFormat.sampleMimeType;
    Assertions.checkArgument(
        MimeTypes.APPLICATION_CEA608.equals(channelMimeType)
            || MimeTypes.APPLICATION_CEA708.equals(channelMimeType),
        "Invalid closed caption mime type provided: " + channelMimeType);
    output.format(
        Format.createTextSampleFormat(
            idGenerator.getFormatId(),
            channelMimeType,
            /* codecs= */ null,
            /* bitrate= */ Format.NO_VALUE,
            channelFormat.selectionFlags,
            channelFormat.language,
            channelFormat.accessibilityChannel,
            /* drmInitData= */ null,
            Format.OFFSET_SAMPLE_RELATIVE,
            channelFormat.initializationData));
    outputs[i] = output;
  }
}
 
Example #10
Source File: FragmentedMp4Extractor.java    From MediaSDK with Apache License 2.0 6 votes vote down vote up
private void outputPendingMetadataSamples(long sampleTimeUs) {
  while (!pendingMetadataSampleInfos.isEmpty()) {
    MetadataSampleInfo sampleInfo = pendingMetadataSampleInfos.removeFirst();
    pendingMetadataSampleBytes -= sampleInfo.size;
    long metadataTimeUs = sampleTimeUs + sampleInfo.presentationTimeDeltaUs;
    if (timestampAdjuster != null) {
      metadataTimeUs = timestampAdjuster.adjustSampleTimestamp(metadataTimeUs);
    }
    for (TrackOutput emsgTrackOutput : emsgTrackOutputs) {
      emsgTrackOutput.sampleMetadata(
          metadataTimeUs,
          C.BUFFER_FLAG_KEY_FRAME,
          sampleInfo.size,
          pendingMetadataSampleBytes,
          null);
    }
  }
}
 
Example #11
Source File: DvbSubtitleReader.java    From TelePlus-Android with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void consume(ParsableByteArray data) {
  if (writingSample) {
    if (bytesToCheck == 2 && !checkNextByte(data, 0x20)) {
      // Failed to check data_identifier
      return;
    }
    if (bytesToCheck == 1 && !checkNextByte(data, 0x00)) {
      // Check and discard the subtitle_stream_id
      return;
    }
    int dataPosition = data.getPosition();
    int bytesAvailable = data.bytesLeft();
    for (TrackOutput output : outputs) {
      data.setPosition(dataPosition);
      output.sampleData(data, bytesAvailable);
    }
    sampleBytesWritten += bytesAvailable;
  }
}
 
Example #12
Source File: ExtractorMediaPeriod.java    From TelePlus-Android with GNU General Public License v2.0 6 votes vote down vote up
@Override
public TrackOutput track(int id, int type) {
  int trackCount = sampleQueues.length;
  for (int i = 0; i < trackCount; i++) {
    if (sampleQueueTrackIds[i] == id) {
      return sampleQueues[i];
    }
  }
  SampleQueue trackOutput = new SampleQueue(allocator);
  trackOutput.setUpstreamFormatChangeListener(this);
  sampleQueueTrackIds = Arrays.copyOf(sampleQueueTrackIds, trackCount + 1);
  sampleQueueTrackIds[trackCount] = id;
  sampleQueues = Arrays.copyOf(sampleQueues, trackCount + 1);
  sampleQueues[trackCount] = trackOutput;
  return trackOutput;
}
 
Example #13
Source File: DefaultDashChunkSource.java    From TelePlus-Android with GNU General Public License v2.0 6 votes vote down vote up
RepresentationHolder(
    long periodDurationUs,
    int trackType,
    Representation representation,
    boolean enableEventMessageTrack,
    boolean enableCea608Track,
    TrackOutput playerEmsgTrackOutput) {
  this(
      periodDurationUs,
      representation,
      createExtractorWrapper(
          trackType,
          representation,
          enableEventMessageTrack,
          enableCea608Track,
          playerEmsgTrackOutput),
      /* segmentNumShift= */ 0,
      representation.getIndex());
}
 
Example #14
Source File: UserDataReader.java    From TelePlus-Android with GNU General Public License v2.0 6 votes vote down vote up
public void createTracks(
    ExtractorOutput extractorOutput, TsPayloadReader.TrackIdGenerator idGenerator) {
  for (int i = 0; i < outputs.length; i++) {
    idGenerator.generateNewId();
    TrackOutput output = extractorOutput.track(idGenerator.getTrackId(), C.TRACK_TYPE_TEXT);
    Format channelFormat = closedCaptionFormats.get(i);
    String channelMimeType = channelFormat.sampleMimeType;
    Assertions.checkArgument(
        MimeTypes.APPLICATION_CEA608.equals(channelMimeType)
            || MimeTypes.APPLICATION_CEA708.equals(channelMimeType),
        "Invalid closed caption mime type provided: " + channelMimeType);
    output.format(
        Format.createTextSampleFormat(
            idGenerator.getFormatId(),
            channelMimeType,
            /* codecs= */ null,
            /* bitrate= */ Format.NO_VALUE,
            channelFormat.selectionFlags,
            channelFormat.language,
            channelFormat.accessibilityChannel,
            /* drmInitData= */ null,
            Format.OFFSET_SAMPLE_RELATIVE,
            channelFormat.initializationData));
    outputs[i] = output;
  }
}
 
Example #15
Source File: SeiReader.java    From TelePlus-Android with GNU General Public License v2.0 6 votes vote down vote up
public void createTracks(ExtractorOutput extractorOutput, TrackIdGenerator idGenerator) {
  for (int i = 0; i < outputs.length; i++) {
    idGenerator.generateNewId();
    TrackOutput output = extractorOutput.track(idGenerator.getTrackId(), C.TRACK_TYPE_TEXT);
    Format channelFormat = closedCaptionFormats.get(i);
    String channelMimeType = channelFormat.sampleMimeType;
    Assertions.checkArgument(MimeTypes.APPLICATION_CEA608.equals(channelMimeType)
        || MimeTypes.APPLICATION_CEA708.equals(channelMimeType),
        "Invalid closed caption mime type provided: " + channelMimeType);
    String formatId = channelFormat.id != null ? channelFormat.id : idGenerator.getFormatId();
    output.format(
        Format.createTextSampleFormat(
            formatId,
            channelMimeType,
            /* codecs= */ null,
            /* bitrate= */ Format.NO_VALUE,
            channelFormat.selectionFlags,
            channelFormat.language,
            channelFormat.accessibilityChannel,
            /* drmInitData= */ null,
            Format.OFFSET_SAMPLE_RELATIVE,
            channelFormat.initializationData));
    outputs[i] = output;
  }
}
 
Example #16
Source File: DvbSubtitleReader.java    From Telegram with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void createTracks(ExtractorOutput extractorOutput, TrackIdGenerator idGenerator) {
  for (int i = 0; i < outputs.length; i++) {
    DvbSubtitleInfo subtitleInfo = subtitleInfos.get(i);
    idGenerator.generateNewId();
    TrackOutput output = extractorOutput.track(idGenerator.getTrackId(), C.TRACK_TYPE_TEXT);
    output.format(
        Format.createImageSampleFormat(
            idGenerator.getFormatId(),
            MimeTypes.APPLICATION_DVBSUBS,
            null,
            Format.NO_VALUE,
            0,
            Collections.singletonList(subtitleInfo.initializationData),
            subtitleInfo.language,
            null));
    outputs[i] = output;
  }
}
 
Example #17
Source File: FragmentedMp4Extractor.java    From Telegram-FOSS with GNU General Public License v2.0 6 votes vote down vote up
private void outputPendingMetadataSamples(long sampleTimeUs) {
  while (!pendingMetadataSampleInfos.isEmpty()) {
    MetadataSampleInfo sampleInfo = pendingMetadataSampleInfos.removeFirst();
    pendingMetadataSampleBytes -= sampleInfo.size;
    long metadataTimeUs = sampleTimeUs + sampleInfo.presentationTimeDeltaUs;
    if (timestampAdjuster != null) {
      metadataTimeUs = timestampAdjuster.adjustSampleTimestamp(metadataTimeUs);
    }
    for (TrackOutput emsgTrackOutput : emsgTrackOutputs) {
      emsgTrackOutput.sampleMetadata(
          metadataTimeUs,
          C.BUFFER_FLAG_KEY_FRAME,
          sampleInfo.size,
          pendingMetadataSampleBytes,
          null);
    }
  }
}
 
Example #18
Source File: BaseMediaChunkOutput.java    From MediaSDK with Apache License 2.0 5 votes vote down vote up
@Override
public TrackOutput track(int id, int type) {
  for (int i = 0; i < trackTypes.length; i++) {
    if (type == trackTypes[i]) {
      return sampleQueues[i];
    }
  }
  Log.e(TAG, "Unmatched track of type: " + type);
  return new DummyTrackOutput();
}
 
Example #19
Source File: AdtsReader.java    From Telegram-FOSS with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Sets the state to STATE_READING_SAMPLE.
 *
 * @param outputToUse TrackOutput object to write the sample to
 * @param currentSampleDuration Duration of the sample to be read
 * @param priorReadBytes Size of prior read bytes
 * @param sampleSize Size of the sample
 */
private void setReadingSampleState(TrackOutput outputToUse, long currentSampleDuration,
    int priorReadBytes, int sampleSize) {
  state = STATE_READING_SAMPLE;
  bytesRead = priorReadBytes;
  this.currentOutput = outputToUse;
  this.currentSampleDuration = currentSampleDuration;
  this.sampleSize = sampleSize;
}
 
Example #20
Source File: SingleSampleMediaChunk.java    From K-Sonic with MIT License 5 votes vote down vote up
@SuppressWarnings("NonAtomicVolatileUpdate")
@Override
public void load() throws IOException, InterruptedException {
  DataSpec loadDataSpec = Util.getRemainderDataSpec(dataSpec, bytesLoaded);
  try {
    // Create and open the input.
    long length = dataSource.open(loadDataSpec);
    if (length != C.LENGTH_UNSET) {
      length += bytesLoaded;
    }
    ExtractorInput extractorInput = new DefaultExtractorInput(dataSource, bytesLoaded, length);
    BaseMediaChunkOutput output = getOutput();
    output.setSampleOffsetUs(0);
    TrackOutput trackOutput = output.track(0, trackType);
    trackOutput.format(sampleFormat);
    // Load the sample data.
    int result = 0;
    while (result != C.RESULT_END_OF_INPUT) {
      bytesLoaded += result;
      result = trackOutput.sampleData(extractorInput, Integer.MAX_VALUE, true);
    }
    int sampleSize = bytesLoaded;
    trackOutput.sampleMetadata(startTimeUs, C.BUFFER_FLAG_KEY_FRAME, sampleSize, 0, null);
  } finally {
    Util.closeQuietly(dataSource);
  }
  loadCompleted = true;
}
 
Example #21
Source File: FragmentedMp4Extractor.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
private void outputPendingMetadataSamples(long sampleTimeUs) {
  while (!pendingMetadataSampleInfos.isEmpty()) {
    MetadataSampleInfo sampleInfo = pendingMetadataSampleInfos.removeFirst();
    pendingMetadataSampleBytes -= sampleInfo.size;
    for (TrackOutput emsgTrackOutput : emsgTrackOutputs) {
      emsgTrackOutput.sampleMetadata(
          sampleTimeUs + sampleInfo.presentationTimeDeltaUs,
          C.BUFFER_FLAG_KEY_FRAME, sampleInfo.size, pendingMetadataSampleBytes, null);
    }
  }
}
 
Example #22
Source File: ProgressiveMediaPeriod.java    From MediaSDK with Apache License 2.0 5 votes vote down vote up
@Override
public void onIcyMetadata(ParsableByteArray metadata) {
  // Always output the first ICY metadata at the start time. This helps minimize any delay
  // between the start of playback and the first ICY metadata event.
  long timeUs =
      !seenIcyMetadata ? seekTimeUs : Math.max(getLargestQueuedTimestampUs(), seekTimeUs);
  int length = metadata.bytesLeft();
  TrackOutput icyTrackOutput = Assertions.checkNotNull(this.icyTrackOutput);
  icyTrackOutput.sampleData(metadata, length);
  icyTrackOutput.sampleMetadata(
      timeUs, C.BUFFER_FLAG_KEY_FRAME, length, /* offset= */ 0, /* encryptionData= */ null);
  seenIcyMetadata = true;
}
 
Example #23
Source File: FragmentedMp4Extractor.java    From K-Sonic with MIT License 5 votes vote down vote up
/**
 * Appends the corresponding encryption data to the {@link TrackOutput} contained in the given
 * {@link TrackBundle}.
 *
 * @param trackBundle The {@link TrackBundle} that contains the {@link Track} for which the
 *     Sample encryption data must be output.
 * @return The number of written bytes.
 */
private int appendSampleEncryptionData(TrackBundle trackBundle) {
  TrackFragment trackFragment = trackBundle.fragment;
  ParsableByteArray sampleEncryptionData = trackFragment.sampleEncryptionData;
  int sampleDescriptionIndex = trackFragment.header.sampleDescriptionIndex;
  TrackEncryptionBox encryptionBox = trackFragment.trackEncryptionBox != null
      ? trackFragment.trackEncryptionBox
      : trackBundle.track.sampleDescriptionEncryptionBoxes[sampleDescriptionIndex];
  int vectorSize = encryptionBox.initializationVectorSize;
  boolean subsampleEncryption = trackFragment
      .sampleHasSubsampleEncryptionTable[trackBundle.currentSampleIndex];

  // Write the signal byte, containing the vector size and the subsample encryption flag.
  encryptionSignalByte.data[0] = (byte) (vectorSize | (subsampleEncryption ? 0x80 : 0));
  encryptionSignalByte.setPosition(0);
  TrackOutput output = trackBundle.output;
  output.sampleData(encryptionSignalByte, 1);
  // Write the vector.
  output.sampleData(sampleEncryptionData, vectorSize);
  // If we don't have subsample encryption data, we're done.
  if (!subsampleEncryption) {
    return 1 + vectorSize;
  }
  // Write the subsample encryption data.
  int subsampleCount = sampleEncryptionData.readUnsignedShort();
  sampleEncryptionData.skipBytes(-2);
  int subsampleDataLength = 2 + 6 * subsampleCount;
  output.sampleData(sampleEncryptionData, subsampleDataLength);
  return 1 + vectorSize + subsampleDataLength;
}
 
Example #24
Source File: H264Reader.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
public SampleReader(TrackOutput output, boolean allowNonIdrKeyframes,
    boolean detectAccessUnits) {
  this.output = output;
  this.allowNonIdrKeyframes = allowNonIdrKeyframes;
  this.detectAccessUnits = detectAccessUnits;
  sps = new SparseArray<>();
  pps = new SparseArray<>();
  previousSliceHeader = new SliceHeaderData();
  sliceHeader = new SliceHeaderData();
  buffer = new byte[DEFAULT_BUFFER_SIZE];
  bitArray = new ParsableNalUnitBitArray(buffer, 0, 0);
  reset();
}
 
Example #25
Source File: CeaUtil.java    From Telegram with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Consumes caption data (cc_data), writing the content as samples to all of the provided outputs.
 *
 * @param presentationTimeUs The presentation time in microseconds for any samples.
 * @param ccDataBuffer The buffer containing the caption data.
 * @param outputs The outputs to which any samples should be written.
 */
public static void consumeCcData(
    long presentationTimeUs, ParsableByteArray ccDataBuffer, TrackOutput[] outputs) {
  // First byte contains: reserved (1), process_cc_data_flag (1), zero_bit (1), cc_count (5).
  int firstByte = ccDataBuffer.readUnsignedByte();
  boolean processCcDataFlag = (firstByte & 0x40) != 0;
  if (!processCcDataFlag) {
    // No need to process.
    return;
  }
  int ccCount = firstByte & 0x1F;
  ccDataBuffer.skipBytes(1); // Ignore em_data
  // Each data packet consists of 24 bits: marker bits (5) + cc_valid (1) + cc_type (2)
  // + cc_data_1 (8) + cc_data_2 (8).
  int sampleLength = ccCount * 3;
  int sampleStartPosition = ccDataBuffer.getPosition();
  for (TrackOutput output : outputs) {
    ccDataBuffer.setPosition(sampleStartPosition);
    output.sampleData(ccDataBuffer, sampleLength);
    output.sampleMetadata(
        presentationTimeUs,
        C.BUFFER_FLAG_KEY_FRAME,
        sampleLength,
        /* offset= */ 0,
        /* encryptionData= */ null);
  }
}
 
Example #26
Source File: CeaUtil.java    From K-Sonic with MIT License 5 votes vote down vote up
/**
 * Consumes the unescaped content of an SEI NAL unit, writing the content of any CEA-608 messages
 * as samples to all of the provided outputs.
 *
 * @param presentationTimeUs The presentation time in microseconds for any samples.
 * @param seiBuffer The unescaped SEI NAL unit data, excluding the NAL unit start code and type.
 * @param outputs The outputs to which any samples should be written.
 */
public static void consume(long presentationTimeUs, ParsableByteArray seiBuffer,
    TrackOutput[] outputs) {
  while (seiBuffer.bytesLeft() > 1 /* last byte will be rbsp_trailing_bits */) {
    int payloadType = readNon255TerminatedValue(seiBuffer);
    int payloadSize = readNon255TerminatedValue(seiBuffer);
    // Process the payload.
    if (payloadSize == -1 || payloadSize > seiBuffer.bytesLeft()) {
      // This might occur if we're trying to read an encrypted SEI NAL unit.
      Log.w(TAG, "Skipping remainder of malformed SEI NAL unit.");
      seiBuffer.setPosition(seiBuffer.limit());
    } else if (isSeiMessageCea608(payloadType, payloadSize, seiBuffer)) {
      // Ignore country_code (1) + provider_code (2) + user_identifier (4)
      // + user_data_type_code (1).
      seiBuffer.skipBytes(8);
      // Ignore first three bits: reserved (1) + process_cc_data_flag (1) + zero_bit (1).
      int ccCount = seiBuffer.readUnsignedByte() & 0x1F;
      // Ignore em_data (1)
      seiBuffer.skipBytes(1);
      // Each data packet consists of 24 bits: marker bits (5) + cc_valid (1) + cc_type (2)
      // + cc_data_1 (8) + cc_data_2 (8).
      int sampleLength = ccCount * 3;
      int sampleStartPosition = seiBuffer.getPosition();
      for (TrackOutput output : outputs) {
        seiBuffer.setPosition(sampleStartPosition);
        output.sampleData(seiBuffer, sampleLength);
        output.sampleMetadata(presentationTimeUs, C.BUFFER_FLAG_KEY_FRAME, sampleLength, 0, null);
      }
      // Ignore trailing information in SEI, if any.
      seiBuffer.skipBytes(payloadSize - (10 + ccCount * 3));
    } else {
      seiBuffer.skipBytes(payloadSize);
    }
  }
}
 
Example #27
Source File: SingleSampleMediaChunk.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("NonAtomicVolatileUpdate")
@Override
public void load() throws IOException, InterruptedException {
  DataSpec loadDataSpec = dataSpec.subrange(nextLoadPosition);
  try {
    // Create and open the input.
    long length = dataSource.open(loadDataSpec);
    if (length != C.LENGTH_UNSET) {
      length += nextLoadPosition;
    }
    ExtractorInput extractorInput =
        new DefaultExtractorInput(dataSource, nextLoadPosition, length);
    BaseMediaChunkOutput output = getOutput();
    output.setSampleOffsetUs(0);
    TrackOutput trackOutput = output.track(0, trackType);
    trackOutput.format(sampleFormat);
    // Load the sample data.
    int result = 0;
    while (result != C.RESULT_END_OF_INPUT) {
      nextLoadPosition += result;
      result = trackOutput.sampleData(extractorInput, Integer.MAX_VALUE, true);
    }
    int sampleSize = (int) nextLoadPosition;
    trackOutput.sampleMetadata(startTimeUs, C.BUFFER_FLAG_KEY_FRAME, sampleSize, 0, null);
  } finally {
    Util.closeQuietly(dataSource);
  }
  loadCompleted = true;
}
 
Example #28
Source File: FlacExtractor.java    From Telegram-FOSS with GNU General Public License v2.0 5 votes vote down vote up
@RequiresNonNull("binarySearchSeeker")
private int handlePendingSeek(
    ExtractorInput input,
    PositionHolder seekPosition,
    ParsableByteArray outputBuffer,
    OutputFrameHolder outputFrameHolder,
    TrackOutput trackOutput)
    throws InterruptedException, IOException {
  int seekResult = binarySearchSeeker.handlePendingSeek(input, seekPosition, outputFrameHolder);
  ByteBuffer outputByteBuffer = outputFrameHolder.byteBuffer;
  if (seekResult == RESULT_CONTINUE && outputByteBuffer.limit() > 0) {
    outputSample(outputBuffer, outputByteBuffer.limit(), outputFrameHolder.timeUs, trackOutput);
  }
  return seekResult;
}
 
Example #29
Source File: DvbSubtitleReader.java    From Telegram-FOSS with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void packetFinished() {
  if (writingSample) {
    for (TrackOutput output : outputs) {
      output.sampleMetadata(sampleTimeUs, C.BUFFER_FLAG_KEY_FRAME, sampleBytesWritten, 0, null);
    }
    writingSample = false;
  }
}
 
Example #30
Source File: ChunkExtractorWrapper.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
@Override
public TrackOutput track(int id, int type) {
  BindingTrackOutput bindingTrackOutput = bindingTrackOutputs.get(id);
  if (bindingTrackOutput == null) {
    // Assert that if we're seeing a new track we have not seen endTracks.
    Assertions.checkState(sampleFormats == null);
    // TODO: Manifest formats for embedded tracks should also be passed here.
    bindingTrackOutput = new BindingTrackOutput(id, type,
        type == primaryTrackType ? primaryTrackManifestFormat : null);
    bindingTrackOutput.bind(trackOutputProvider);
    bindingTrackOutputs.put(id, bindingTrackOutput);
  }
  return bindingTrackOutput;
}