com.google.android.exoplayer2.decoder.DecoderInputBuffer Java Examples

The following examples show how to use com.google.android.exoplayer2.decoder.DecoderInputBuffer. 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: SimpleDecoderAudioRenderer.java    From Telegram-FOSS with GNU General Public License v2.0 6 votes vote down vote up
/**
 * @param eventHandler A handler to use when delivering events to {@code eventListener}. May be
 *     null if delivery of events is not required.
 * @param eventListener A listener of events. May be null if delivery of events is not required.
 * @param drmSessionManager For use with encrypted media. May be null if support for encrypted
 *     media is not required.
 * @param playClearSamplesWithoutKeys Encrypted media may contain clear (un-encrypted) regions.
 *     For example a media file may start with a short clear region so as to allow playback to
 *     begin in parallel with key acquisition. This parameter specifies whether the renderer is
 *     permitted to play clear regions of encrypted media files before {@code drmSessionManager}
 *     has obtained the keys necessary to decrypt encrypted regions of the media.
 * @param audioSink The sink to which audio will be output.
 */
public SimpleDecoderAudioRenderer(
    @Nullable Handler eventHandler,
    @Nullable AudioRendererEventListener eventListener,
    @Nullable DrmSessionManager<ExoMediaCrypto> drmSessionManager,
    boolean playClearSamplesWithoutKeys,
    AudioSink audioSink) {
  super(C.TRACK_TYPE_AUDIO);
  this.drmSessionManager = drmSessionManager;
  this.playClearSamplesWithoutKeys = playClearSamplesWithoutKeys;
  eventDispatcher = new EventDispatcher(eventHandler, eventListener);
  this.audioSink = audioSink;
  audioSink.setListener(new AudioSinkListener());
  formatHolder = new FormatHolder();
  flagsOnlyBuffer = DecoderInputBuffer.newFlagsOnlyInstance();
  decoderReinitializationState = REINITIALIZATION_STATE_NONE;
  audioTrackNeedsConfigure = true;
}
 
