Java Code Examples for com.google.android.exoplayer2.util.Util#constrainValue()

The following examples show how to use com.google.android.exoplayer2.util.Util#constrainValue() . 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: WavHeader.java    From MediaSDK with Apache License 2.0 6 votes vote down vote up
@Override
public SeekPoints getSeekPoints(long timeUs) {
  long dataSize = dataEndPosition - dataStartPosition;
  long positionOffset = (timeUs * averageBytesPerSecond) / C.MICROS_PER_SECOND;
  // Constrain to nearest preceding frame offset.
  positionOffset = (positionOffset / blockAlignment) * blockAlignment;
  positionOffset = Util.constrainValue(positionOffset, 0, dataSize - blockAlignment);
  long seekPosition = dataStartPosition + positionOffset;
  long seekTimeUs = getTimeUs(seekPosition);
  SeekPoint seekPoint = new SeekPoint(seekTimeUs, seekPosition);
  if (seekTimeUs >= timeUs || positionOffset == dataSize - blockAlignment) {
    return new SeekPoints(seekPoint);
  } else {
    long secondSeekPosition = seekPosition + blockAlignment;
    long secondSeekTimeUs = getTimeUs(secondSeekPosition);
    SeekPoint secondSeekPoint = new SeekPoint(secondSeekTimeUs, secondSeekPosition);
    return new SeekPoints(seekPoint, secondSeekPoint);
  }
}
 
Example 2
Source File: ClippingMediaPeriod.java    From TelePlus-Android with GNU General Public License v2.0 6 votes vote down vote up
private SeekParameters clipSeekParameters(long positionUs, SeekParameters seekParameters) {
  long toleranceBeforeUs =
      Util.constrainValue(
          seekParameters.toleranceBeforeUs, /* min= */ 0, /* max= */ positionUs - startUs);
  long toleranceAfterUs =
      Util.constrainValue(
          seekParameters.toleranceAfterUs,
          /* min= */ 0,
          /* max= */ endUs == C.TIME_END_OF_SOURCE ? Long.MAX_VALUE : endUs - positionUs);
  if (toleranceBeforeUs == seekParameters.toleranceBeforeUs
      && toleranceAfterUs == seekParameters.toleranceAfterUs) {
    return seekParameters;
  } else {
    return new SeekParameters(toleranceBeforeUs, toleranceAfterUs);
  }
}
 
Example 3
Source File: ClippingMediaPeriod.java    From Telegram-FOSS with GNU General Public License v2.0 6 votes vote down vote up
private SeekParameters clipSeekParameters(long positionUs, SeekParameters seekParameters) {
  long toleranceBeforeUs =
      Util.constrainValue(
          seekParameters.toleranceBeforeUs, /* min= */ 0, /* max= */ positionUs - startUs);
  long toleranceAfterUs =
      Util.constrainValue(
          seekParameters.toleranceAfterUs,
          /* min= */ 0,
          /* max= */ endUs == C.TIME_END_OF_SOURCE ? Long.MAX_VALUE : endUs - positionUs);
  if (toleranceBeforeUs == seekParameters.toleranceBeforeUs
      && toleranceAfterUs == seekParameters.toleranceAfterUs) {
    return seekParameters;
  } else {
    return new SeekParameters(toleranceBeforeUs, toleranceAfterUs);
  }
}
 
Example 4
Source File: WavHeader.java    From Telegram with GNU General Public License v2.0 6 votes vote down vote up
@Override
public SeekPoints getSeekPoints(long timeUs) {
  long dataSize = dataEndPosition - dataStartPosition;
  long positionOffset = (timeUs * averageBytesPerSecond) / C.MICROS_PER_SECOND;
  // Constrain to nearest preceding frame offset.
  positionOffset = (positionOffset / blockAlignment) * blockAlignment;
  positionOffset = Util.constrainValue(positionOffset, 0, dataSize - blockAlignment);
  long seekPosition = dataStartPosition + positionOffset;
  long seekTimeUs = getTimeUs(seekPosition);
  SeekPoint seekPoint = new SeekPoint(seekTimeUs, seekPosition);
  if (seekTimeUs >= timeUs || positionOffset == dataSize - blockAlignment) {
    return new SeekPoints(seekPoint);
  } else {
    long secondSeekPosition = seekPosition + blockAlignment;
    long secondSeekTimeUs = getTimeUs(secondSeekPosition);
    SeekPoint secondSeekPoint = new SeekPoint(secondSeekTimeUs, secondSeekPosition);
    return new SeekPoints(seekPoint, secondSeekPoint);
  }
}
 