Example #2
Source File: BaseRenderer.java    From Telegram-FOSS with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Reads from the enabled upstream source. If the upstream source has been read to the end then
 * {@link C#RESULT_BUFFER_READ} is only returned if {@link #setCurrentStreamFinal()} has been
 * called. {@link C#RESULT_NOTHING_READ} is returned otherwise.
 *
 * @param formatHolder A {@link FormatHolder} to populate in the case of reading a format.
 * @param buffer A {@link DecoderInputBuffer} to populate in the case of reading a sample or the
 *     end of the stream. If the end of the stream has been reached, the
 *     {@link C#BUFFER_FLAG_END_OF_STREAM} flag will be set on the buffer.
 * @param formatRequired Whether the caller requires that the format of the stream be read even if
 *     it's not changing. A sample will never be read if set to true, however it is still possible
 *     for the end of stream or nothing to be read.
 * @return The result, which can be {@link C#RESULT_NOTHING_READ}, {@link C#RESULT_FORMAT_READ} or
 *     {@link C#RESULT_BUFFER_READ}.
 */
protected final int readSource(FormatHolder formatHolder, DecoderInputBuffer buffer,
    boolean formatRequired) {
  int result = stream.readData(formatHolder, buffer, formatRequired);
  if (result == C.RESULT_BUFFER_READ) {
    if (buffer.isEndOfStream()) {
      readingPositionUs = C.TIME_END_OF_SOURCE;
      return streamIsFinal ? C.RESULT_BUFFER_READ : C.RESULT_NOTHING_READ;
    }
    buffer.timeUs += streamOffsetUs;
    readingPositionUs = Math.max(readingPositionUs, buffer.timeUs);
  } else if (result == C.RESULT_FORMAT_READ) {
    Format format = formatHolder.format;
    if (format.subsampleOffsetUs != Format.OFFSET_SAMPLE_RELATIVE) {
      format = format.copyWithSubsampleOffsetUs(format.subsampleOffsetUs + streamOffsetUs);
      formatHolder.format = format;
    }
  }
  return result;
}
 
Example #3
Source File: HlsSampleStreamWrapper.java    From K-Sonic with MIT License 6 votes vote down vote up
int readData(int group, FormatHolder formatHolder, DecoderInputBuffer buffer,
    boolean requireFormat) {
  if (isPendingReset()) {
    return C.RESULT_NOTHING_READ;
  }

  while (mediaChunks.size() > 1 && finishedReadingChunk(mediaChunks.getFirst())) {
    mediaChunks.removeFirst();
  }
  HlsMediaChunk currentChunk = mediaChunks.getFirst();
  Format trackFormat = currentChunk.trackFormat;
  if (!trackFormat.equals(downstreamTrackFormat)) {
    eventDispatcher.downstreamFormatChanged(trackType, trackFormat,
        currentChunk.trackSelectionReason, currentChunk.trackSelectionData,
        currentChunk.startTimeUs);
  }
  downstreamTrackFormat = trackFormat;

  return sampleQueues.valueAt(group).readData(formatHolder, buffer, requireFormat,
      loadingFinished, lastSeekPositionUs);
}
 
Example #4
Source File: SimpleDecoderAudioRenderer.java    From TelePlus-Android with GNU General Public License v2.0 6 votes vote down vote up
/**
 * @param eventHandler A handler to use when delivering events to {@code eventListener}. May be
 *     null if delivery of events is not required.
 * @param eventListener A listener of events. May be null if delivery of events is not required.
 * @param drmSessionManager For use with encrypted media. May be null if support for encrypted
 *     media is not required.
 * @param playClearSamplesWithoutKeys Encrypted media may contain clear (un-encrypted) regions.
 *     For example a media file may start with a short clear region so as to allow playback to
 *     begin in parallel with key acquisition. This parameter specifies whether the renderer is
 *     permitted to play clear regions of encrypted media files before {@code drmSessionManager}
 *     has obtained the keys necessary to decrypt encrypted regions of the media.
 * @param audioSink The sink to which audio will be output.
 */
public SimpleDecoderAudioRenderer(
    @Nullable Handler eventHandler,
    @Nullable AudioRendererEventListener eventListener,
    @Nullable DrmSessionManager<ExoMediaCrypto> drmSessionManager,
    boolean playClearSamplesWithoutKeys,
    AudioSink audioSink) {
  super(C.TRACK_TYPE_AUDIO);
  this.drmSessionManager = drmSessionManager;
  this.playClearSamplesWithoutKeys = playClearSamplesWithoutKeys;
  eventDispatcher = new EventDispatcher(eventHandler, eventListener);
  this.audioSink = audioSink;
  audioSink.setListener(new AudioSinkListener());
  formatHolder = new FormatHolder();
  flagsOnlyBuffer = DecoderInputBuffer.newFlagsOnlyInstance();
  decoderReinitializationState = REINITIALIZATION_STATE_NONE;
  audioTrackNeedsConfigure = true;
}
 
Example #5
Source File: MediaCodecRenderer.java    From MediaSDK with Apache License 2.0 6 votes vote down vote up
/**
 * @param trackType The track type that the renderer handles. One of the {@code C.TRACK_TYPE_*}
 *     constants defined in {@link C}.
 * @param mediaCodecSelector A decoder selector.
 * @param drmSessionManager For use with encrypted media. May be null if support for encrypted
 *     media is not required.
 * @param playClearSamplesWithoutKeys Encrypted media may contain clear (un-encrypted) regions.
 *     For example a media file may start with a short clear region so as to allow playback to
 *     begin in parallel with key acquisition. This parameter specifies whether the renderer is
 *     permitted to play clear regions of encrypted media files before {@code drmSessionManager}
 *     has obtained the keys necessary to decrypt encrypted regions of the media.
 * @param enableDecoderFallback Whether to enable fallback to lower-priority decoders if decoder
 *     initialization fails. This may result in using a decoder that is less efficient or slower
 *     than the primary decoder.
 * @param assumedMinimumCodecOperatingRate A codec operating rate that all codecs instantiated by
 *     this renderer are assumed to meet implicitly (i.e. without the operating rate being set
 *     explicitly using {@link MediaFormat#KEY_OPERATING_RATE}).
 */
public MediaCodecRenderer(
    int trackType,
    MediaCodecSelector mediaCodecSelector,
    @Nullable DrmSessionManager<FrameworkMediaCrypto> drmSessionManager,
    boolean playClearSamplesWithoutKeys,
    boolean enableDecoderFallback,
    float assumedMinimumCodecOperatingRate) {
  super(trackType);
  this.mediaCodecSelector = Assertions.checkNotNull(mediaCodecSelector);
  this.drmSessionManager = drmSessionManager;
  this.playClearSamplesWithoutKeys = playClearSamplesWithoutKeys;
  this.enableDecoderFallback = enableDecoderFallback;
  this.assumedMinimumCodecOperatingRate = assumedMinimumCodecOperatingRate;
  buffer = new DecoderInputBuffer(DecoderInputBuffer.BUFFER_REPLACEMENT_MODE_DISABLED);
  flagsOnlyBuffer = DecoderInputBuffer.newFlagsOnlyInstance();
  formatQueue = new TimedValueQueue<>();
  decodeOnlyPresentationTimestamps = new ArrayList<>();
  outputBufferInfo = new MediaCodec.BufferInfo();
  codecReconfigurationState = RECONFIGURATION_STATE_NONE;
  codecDrainState = DRAIN_STATE_NONE;
  codecDrainAction = DRAIN_ACTION_NONE;
  codecOperatingRate = CODEC_OPERATING_RATE_UNSET;
  rendererOperatingRate = 1f;
  renderTimeLimitMs = C.TIME_UNSET;
}
 
Example #6
Source File: ProgressiveMediaPeriod.java    From MediaSDK with Apache License 2.0 6 votes vote down vote up
int readData(
    int sampleQueueIndex,
    FormatHolder formatHolder,
    DecoderInputBuffer buffer,
    boolean formatRequired) {
  if (suppressRead()) {
    return C.RESULT_NOTHING_READ;
  }
  maybeNotifyDownstreamFormat(sampleQueueIndex);
  int result =
      sampleQueues[sampleQueueIndex].read(
          formatHolder, buffer, formatRequired, loadingFinished, lastSeekPositionUs);
  if (result == C.RESULT_NOTHING_READ) {
    maybeStartDeferredRetry(sampleQueueIndex);
  }
  return result;
}
 
Example #7
Source File: AudioDecoder.java    From DanDanPlayForAndroid with MIT License 6 votes vote down vote up
public AudioDecoder(
    int numInputBuffers,
    int numOutputBuffers,
    int initialInputBufferSize,
    Format format,
    boolean outputFloat)
    throws AudioSoftDecoderException {
  super(new DecoderInputBuffer[numInputBuffers], new SimpleOutputBuffer[numOutputBuffers]);
  if (!DecoderSoLibrary.isAvailable()) {
    throw new AudioSoftDecoderException("Failed to load decoder native libraries.");
  }
  Assertions.checkNotNull(format.sampleMimeType);
  codecName = Assertions.checkNotNull(getCodecName(format.sampleMimeType, format.pcmEncoding));
  extraData = getExtraData(format.sampleMimeType, format.initializationData);
  encoding = outputFloat ? C.ENCODING_PCM_FLOAT : C.ENCODING_PCM_16BIT;
  outputBufferSize = outputFloat ? OUTPUT_BUFFER_SIZE_32BIT : OUTPUT_BUFFER_SIZE_16BIT;
  nativeContext =
      ffmpegInitialize(codecName, extraData, outputFloat, format.sampleRate, format.channelCount);
  if (nativeContext == 0) {
    throw new AudioSoftDecoderException("Initialization failed.");
  }
  setInitialInputBufferSize(initialInputBufferSize);
}
 
Example #8
Source File: SilenceMediaSource.java    From Telegram-FOSS with GNU General Public License v2.0 6 votes vote down vote up
@Override
public int readData(
    FormatHolder formatHolder, DecoderInputBuffer buffer, boolean formatRequired) {
  if (!sentFormat || formatRequired) {
    formatHolder.format = FORMAT;
    sentFormat = true;
    return C.RESULT_FORMAT_READ;
  }

  long bytesRemaining = durationBytes - positionBytes;
  if (bytesRemaining == 0) {
    buffer.addFlag(C.BUFFER_FLAG_END_OF_STREAM);
    return C.RESULT_BUFFER_READ;
  }

  int bytesToWrite = (int) Math.min(SILENCE_SAMPLE.length, bytesRemaining);
  buffer.ensureSpaceForWrite(bytesToWrite);
  buffer.addFlag(C.BUFFER_FLAG_KEY_FRAME);
  buffer.data.put(SILENCE_SAMPLE, /* offset= */ 0, bytesToWrite);
  buffer.timeUs = getAudioPositionUs(positionBytes);
  positionBytes += bytesToWrite;
  return C.RESULT_BUFFER_READ;
}
 
Example #9
Source File: SimpleDecoderAudioRenderer.java    From Telegram with GNU General Public License v2.0 6 votes vote down vote up
/**
 * @param eventHandler A handler to use when delivering events to {@code eventListener}. May be
 *     null if delivery of events is not required.
 * @param eventListener A listener of events. May be null if delivery of events is not required.
 * @param drmSessionManager For use with encrypted media. May be null if support for encrypted
 *     media is not required.
 * @param playClearSamplesWithoutKeys Encrypted media may contain clear (un-encrypted) regions.
 *     For example a media file may start with a short clear region so as to allow playback to
 *     begin in parallel with key acquisition. This parameter specifies whether the renderer is
 *     permitted to play clear regions of encrypted media files before {@code drmSessionManager}
 *     has obtained the keys necessary to decrypt encrypted regions of the media.
 * @param audioSink The sink to which audio will be output.
 */
public SimpleDecoderAudioRenderer(
    @Nullable Handler eventHandler,
    @Nullable AudioRendererEventListener eventListener,
    @Nullable DrmSessionManager<ExoMediaCrypto> drmSessionManager,
    boolean playClearSamplesWithoutKeys,
    AudioSink audioSink) {
  super(C.TRACK_TYPE_AUDIO);
  this.drmSessionManager = drmSessionManager;
  this.playClearSamplesWithoutKeys = playClearSamplesWithoutKeys;
  eventDispatcher = new EventDispatcher(eventHandler, eventListener);
  this.audioSink = audioSink;
  audioSink.setListener(new AudioSinkListener());
  formatHolder = new FormatHolder();
  flagsOnlyBuffer = DecoderInputBuffer.newFlagsOnlyInstance();
  decoderReinitializationState = REINITIALIZATION_STATE_NONE;
  audioTrackNeedsConfigure = true;
}
 
Example #10
Source File: SilenceMediaSource.java    From Telegram with GNU General Public License v2.0 6 votes vote down vote up
@Override
public int readData(
    FormatHolder formatHolder, DecoderInputBuffer buffer, boolean formatRequired) {
  if (!sentFormat || formatRequired) {
    formatHolder.format = FORMAT;
    sentFormat = true;
    return C.RESULT_FORMAT_READ;
  }

  long bytesRemaining = durationBytes - positionBytes;
  if (bytesRemaining == 0) {
    buffer.addFlag(C.BUFFER_FLAG_END_OF_STREAM);
    return C.RESULT_BUFFER_READ;
  }

  int bytesToWrite = (int) Math.min(SILENCE_SAMPLE.length, bytesRemaining);
  buffer.ensureSpaceForWrite(bytesToWrite);
  buffer.addFlag(C.BUFFER_FLAG_KEY_FRAME);
  buffer.data.put(SILENCE_SAMPLE, /* offset= */ 0, bytesToWrite);
  buffer.timeUs = getAudioPositionUs(positionBytes);
  positionBytes += bytesToWrite;
  return C.RESULT_BUFFER_READ;
}
 
Example #11
Source File: FfmpegDecoder.java    From Telegram-FOSS with GNU General Public License v2.0 6 votes vote down vote up
public FfmpegDecoder(
    int numInputBuffers,
    int numOutputBuffers,
    int initialInputBufferSize,
    Format format,
    boolean outputFloat)
    throws FfmpegDecoderException {
  super(new DecoderInputBuffer[numInputBuffers], new SimpleOutputBuffer[numOutputBuffers]);
  Assertions.checkNotNull(format.sampleMimeType);
  codecName =
      Assertions.checkNotNull(
          FfmpegLibrary.getCodecName(format.sampleMimeType, format.pcmEncoding));
  extraData = getExtraData(format.sampleMimeType, format.initializationData);
  encoding = outputFloat ? C.ENCODING_PCM_FLOAT : C.ENCODING_PCM_16BIT;
  outputBufferSize = outputFloat ? OUTPUT_BUFFER_SIZE_32BIT : OUTPUT_BUFFER_SIZE_16BIT;
  nativeContext =
      ffmpegInitialize(codecName, extraData, outputFloat, format.sampleRate, format.channelCount);
  if (nativeContext == 0) {
    throw new FfmpegDecoderException("Initialization failed.");
  }
  setInitialInputBufferSize(initialInputBufferSize);
}
 
Example #12
Source File: SilenceMediaSource.java    From MediaSDK with Apache License 2.0 6 votes vote down vote up
@Override
public int readData(
    FormatHolder formatHolder, DecoderInputBuffer buffer, boolean formatRequired) {
  if (!sentFormat || formatRequired) {
    formatHolder.format = FORMAT;
    sentFormat = true;
    return C.RESULT_FORMAT_READ;
  }

  long bytesRemaining = durationBytes - positionBytes;
  if (bytesRemaining == 0) {
    buffer.addFlag(C.BUFFER_FLAG_END_OF_STREAM);
    return C.RESULT_BUFFER_READ;
  }

  int bytesToWrite = (int) Math.min(SILENCE_SAMPLE.length, bytesRemaining);
  buffer.ensureSpaceForWrite(bytesToWrite);
  buffer.data.put(SILENCE_SAMPLE, /* offset= */ 0, bytesToWrite);
  buffer.timeUs = getAudioPositionUs(positionBytes);
  buffer.addFlag(C.BUFFER_FLAG_KEY_FRAME);
  positionBytes += bytesToWrite;
  return C.RESULT_BUFFER_READ;
}
 
Example #13
Source File: MediaCodecRenderer.java    From TelePlus-Android with GNU General Public License v2.0 6 votes vote down vote up
/**
 * @param trackType The track type that the renderer handles. One of the {@code C.TRACK_TYPE_*}
 *     constants defined in {@link C}.
 * @param mediaCodecSelector A decoder selector.
 * @param drmSessionManager For use with encrypted media. May be null if support for encrypted
 *     media is not required.
 * @param playClearSamplesWithoutKeys Encrypted media may contain clear (un-encrypted) regions.
 *     For example a media file may start with a short clear region so as to allow playback to
 *     begin in parallel with key acquisition. This parameter specifies whether the renderer is
 *     permitted to play clear regions of encrypted media files before {@code drmSessionManager}
 *     has obtained the keys necessary to decrypt encrypted regions of the media.
 * @param assumedMinimumCodecOperatingRate A codec operating rate that all codecs instantiated by
 *     this renderer are assumed to meet implicitly (i.e. without the operating rate being set
 *     explicitly using {@link MediaFormat#KEY_OPERATING_RATE}).
 */
public MediaCodecRenderer(
    int trackType,
    MediaCodecSelector mediaCodecSelector,
    @Nullable DrmSessionManager<FrameworkMediaCrypto> drmSessionManager,
    boolean playClearSamplesWithoutKeys,
    float assumedMinimumCodecOperatingRate) {
  super(trackType);
  Assertions.checkState(Util.SDK_INT >= 16);
  this.mediaCodecSelector = Assertions.checkNotNull(mediaCodecSelector);
  this.drmSessionManager = drmSessionManager;
  this.playClearSamplesWithoutKeys = playClearSamplesWithoutKeys;
  this.assumedMinimumCodecOperatingRate = assumedMinimumCodecOperatingRate;
  buffer = new DecoderInputBuffer(DecoderInputBuffer.BUFFER_REPLACEMENT_MODE_DISABLED);
  flagsOnlyBuffer = DecoderInputBuffer.newFlagsOnlyInstance();
  formatHolder = new FormatHolder();
  decodeOnlyPresentationTimestamps = new ArrayList<>();
  outputBufferInfo = new MediaCodec.BufferInfo();
  codecReconfigurationState = RECONFIGURATION_STATE_NONE;
  codecReinitializationState = REINITIALIZATION_STATE_NONE;
  codecOperatingRate = CODEC_OPERATING_RATE_UNSET;
  rendererOperatingRate = 1f;
}
 
Example #14
Source File: BaseRenderer.java    From TelePlus-Android with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Reads from the enabled upstream source. If the upstream source has been read to the end then
 * {@link C#RESULT_BUFFER_READ} is only returned if {@link #setCurrentStreamFinal()} has been
 * called. {@link C#RESULT_NOTHING_READ} is returned otherwise.
 *
 * @param formatHolder A {@link FormatHolder} to populate in the case of reading a format.
 * @param buffer A {@link DecoderInputBuffer} to populate in the case of reading a sample or the
 *     end of the stream. If the end of the stream has been reached, the
 *     {@link C#BUFFER_FLAG_END_OF_STREAM} flag will be set on the buffer.
 * @param formatRequired Whether the caller requires that the format of the stream be read even if
 *     it's not changing. A sample will never be read if set to true, however it is still possible
 *     for the end of stream or nothing to be read.
 * @return The result, which can be {@link C#RESULT_NOTHING_READ}, {@link C#RESULT_FORMAT_READ} or
 *     {@link C#RESULT_BUFFER_READ}.
 */
protected final int readSource(FormatHolder formatHolder, DecoderInputBuffer buffer,
    boolean formatRequired) {
  int result = stream.readData(formatHolder, buffer, formatRequired);
  if (result == C.RESULT_BUFFER_READ) {
    if (buffer.isEndOfStream()) {
      readEndOfStream = true;
      return streamIsFinal ? C.RESULT_BUFFER_READ : C.RESULT_NOTHING_READ;
    }
    buffer.timeUs += streamOffsetUs;
  } else if (result == C.RESULT_FORMAT_READ) {
    Format format = formatHolder.format;
    if (format.subsampleOffsetUs != Format.OFFSET_SAMPLE_RELATIVE) {
      format = format.copyWithSubsampleOffsetUs(format.subsampleOffsetUs + streamOffsetUs);
      formatHolder.format = format;
    }
  }
  return result;
}
 
Example #15
Source File: SimpleDecoderAudioRenderer.java    From TelePlus-Android with GNU General Public License v2.0 6 votes vote down vote up
/**
 * @param eventHandler A handler to use when delivering events to {@code eventListener}. May be
 *     null if delivery of events is not required.
 * @param eventListener A listener of events. May be null if delivery of events is not required.
 * @param drmSessionManager For use with encrypted media. May be null if support for encrypted
 *     media is not required.
 * @param playClearSamplesWithoutKeys Encrypted media may contain clear (un-encrypted) regions.
 *     For example a media file may start with a short clear region so as to allow playback to
 *     begin in parallel with key acquisition. This parameter specifies whether the renderer is
 *     permitted to play clear regions of encrypted media files before {@code drmSessionManager}
 *     has obtained the keys necessary to decrypt encrypted regions of the media.
 * @param audioSink The sink to which audio will be output.
 */
public SimpleDecoderAudioRenderer(
    @Nullable Handler eventHandler,
    @Nullable AudioRendererEventListener eventListener,
    @Nullable DrmSessionManager<ExoMediaCrypto> drmSessionManager,
    boolean playClearSamplesWithoutKeys,
    AudioSink audioSink) {
  super(C.TRACK_TYPE_AUDIO);
  this.drmSessionManager = drmSessionManager;
  this.playClearSamplesWithoutKeys = playClearSamplesWithoutKeys;
  eventDispatcher = new EventDispatcher(eventHandler, eventListener);
  this.audioSink = audioSink;
  audioSink.setListener(new AudioSinkListener());
  formatHolder = new FormatHolder();
  flagsOnlyBuffer = DecoderInputBuffer.newFlagsOnlyInstance();
  decoderReinitializationState = REINITIALIZATION_STATE_NONE;
  audioTrackNeedsConfigure = true;
}
 
Example #16
Source File: BaseRenderer.java    From MediaSDK with Apache License 2.0 6 votes vote down vote up
/**
 * Reads from the enabled upstream source. If the upstream source has been read to the end then
 * {@link C#RESULT_BUFFER_READ} is only returned if {@link #setCurrentStreamFinal()} has been
 * called. {@link C#RESULT_NOTHING_READ} is returned otherwise.
 *
 * @param formatHolder A {@link FormatHolder} to populate in the case of reading a format.
 * @param buffer A {@link DecoderInputBuffer} to populate in the case of reading a sample or the
 *     end of the stream. If the end of the stream has been reached, the {@link
 *     C#BUFFER_FLAG_END_OF_STREAM} flag will be set on the buffer.
 * @param formatRequired Whether the caller requires that the format of the stream be read even if
 *     it's not changing. A sample will never be read if set to true, however it is still possible
 *     for the end of stream or nothing to be read.
 * @return The result, which can be {@link C#RESULT_NOTHING_READ}, {@link C#RESULT_FORMAT_READ} or
 *     {@link C#RESULT_BUFFER_READ}.
 */
protected final int readSource(
    FormatHolder formatHolder, DecoderInputBuffer buffer, boolean formatRequired) {
  int result = stream.readData(formatHolder, buffer, formatRequired);
  if (result == C.RESULT_BUFFER_READ) {
    if (buffer.isEndOfStream()) {
      readingPositionUs = C.TIME_END_OF_SOURCE;
      return streamIsFinal ? C.RESULT_BUFFER_READ : C.RESULT_NOTHING_READ;
    }
    buffer.timeUs += streamOffsetUs;
    readingPositionUs = Math.max(readingPositionUs, buffer.timeUs);
  } else if (result == C.RESULT_FORMAT_READ) {
    Format format = formatHolder.format;
    if (format.subsampleOffsetUs != Format.OFFSET_SAMPLE_RELATIVE) {
      format = format.copyWithSubsampleOffsetUs(format.subsampleOffsetUs + streamOffsetUs);
      formatHolder.format = format;
    }
  }
  return result;
}
 
Example #17
Source File: SoftAudioRenderer.java    From DanDanPlayForAndroid with MIT License 5 votes vote down vote up
@Override
protected SimpleDecoder<DecoderInputBuffer, ? extends SimpleOutputBuffer, ? extends AudioSoftDecoderException> createDecoder(Format format, ExoMediaCrypto mediaCrypto) throws AudioSoftDecoderException {
  int initialInputBufferSize =
          format.maxInputSize != Format.NO_VALUE ? format.maxInputSize : DEFAULT_INPUT_BUFFER_SIZE;
  decoder = new AudioDecoder(
                  NUM_BUFFERS, NUM_BUFFERS, initialInputBufferSize, format, shouldUseFloatOutput(format));
  return decoder;
}
 
Example #18
Source File: DefaultTrackOutput.java    From K-Sonic with MIT License 5 votes vote down vote up
/**
 * Attempts to read from the queue.
 *
 * @param formatHolder A {@link FormatHolder} to populate in the case of reading a format.
 * @param buffer A {@link DecoderInputBuffer} to populate in the case of reading a sample or the
 *     end of the stream. If the end of the stream has been reached, the
 *     {@link C#BUFFER_FLAG_END_OF_STREAM} flag will be set on the buffer.
 * @param formatRequired Whether the caller requires that the format of the stream be read even if
 *     it's not changing. A sample will never be read if set to true, however it is still possible
 *     for the end of stream or nothing to be read.
 * @param loadingFinished True if an empty queue should be considered the end of the stream.
 * @param decodeOnlyUntilUs If a buffer is read, the {@link C#BUFFER_FLAG_DECODE_ONLY} flag will
 *     be set if the buffer's timestamp is less than this value.
 * @return The result, which can be {@link C#RESULT_NOTHING_READ}, {@link C#RESULT_FORMAT_READ} or
 *     {@link C#RESULT_BUFFER_READ}.
 */
public int readData(FormatHolder formatHolder, DecoderInputBuffer buffer, boolean formatRequired,
    boolean loadingFinished, long decodeOnlyUntilUs) {
  int result = infoQueue.readData(formatHolder, buffer, formatRequired, loadingFinished,
      downstreamFormat, extrasHolder);
  switch (result) {
    case C.RESULT_FORMAT_READ:
      downstreamFormat = formatHolder.format;
      return C.RESULT_FORMAT_READ;
    case C.RESULT_BUFFER_READ:
      if (!buffer.isEndOfStream()) {
        if (buffer.timeUs < decodeOnlyUntilUs) {
          buffer.addFlag(C.BUFFER_FLAG_DECODE_ONLY);
        }
        // Read encryption data if the sample is encrypted.
        if (buffer.isEncrypted()) {
          readEncryptionData(buffer, extrasHolder);
        }
        // Write the sample data into the holder.
        buffer.ensureSpaceForWrite(extrasHolder.size);
        readData(extrasHolder.offset, buffer.data, extrasHolder.size);
        // Advance the read head.
        dropDownstreamTo(extrasHolder.nextOffset);
      }
      return C.RESULT_BUFFER_READ;
    case C.RESULT_NOTHING_READ:
      return C.RESULT_NOTHING_READ;
    default:
      throw new IllegalStateException();
  }
}
 
Example #19
Source File: FfmpegDecoder.java    From PowerFileExplorer with GNU General Public License v3.0 5 votes vote down vote up
public FfmpegDecoder(int numInputBuffers, int numOutputBuffers, int initialInputBufferSize,
    String mimeType, List<byte[]> initializationData) throws FfmpegDecoderException {
  super(new DecoderInputBuffer[numInputBuffers], new SimpleOutputBuffer[numOutputBuffers]);
  if (!FfmpegLibrary.isAvailable()) {
    throw new FfmpegDecoderException("Failed to load decoder native libraries.");
  }
  codecName = FfmpegLibrary.getCodecName(mimeType);
  extraData = getExtraData(mimeType, initializationData);
  nativeContext = ffmpegInitialize(codecName, extraData);
  if (nativeContext == 0) {
    throw new FfmpegDecoderException("Initialization failed.");
  }
  setInitialInputBufferSize(initialInputBufferSize);
}
 
Example #20
Source File: SampleMetadataQueue.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Attempts to read from the queue.
 *
 * @param formatHolder A {@link FormatHolder} to populate in the case of reading a format.
 * @param buffer A {@link DecoderInputBuffer} to populate in the case of reading a sample or the
 *     end of the stream. If a sample is read then the buffer is populated with information
 *     about the sample, but not its data. The size and absolute position of the data in the
 *     rolling buffer is stored in {@code extrasHolder}, along with an encryption id if present
 *     and the absolute position of the first byte that may still be required after the current
 *     sample has been read. May be null if the caller requires that the format of the stream be
 *     read even if it's not changing.
 * @param formatRequired Whether the caller requires that the format of the stream be read even
 *     if it's not changing. A sample will never be read if set to true, however it is still
 *     possible for the end of stream or nothing to be read.
 * @param loadingFinished True if an empty queue should be considered the end of the stream.
 * @param downstreamFormat The current downstream {@link Format}. If the format of the next
 *     sample is different to the current downstream format then a format will be read.
 * @param extrasHolder The holder into which extra sample information should be written.
 * @return The result, which can be {@link C#RESULT_NOTHING_READ}, {@link C#RESULT_FORMAT_READ}
 *     or {@link C#RESULT_BUFFER_READ}.
 */
@SuppressWarnings("ReferenceEquality")
public synchronized int read(FormatHolder formatHolder, DecoderInputBuffer buffer,
    boolean formatRequired, boolean loadingFinished, Format downstreamFormat,
    SampleExtrasHolder extrasHolder) {
  if (!hasNextSample()) {
    if (loadingFinished) {
      buffer.setFlags(C.BUFFER_FLAG_END_OF_STREAM);
      return C.RESULT_BUFFER_READ;
    } else if (upstreamFormat != null
        && (formatRequired || upstreamFormat != downstreamFormat)) {
      formatHolder.format = upstreamFormat;
      return C.RESULT_FORMAT_READ;
    } else {
      return C.RESULT_NOTHING_READ;
    }
  }

  int relativeReadIndex = getRelativeIndex(readPosition);
  if (formatRequired || formats[relativeReadIndex] != downstreamFormat) {
    formatHolder.format = formats[relativeReadIndex];
    return C.RESULT_FORMAT_READ;
  }

  if (buffer.isFlagsOnly()) {
    return C.RESULT_NOTHING_READ;
  }

  buffer.timeUs = timesUs[relativeReadIndex];
  buffer.setFlags(flags[relativeReadIndex]);
  extrasHolder.size = sizes[relativeReadIndex];
  extrasHolder.offset = offsets[relativeReadIndex];
  extrasHolder.cryptoData = cryptoDatas[relativeReadIndex];

  readPosition++;
  return C.RESULT_BUFFER_READ;
}
 
Example #21
Source File: SingleSampleMediaPeriod.java    From MediaSDK with Apache License 2.0 5 votes vote down vote up
@Override
public int readData(FormatHolder formatHolder, DecoderInputBuffer buffer,
    boolean requireFormat) {
  maybeNotifyDownstreamFormat();
  if (streamState == STREAM_STATE_END_OF_STREAM) {
    buffer.addFlag(C.BUFFER_FLAG_END_OF_STREAM);
    return C.RESULT_BUFFER_READ;
  } else if (requireFormat || streamState == STREAM_STATE_SEND_FORMAT) {
    formatHolder.format = format;
    streamState = STREAM_STATE_SEND_SAMPLE;
    return C.RESULT_FORMAT_READ;
  } else if (loadingFinished) {
    if (sampleData != null) {
      buffer.addFlag(C.BUFFER_FLAG_KEY_FRAME);
      buffer.timeUs = 0;
      if (buffer.isFlagsOnly()) {
        return C.RESULT_BUFFER_READ;
      }
      buffer.ensureSpaceForWrite(sampleSize);
      buffer.data.put(sampleData, 0, sampleSize);
    } else {
      buffer.addFlag(C.BUFFER_FLAG_END_OF_STREAM);
    }
    streamState = STREAM_STATE_END_OF_STREAM;
    return C.RESULT_BUFFER_READ;
  }
  return C.RESULT_NOTHING_READ;
}
 
Example #22
Source File: ProgressiveMediaPeriod.java    From Telegram-FOSS with GNU General Public License v2.0 5 votes vote down vote up
int readData(int track, FormatHolder formatHolder, DecoderInputBuffer buffer,
    boolean formatRequired) {
  if (suppressRead()) {
    return C.RESULT_NOTHING_READ;
  }
  maybeNotifyDownstreamFormat(track);
  int result =
      sampleQueues[track].read(
          formatHolder, buffer, formatRequired, loadingFinished, lastSeekPositionUs);
  if (result == C.RESULT_NOTHING_READ) {
    maybeStartDeferredRetry(track);
  }
  return result;
}
 
Example #23
Source File: ExtractorMediaPeriod.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
int readData(int track, FormatHolder formatHolder, DecoderInputBuffer buffer,
    boolean formatRequired) {
  if (suppressRead()) {
    return C.RESULT_NOTHING_READ;
  }
  int result =
      sampleQueues[track].read(
          formatHolder, buffer, formatRequired, loadingFinished, lastSeekPositionUs);
  if (result == C.RESULT_BUFFER_READ) {
    maybeNotifyTrackFormat(track);
  } else if (result == C.RESULT_NOTHING_READ) {
    maybeStartDeferredRetry(track);
  }
  return result;
}
 
Example #24
Source File: MediaCodecAudioRenderer.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected void onQueueInputBuffer(DecoderInputBuffer buffer) {
  if (allowFirstBufferPositionDiscontinuity && !buffer.isDecodeOnly()) {
    // TODO: Remove this hack once we have a proper fix for [Internal: b/71876314].
    // Allow the position to jump if the first presentable input buffer has a timestamp that
    // differs significantly from what was expected.
    if (Math.abs(buffer.timeUs - currentPositionUs) > 500000) {
      currentPositionUs = buffer.timeUs;
    }
    allowFirstBufferPositionDiscontinuity = false;
  }
}
 
Example #25
Source File: FlacDecoder.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates a Flac decoder.
 *
 * @param numInputBuffers The number of input buffers.
 * @param numOutputBuffers The number of output buffers.
 * @param maxInputBufferSize The maximum required input buffer size if known, or {@link
 *     Format#NO_VALUE} otherwise.
 * @param initializationData Codec-specific initialization data. It should contain only one entry
 *     which is the flac file header.
 * @throws FlacDecoderException Thrown if an exception occurs when initializing the decoder.
 */
public FlacDecoder(
    int numInputBuffers,
    int numOutputBuffers,
    int maxInputBufferSize,
    List<byte[]> initializationData)
    throws FlacDecoderException {
  super(new DecoderInputBuffer[numInputBuffers], new SimpleOutputBuffer[numOutputBuffers]);
  if (initializationData.size() != 1) {
    throw new FlacDecoderException("Initialization data must be of length 1");
  }
  decoderJni = new FlacDecoderJni();
  decoderJni.setData(ByteBuffer.wrap(initializationData.get(0)));
  FlacStreamInfo streamInfo;
  try {
    streamInfo = decoderJni.decodeMetadata();
  } catch (IOException | InterruptedException e) {
    // Never happens.
    throw new IllegalStateException(e);
  }
  if (streamInfo == null) {
    throw new FlacDecoderException("Metadata decoding failed");
  }

  int initialInputBufferSize =
      maxInputBufferSize != Format.NO_VALUE ? maxInputBufferSize : streamInfo.maxFrameSize;
  setInitialInputBufferSize(initialInputBufferSize);
  maxOutputBufferSize = streamInfo.maxDecodedFrameSize();
}
 
Example #26
Source File: ChunkSampleStream.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
@Override
public int readData(FormatHolder formatHolder, DecoderInputBuffer buffer,
    boolean formatRequired) {
  if (isPendingReset()) {
    return C.RESULT_NOTHING_READ;
  }
  int result =
      sampleQueue.read(
          formatHolder, buffer, formatRequired, loadingFinished, decodeOnlyUntilPositionUs);
  if (result == C.RESULT_BUFFER_READ) {
    maybeNotifyTrackFormatChanged();
  }
  return result;
}
 
Example #27
Source File: SampleQueue.java    From Telegram-FOSS with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Attempts to read from the queue.
 *
 * @param formatHolder A {@link FormatHolder} to populate in the case of reading a format.
 * @param buffer A {@link DecoderInputBuffer} to populate in the case of reading a sample or the
 *     end of the stream. If the end of the stream has been reached, the {@link
 *     C#BUFFER_FLAG_END_OF_STREAM} flag will be set on the buffer. If a {@link
 *     DecoderInputBuffer#isFlagsOnly() flags-only} buffer is passed, only the buffer flags may be
 *     populated by this method and the read position of the queue will not change.
 * @param formatRequired Whether the caller requires that the format of the stream be read even if
 *     it's not changing. A sample will never be read if set to true, however it is still possible
 *     for the end of stream or nothing to be read.
 * @param loadingFinished True if an empty queue should be considered the end of the stream.
 * @param decodeOnlyUntilUs If a buffer is read, the {@link C#BUFFER_FLAG_DECODE_ONLY} flag will
 *     be set if the buffer's timestamp is less than this value.
 * @return The result, which can be {@link C#RESULT_NOTHING_READ}, {@link C#RESULT_FORMAT_READ} or
 *     {@link C#RESULT_BUFFER_READ}.
 */
public int read(
    FormatHolder formatHolder,
    DecoderInputBuffer buffer,
    boolean formatRequired,
    boolean loadingFinished,
    long decodeOnlyUntilUs) {
  int result = metadataQueue.read(formatHolder, buffer, formatRequired, loadingFinished,
      downstreamFormat, extrasHolder);
  switch (result) {
    case C.RESULT_FORMAT_READ:
      downstreamFormat = formatHolder.format;
      return C.RESULT_FORMAT_READ;
    case C.RESULT_BUFFER_READ:
      if (!buffer.isEndOfStream()) {
        if (buffer.timeUs < decodeOnlyUntilUs) {
          buffer.addFlag(C.BUFFER_FLAG_DECODE_ONLY);
        }
        if (!buffer.isFlagsOnly()) {
          // Read encryption data if the sample is encrypted.
          if (buffer.isEncrypted()) {
            readEncryptionData(buffer, extrasHolder);
          }
          // Write the sample data into the holder.
          buffer.ensureSpaceForWrite(extrasHolder.size);
          readData(extrasHolder.offset, buffer.data, extrasHolder.size);
        }
      }
      return C.RESULT_BUFFER_READ;
    case C.RESULT_NOTHING_READ:
      return C.RESULT_NOTHING_READ;
    default:
      throw new IllegalStateException();
  }
}
 
Example #28
Source File: MediaCodecRenderer.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
private static MediaCodec.CryptoInfo getFrameworkCryptoInfo(
    DecoderInputBuffer buffer, int adaptiveReconfigurationBytes) {
  MediaCodec.CryptoInfo cryptoInfo = buffer.cryptoInfo.getFrameworkCryptoInfoV16();
  if (adaptiveReconfigurationBytes == 0) {
    return cryptoInfo;
  }
  // There must be at least one sub-sample, although numBytesOfClearData is permitted to be
  // null if it contains no clear data. Instantiate it if needed, and add the reconfiguration
  // bytes to the clear byte count of the first sub-sample.
  if (cryptoInfo.numBytesOfClearData == null) {
    cryptoInfo.numBytesOfClearData = new int[1];
  }
  cryptoInfo.numBytesOfClearData[0] += adaptiveReconfigurationBytes;
  return cryptoInfo;
}
 
Example #29
Source File: SimpleDecoderAudioRenderer.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
private void onQueueInputBuffer(DecoderInputBuffer buffer) {
  if (allowFirstBufferPositionDiscontinuity && !buffer.isDecodeOnly()) {
    // TODO: Remove this hack once we have a proper fix for [Internal: b/71876314].
    // Allow the position to jump if the first presentable input buffer has a timestamp that
    // differs significantly from what was expected.
    if (Math.abs(buffer.timeUs - currentPositionUs) > 500000) {
      currentPositionUs = buffer.timeUs;
    }
    allowFirstBufferPositionDiscontinuity = false;
  }
}
 
Example #30
Source File: MediaCodecAudioRenderer.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected void onQueueInputBuffer(DecoderInputBuffer buffer) {
  if (allowFirstBufferPositionDiscontinuity && !buffer.isDecodeOnly()) {
    // TODO: Remove this hack once we have a proper fix for [Internal: b/71876314].
    // Allow the position to jump if the first presentable input buffer has a timestamp that
    // differs significantly from what was expected.
    if (Math.abs(buffer.timeUs - currentPositionUs) > 500000) {
      currentPositionUs = buffer.timeUs;
    }
    allowFirstBufferPositionDiscontinuity = false;
  }
}