Example 5
Source File: BasePlayer.java    From MediaSDK with Apache License 2.0 5 votes vote down vote up
@Override
public final int getBufferedPercentage() {
  long position = getBufferedPosition();
  long duration = getDuration();
  return position == C.TIME_UNSET || duration == C.TIME_UNSET
      ? 0
      : duration == 0 ? 100 : Util.constrainValue((int) ((position * 100) / duration), 0, 100);
}
 
Example 6
Source File: BasePlayer.java    From Telegram with GNU General Public License v2.0 5 votes vote down vote up
@Override
public final int getBufferedPercentage() {
  long position = getBufferedPosition();
  long duration = getDuration();
  return position == C.TIME_UNSET || duration == C.TIME_UNSET
      ? 0
      : duration == 0 ? 100 : Util.constrainValue((int) ((position * 100) / duration), 0, 100);
}
 
Example 7
Source File: DefaultDashChunkSource.java    From MediaSDK with Apache License 2.0 5 votes vote down vote up
private long getSegmentNum(
    RepresentationHolder representationHolder,
    @Nullable MediaChunk previousChunk,
    long loadPositionUs,
    long firstAvailableSegmentNum,
    long lastAvailableSegmentNum) {
  return previousChunk != null
      ? previousChunk.getNextChunkIndex()
      : Util.constrainValue(
          representationHolder.getSegmentNum(loadPositionUs),
          firstAvailableSegmentNum,
          lastAvailableSegmentNum);
}
 
Example 8
Source File: ConstantBitrateSeekMap.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
private long getFramePositionForTimeUs(long timeUs) {
  long positionOffset = (timeUs * bitrate) / (C.MICROS_PER_SECOND * C.BITS_PER_BYTE);
  // Constrain to nearest preceding frame offset.
  positionOffset = (positionOffset / frameSize) * frameSize;
  positionOffset =
      Util.constrainValue(positionOffset, /* min= */ 0, /* max= */ dataSize - frameSize);
  return firstFrameBytePosition + positionOffset;
}
 
Example 9
Source File: Tx3gDecoder.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
private void decodeInitializationData(List<byte[]> initializationData) {
  if (initializationData != null && initializationData.size() == 1
      && (initializationData.get(0).length == 48 || initializationData.get(0).length == 53)) {
    byte[] initializationBytes = initializationData.get(0);
    defaultFontFace = initializationBytes[24];
    defaultColorRgba = ((initializationBytes[26] & 0xFF) << 24)
        | ((initializationBytes[27] & 0xFF) << 16)
        | ((initializationBytes[28] & 0xFF) << 8)
        | (initializationBytes[29] & 0xFF);
    String fontFamily =
        Util.fromUtf8Bytes(initializationBytes, 43, initializationBytes.length - 43);
    defaultFontFamily = TX3G_SERIF.equals(fontFamily) ? C.SERIF_NAME : C.SANS_SERIF_NAME;
    //font size (initializationBytes[25]) is 5% of video height
    calculatedVideoTrackHeight = 20 * initializationBytes[25];
    customVerticalPlacement = (initializationBytes[0] & 0x20) != 0;
    if (customVerticalPlacement) {
      int requestedVerticalPlacement = ((initializationBytes[10] & 0xFF) << 8)
          | (initializationBytes[11] & 0xFF);
      defaultVerticalPlacement = (float) requestedVerticalPlacement / calculatedVideoTrackHeight;
      defaultVerticalPlacement = Util.constrainValue(defaultVerticalPlacement, 0.0f, 0.95f);
    } else {
      defaultVerticalPlacement = DEFAULT_VERTICAL_PLACEMENT;
    }
  } else {
    defaultFontFace = DEFAULT_FONT_FACE;
    defaultColorRgba = DEFAULT_COLOR;
    defaultFontFamily = DEFAULT_FONT_FAMILY;
    customVerticalPlacement = false;
    defaultVerticalPlacement = DEFAULT_VERTICAL_PLACEMENT;
  }
}
 
Example 10
Source File: DefaultDashChunkSource.java    From Telegram-FOSS with GNU General Public License v2.0 5 votes vote down vote up
private long getSegmentNum(
    RepresentationHolder representationHolder,
    @Nullable MediaChunk previousChunk,
    long loadPositionUs,
    long firstAvailableSegmentNum,
    long lastAvailableSegmentNum) {
  return previousChunk != null
      ? previousChunk.getNextChunkIndex()
      : Util.constrainValue(
          representationHolder.getSegmentNum(loadPositionUs),
          firstAvailableSegmentNum,
          lastAvailableSegmentNum);
}
 
Example 11
Source File: XingSeeker.java    From Telegram-FOSS with GNU General Public License v2.0 5 votes vote down vote up
@Override
public SeekPoints getSeekPoints(long timeUs) {
  if (!isSeekable()) {
    return new SeekPoints(new SeekPoint(0, dataStartPosition + xingFrameSize));
  }
  timeUs = Util.constrainValue(timeUs, 0, durationUs);
  double percent = (timeUs * 100d) / durationUs;
  double scaledPosition;
  if (percent <= 0) {
    scaledPosition = 0;
  } else if (percent >= 100) {
    scaledPosition = 256;
  } else {
    int prevTableIndex = (int) percent;
    long[] tableOfContents = Assertions.checkNotNull(this.tableOfContents);
    double prevScaledPosition = tableOfContents[prevTableIndex];
    double nextScaledPosition = prevTableIndex == 99 ? 256 : tableOfContents[prevTableIndex + 1];
    // Linearly interpolate between the two scaled positions.
    double interpolateFraction = percent - prevTableIndex;
    scaledPosition = prevScaledPosition
        + (interpolateFraction * (nextScaledPosition - prevScaledPosition));
  }
  long positionOffset = Math.round((scaledPosition / 256) * dataSize);
  // Ensure returned positions skip the frame containing the XING header.
  positionOffset = Util.constrainValue(positionOffset, xingFrameSize, dataSize - 1);
  return new SeekPoints(new SeekPoint(timeUs, dataStartPosition + positionOffset));
}
 
Example 12
Source File: SonicAudioProcessor.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Sets the playback pitch. Calling this method will discard any data buffered within the
 * processor, and may update the value returned by {@link #isActive()}.
 *
 * @param pitch The requested new pitch.
 * @return The actual new pitch.
 */
public float setPitch(float pitch) {
  pitch = Util.constrainValue(pitch, MINIMUM_PITCH, MAXIMUM_PITCH);
  if (this.pitch != pitch) {
    this.pitch = pitch;
    sonic = null;
  }
  flush();
  return pitch;
}
 
Example 13
Source File: DefaultOggSeeker.java    From Telegram-FOSS with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void startSeek(long targetGranule) {
  this.targetGranule = Util.constrainValue(targetGranule, 0, totalGranules - 1);
  state = STATE_SEEK;
  start = payloadStartPosition;
  end = payloadEndPosition;
  startGranule = 0;
  endGranule = totalGranules;
}
 
Example 14
Source File: SonicAudioProcessor.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Sets the playback speed. Calling this method will discard any data buffered within the
 * processor, and may update the value returned by {@link #isActive()}.
 *
 * @param speed The requested new playback speed.
 * @return The actual new playback speed.
 */
public float setSpeed(float speed) {
  speed = Util.constrainValue(speed, MINIMUM_SPEED, MAXIMUM_SPEED);
  if (this.speed != speed) {
    this.speed = speed;
    sonic = null;
  }
  flush();
  return speed;
}
 
Example 15
Source File: SimpleExoPlayer.java    From Telegram with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void setVolume(float audioVolume) {
  verifyApplicationThread();
  audioVolume = Util.constrainValue(audioVolume, /* min= */ 0, /* max= */ 1);
  if (this.audioVolume == audioVolume) {
    return;
  }
  this.audioVolume = audioVolume;
  sendVolumeToRenderers();
  for (AudioListener audioListener : audioListeners) {
    audioListener.onVolumeChanged(audioVolume);
  }
}
 
Example 16
Source File: AtomParsers.java    From MediaSDK with Apache License 2.0 5 votes vote down vote up
/** Returns whether it's possible to apply the specified edit using gapless playback info. */
private static boolean canApplyEditWithGaplessInfo(
    long[] timestamps, long duration, long editStartTime, long editEndTime) {
  int lastIndex = timestamps.length - 1;
  int latestDelayIndex = Util.constrainValue(MAX_GAPLESS_TRIM_SIZE_SAMPLES, 0, lastIndex);
  int earliestPaddingIndex =
      Util.constrainValue(timestamps.length - MAX_GAPLESS_TRIM_SIZE_SAMPLES, 0, lastIndex);
  return timestamps[0] <= editStartTime
      && editStartTime < timestamps[latestDelayIndex]
      && timestamps[earliestPaddingIndex] < editEndTime
      && editEndTime <= duration;
}
 
Example 17
Source File: SonicAudioProcessor.java    From MediaSDK with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the playback speed. This method may only be called after draining data through the
 * processor. The value returned by {@link #isActive()} may change, and the processor must be
 * {@link #flush() flushed} before queueing more data.
 *
 * @param speed The requested new playback speed.
 * @return The actual new playback speed.
 */
public float setSpeed(float speed) {
  speed = Util.constrainValue(speed, MINIMUM_SPEED, MAXIMUM_SPEED);
  if (this.speed != speed) {
    this.speed = speed;
    pendingSonicRecreation = true;
  }
  return speed;
}
 
Example 18
Source File: BinarySearchSeeker.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns the next position in the stream to search for target frame, given [floorBytePosition,
 * ceilingBytePosition), with corresponding [floorTimePosition, ceilingTimePosition).
 */
protected static long calculateNextSearchBytePosition(
    long targetTimePosition,
    long floorTimePosition,
    long ceilingTimePosition,
    long floorBytePosition,
    long ceilingBytePosition,
    long approxBytesPerFrame) {
  if (floorBytePosition + 1 >= ceilingBytePosition
      || floorTimePosition + 1 >= ceilingTimePosition) {
    return floorBytePosition;
  }
  long seekTimeDuration = targetTimePosition - floorTimePosition;
  float estimatedBytesPerTimeUnit =
      (float) (ceilingBytePosition - floorBytePosition)
          / (ceilingTimePosition - floorTimePosition);
  // It's better to under-estimate rather than over-estimate, because the extractor
  // input can skip forward easily, but cannot rewind easily (it may require a new connection
  // to be made).
  // Therefore, we should reduce the estimated position by some amount, so it will converge to
  // the correct frame earlier.
  long bytesToSkip = (long) (seekTimeDuration * estimatedBytesPerTimeUnit);
  long confidenceInterval = bytesToSkip / 20;
  long estimatedFramePosition = floorBytePosition + bytesToSkip - approxBytesPerFrame;
  long estimatedPosition = estimatedFramePosition - confidenceInterval;
  return Util.constrainValue(estimatedPosition, floorBytePosition, ceilingBytePosition - 1);
}
 
Example 19
Source File: TrimmingAudioProcessor.java    From TelePlus-Android with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void queueInput(ByteBuffer inputBuffer) {
  int position = inputBuffer.position();
  int limit = inputBuffer.limit();
  int remaining = limit - position;

  // Trim any pending start bytes from the input buffer.
  int trimBytes = Math.min(remaining, pendingTrimStartBytes);
  pendingTrimStartBytes -= trimBytes;
  inputBuffer.position(position + trimBytes);
  if (pendingTrimStartBytes > 0) {
    // Nothing to output yet.
    return;
  }
  remaining -= trimBytes;

  // endBuffer must be kept as full as possible, so that we trim the right amount of media if we
  // don't receive any more input. After taking into account the number of bytes needed to keep
  // endBuffer as full as possible, the output should be any surplus bytes currently in endBuffer
  // followed by any surplus bytes in the new inputBuffer.
  int remainingBytesToOutput = endBufferSize + remaining - endBuffer.length;
  if (buffer.capacity() < remainingBytesToOutput) {
    buffer = ByteBuffer.allocateDirect(remainingBytesToOutput).order(ByteOrder.nativeOrder());
  } else {
    buffer.clear();
  }

  // Output from endBuffer.
  int endBufferBytesToOutput = Util.constrainValue(remainingBytesToOutput, 0, endBufferSize);
  buffer.put(endBuffer, 0, endBufferBytesToOutput);
  remainingBytesToOutput -= endBufferBytesToOutput;

  // Output from inputBuffer, restoring its limit afterwards.
  int inputBufferBytesToOutput = Util.constrainValue(remainingBytesToOutput, 0, remaining);
  inputBuffer.limit(inputBuffer.position() + inputBufferBytesToOutput);
  buffer.put(inputBuffer);
  inputBuffer.limit(limit);
  remaining -= inputBufferBytesToOutput;

  // Compact endBuffer, then repopulate it using the new input.
  endBufferSize -= endBufferBytesToOutput;
  System.arraycopy(endBuffer, endBufferBytesToOutput, endBuffer, 0, endBufferSize);
  inputBuffer.get(endBuffer, endBufferSize, remaining);
  endBufferSize += remaining;

  buffer.flip();
  outputBuffer = buffer;
}
 
Example 20
Source File: TrimmingAudioProcessor.java    From MediaSDK with Apache License 2.0 4 votes vote down vote up
@Override
public void queueInput(ByteBuffer inputBuffer) {
  int position = inputBuffer.position();
  int limit = inputBuffer.limit();
  int remaining = limit - position;

  if (remaining == 0) {
    return;
  }

  // Trim any pending start bytes from the input buffer.
  int trimBytes = Math.min(remaining, pendingTrimStartBytes);
  trimmedFrameCount += trimBytes / inputAudioFormat.bytesPerFrame;
  pendingTrimStartBytes -= trimBytes;
  inputBuffer.position(position + trimBytes);
  if (pendingTrimStartBytes > 0) {
    // Nothing to output yet.
    return;
  }
  remaining -= trimBytes;

  // endBuffer must be kept as full as possible, so that we trim the right amount of media if we
  // don't receive any more input. After taking into account the number of bytes needed to keep
  // endBuffer as full as possible, the output should be any surplus bytes currently in endBuffer
  // followed by any surplus bytes in the new inputBuffer.
  int remainingBytesToOutput = endBufferSize + remaining - endBuffer.length;
  ByteBuffer buffer = replaceOutputBuffer(remainingBytesToOutput);

  // Output from endBuffer.
  int endBufferBytesToOutput = Util.constrainValue(remainingBytesToOutput, 0, endBufferSize);
  buffer.put(endBuffer, 0, endBufferBytesToOutput);
  remainingBytesToOutput -= endBufferBytesToOutput;

  // Output from inputBuffer, restoring its limit afterwards.
  int inputBufferBytesToOutput = Util.constrainValue(remainingBytesToOutput, 0, remaining);
  inputBuffer.limit(inputBuffer.position() + inputBufferBytesToOutput);
  buffer.put(inputBuffer);
  inputBuffer.limit(limit);
  remaining -= inputBufferBytesToOutput;

  // Compact endBuffer, then repopulate it using the new input.
  endBufferSize -= endBufferBytesToOutput;
  System.arraycopy(endBuffer, endBufferBytesToOutput, endBuffer, 0, endBufferSize);
  inputBuffer.get(endBuffer, endBufferSize, remaining);
  endBufferSize += remaining;

  buffer.flip();
}