Commit fda3b3d8 by ibaker Committed by Oliver Woodman

Use static imports for methods that make sense without their class name

PiperOrigin-RevId: 323349585
parent 7083dbf7
Showing with 441 additions and 260 deletions
......@@ -15,6 +15,8 @@
*/
package com.google.android.exoplayer2.ext.cast;
import static java.lang.Math.min;
import android.os.Looper;
import androidx.annotation.Nullable;
import com.google.android.exoplayer2.BasePlayer;
......@@ -335,7 +337,7 @@ public final class CastPlayer extends BasePlayer {
&& toIndex <= currentTimeline.getWindowCount()
&& newIndex >= 0
&& newIndex < currentTimeline.getWindowCount());
newIndex = Math.min(newIndex, currentTimeline.getWindowCount() - (toIndex - fromIndex));
newIndex = min(newIndex, currentTimeline.getWindowCount() - (toIndex - fromIndex));
if (fromIndex == toIndex || fromIndex == newIndex) {
// Do nothing.
return;
......@@ -811,7 +813,7 @@ public final class CastPlayer extends BasePlayer {
}
return remoteMediaClient.queueLoad(
mediaQueueItems,
Math.min(startWindowIndex, mediaQueueItems.length - 1),
min(startWindowIndex, mediaQueueItems.length - 1),
getCastRepeatMode(repeatMode),
startPositionMs,
/* customData= */ null);
......
......@@ -15,6 +15,8 @@
*/
package com.google.android.exoplayer2.ext.cast;
import static org.mockito.Mockito.when;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.testutil.TimelineAsserts;
......@@ -105,18 +107,18 @@ public class CastTimelineTrackerTest {
int[] itemIds, int currentItemId, long currentDurationMs) {
RemoteMediaClient remoteMediaClient = Mockito.mock(RemoteMediaClient.class);
MediaStatus status = Mockito.mock(MediaStatus.class);
Mockito.when(status.getQueueItems()).thenReturn(Collections.emptyList());
Mockito.when(remoteMediaClient.getMediaStatus()).thenReturn(status);
Mockito.when(status.getMediaInfo()).thenReturn(getMediaInfo(currentDurationMs));
Mockito.when(status.getCurrentItemId()).thenReturn(currentItemId);
when(status.getQueueItems()).thenReturn(Collections.emptyList());
when(remoteMediaClient.getMediaStatus()).thenReturn(status);
when(status.getMediaInfo()).thenReturn(getMediaInfo(currentDurationMs));
when(status.getCurrentItemId()).thenReturn(currentItemId);
MediaQueue mediaQueue = mockMediaQueue(itemIds);
Mockito.when(remoteMediaClient.getMediaQueue()).thenReturn(mediaQueue);
when(remoteMediaClient.getMediaQueue()).thenReturn(mediaQueue);
return remoteMediaClient;
}
private static MediaQueue mockMediaQueue(int[] itemIds) {
MediaQueue mediaQueue = Mockito.mock(MediaQueue.class);
Mockito.when(mediaQueue.getItemIds()).thenReturn(itemIds);
when(mediaQueue.getItemIds()).thenReturn(itemIds);
return mediaQueue;
}
......
......@@ -15,6 +15,8 @@
*/
package com.google.android.exoplayer2.ext.cronet;
import static java.lang.Math.min;
import java.io.IOException;
import java.nio.ByteBuffer;
import org.chromium.net.UploadDataProvider;
......@@ -40,7 +42,7 @@ import org.chromium.net.UploadDataSink;
@Override
public void read(UploadDataSink uploadDataSink, ByteBuffer byteBuffer) throws IOException {
int readLength = Math.min(byteBuffer.remaining(), data.length - position);
int readLength = min(byteBuffer.remaining(), data.length - position);
byteBuffer.put(data, position, readLength);
position += readLength;
uploadDataSink.onReadSucceeded(false);
......
......@@ -16,6 +16,8 @@
package com.google.android.exoplayer2.ext.cronet;
import static com.google.android.exoplayer2.util.Util.castNonNull;
import static java.lang.Math.max;
import static java.lang.Math.min;
import android.net.Uri;
import android.text.TextUtils;
......@@ -531,14 +533,14 @@ public class CronetDataSource extends BaseDataSource implements HttpDataSource {
readBuffer.flip();
Assertions.checkState(readBuffer.hasRemaining());
if (bytesToSkip > 0) {
int bytesSkipped = (int) Math.min(readBuffer.remaining(), bytesToSkip);
int bytesSkipped = (int) min(readBuffer.remaining(), bytesToSkip);
readBuffer.position(readBuffer.position() + bytesSkipped);
bytesToSkip -= bytesSkipped;
}
}
}
int bytesRead = Math.min(readBuffer.remaining(), readLength);
int bytesRead = min(readBuffer.remaining(), readLength);
readBuffer.get(buffer, offset, bytesRead);
if (bytesRemaining != C.LENGTH_UNSET) {
......@@ -846,7 +848,7 @@ public class CronetDataSource extends BaseDataSource implements HttpDataSource {
// would increase it.
Log.w(TAG, "Inconsistent headers [" + contentLengthHeader + "] [" + contentRangeHeader
+ "]");
contentLength = Math.max(contentLength, contentLengthFromRange);
contentLength = max(contentLength, contentLengthFromRange);
}
} catch (NumberFormatException e) {
Log.e(TAG, "Unexpected Content-Range [" + contentRangeHeader + "]");
......@@ -889,7 +891,7 @@ public class CronetDataSource extends BaseDataSource implements HttpDataSource {
// Copy as much as possible from the src buffer into dst buffer.
// Returns the number of bytes copied.
private static int copyByteBuffer(ByteBuffer src, ByteBuffer dst) {
int remaining = Math.min(src.remaining(), dst.remaining());
int remaining = min(src.remaining(), dst.remaining());
int limit = src.limit();
src.limit(src.position() + remaining);
dst.put(src);
......
......@@ -15,6 +15,8 @@
*/
package com.google.android.exoplayer2.ext.cronet;
import static java.lang.Math.min;
import android.content.Context;
import androidx.annotation.IntDef;
import androidx.annotation.Nullable;
......@@ -230,7 +232,7 @@ public final class CronetEngineWrapper {
}
String[] versionStringsLeft = Util.split(versionLeft, "\\.");
String[] versionStringsRight = Util.split(versionRight, "\\.");
int minLength = Math.min(versionStringsLeft.length, versionStringsRight.length);
int minLength = min(versionStringsLeft.length, versionStringsRight.length);
for (int i = 0; i < minLength; i++) {
if (!versionStringsLeft[i].equals(versionStringsRight[i])) {
try {
......
......@@ -16,6 +16,7 @@
package com.google.android.exoplayer2.ext.cronet;
import static com.google.common.truth.Truth.assertThat;
import static java.lang.Math.min;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
......@@ -1423,7 +1424,7 @@ public final class CronetDataSourceTest {
mockUrlRequest, testUrlResponseInfo);
} else {
ByteBuffer inputBuffer = (ByteBuffer) invocation.getArguments()[0];
int readLength = Math.min(positionAndRemaining[1], inputBuffer.remaining());
int readLength = min(positionAndRemaining[1], inputBuffer.remaining());
inputBuffer.put(buildTestDataBuffer(positionAndRemaining[0], readLength));
positionAndRemaining[0] += readLength;
positionAndRemaining[1] -= readLength;
......
......@@ -15,6 +15,8 @@
*/
package com.google.android.exoplayer2.ext.flac;
import static java.lang.Math.max;
import com.google.android.exoplayer2.extractor.BinarySearchSeeker;
import com.google.android.exoplayer2.extractor.ExtractorInput;
import com.google.android.exoplayer2.extractor.FlacStreamMetadata;
......@@ -74,7 +76,7 @@ import java.nio.ByteBuffer;
/* floorBytePosition= */ firstFramePosition,
/* ceilingBytePosition= */ inputLength,
/* approxBytesPerFrame= */ streamMetadata.getApproxBytesPerFrame(),
/* minimumSearchRange= */ Math.max(
/* minimumSearchRange= */ max(
FlacConstants.MIN_FRAME_HEADER_SIZE, streamMetadata.minFrameSize));
this.decoderJni = Assertions.checkNotNull(decoderJni);
}
......
......@@ -15,6 +15,8 @@
*/
package com.google.android.exoplayer2.ext.flac;
import static java.lang.Math.min;
import androidx.annotation.Nullable;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.ParserException;
......@@ -118,7 +120,7 @@ import java.nio.ByteBuffer;
public int read(ByteBuffer target) throws IOException {
int byteCount = target.remaining();
if (byteBufferData != null) {
byteCount = Math.min(byteCount, byteBufferData.remaining());
byteCount = min(byteCount, byteBufferData.remaining());
int originalLimit = byteBufferData.limit();
byteBufferData.limit(byteBufferData.position() + byteCount);
target.put(byteBufferData);
......@@ -126,7 +128,7 @@ import java.nio.ByteBuffer;
} else if (extractorInput != null) {
ExtractorInput extractorInput = this.extractorInput;
byte[] tempBuffer = Util.castNonNull(this.tempBuffer);
byteCount = Math.min(byteCount, TEMP_BUFFER_SIZE);
byteCount = min(byteCount, TEMP_BUFFER_SIZE);
int read = readFromExtractorInput(extractorInput, tempBuffer, /* offset= */ 0, byteCount);
if (read < 4) {
// Reading less than 4 bytes, most of the time, happens because of getting the bytes left in
......
......@@ -15,6 +15,8 @@
*/
package com.google.android.exoplayer2.ext.mediasession;
import static java.lang.Math.min;
import android.os.Bundle;
import android.os.ResultReceiver;
import android.support.v4.media.MediaDescriptionCompat;
......@@ -177,7 +179,7 @@ public abstract class TimelineQueueNavigator implements MediaSessionConnector.Qu
return;
}
ArrayDeque<MediaSessionCompat.QueueItem> queue = new ArrayDeque<>();
int queueSize = Math.min(maxQueueSize, timeline.getWindowCount());
int queueSize = min(maxQueueSize, timeline.getWindowCount());
// Add the active queue item.
int currentWindowIndex = player.getCurrentWindowIndex();
......
......@@ -16,6 +16,7 @@
package com.google.android.exoplayer2.ext.okhttp;
import static com.google.android.exoplayer2.util.Util.castNonNull;
import static java.lang.Math.min;
import android.net.Uri;
import androidx.annotation.Nullable;
......@@ -395,7 +396,7 @@ public class OkHttpDataSource extends BaseDataSource implements HttpDataSource {
}
while (bytesSkipped != bytesToSkip) {
int readLength = (int) Math.min(bytesToSkip - bytesSkipped, SKIP_BUFFER.length);
int readLength = (int) min(bytesToSkip - bytesSkipped, SKIP_BUFFER.length);
int read = castNonNull(responseByteStream).read(SKIP_BUFFER, 0, readLength);
if (Thread.currentThread().isInterrupted()) {
throw new InterruptedIOException();
......@@ -431,7 +432,7 @@ public class OkHttpDataSource extends BaseDataSource implements HttpDataSource {
if (bytesRemaining == 0) {
return C.RESULT_END_OF_INPUT;
}
readLength = (int) Math.min(readLength, bytesRemaining);
readLength = (int) min(readLength, bytesRemaining);
}
int read = castNonNull(responseByteStream).read(buffer, offset, readLength);
......
......@@ -15,6 +15,8 @@
*/
package com.google.android.exoplayer2.util;
import static java.lang.Math.min;
import com.google.common.base.Charsets;
import java.nio.charset.Charset;
......@@ -319,7 +321,7 @@ public final class ParsableBitArray {
if (numBits < 32) {
value &= (1 << numBits) - 1;
}
int firstByteReadSize = Math.min(8 - bitOffset, numBits);
int firstByteReadSize = min(8 - bitOffset, numBits);
int firstByteRightPaddingSize = 8 - bitOffset - firstByteReadSize;
int firstByteBitmask = (0xFF00 >> bitOffset) | ((1 << firstByteRightPaddingSize) - 1);
data[byteOffset] = (byte) (data[byteOffset] & firstByteBitmask);
......
......@@ -17,6 +17,8 @@ package com.google.android.exoplayer2.util;
import static android.content.Context.UI_MODE_SERVICE;
import static com.google.android.exoplayer2.util.Assertions.checkNotNull;
import static java.lang.Math.max;
import static java.lang.Math.min;
import android.Manifest.permission;
import android.annotation.SuppressLint;
......@@ -721,7 +723,7 @@ public final class Util {
* @return The constrained value {@code Math.max(min, Math.min(value, max))}.
*/
public static int constrainValue(int value, int min, int max) {
return Math.max(min, Math.min(value, max));
return max(min, min(value, max));
}
/**
......@@ -733,7 +735,7 @@ public final class Util {
* @return The constrained value {@code Math.max(min, Math.min(value, max))}.
*/
public static long constrainValue(long value, long min, long max) {
return Math.max(min, Math.min(value, max));
return max(min, min(value, max));
}
/**
......@@ -745,7 +747,7 @@ public final class Util {
* @return The constrained value {@code Math.max(min, Math.min(value, max))}.
*/
public static float constrainValue(float value, float min, float max) {
return Math.max(min, Math.min(value, max));
return max(min, min(value, max));
}
/**
......@@ -847,7 +849,7 @@ public final class Util {
index++;
}
}
return stayInBounds ? Math.max(0, index) : index;
return stayInBounds ? max(0, index) : index;
}
/**
......@@ -879,7 +881,7 @@ public final class Util {
index++;
}
}
return stayInBounds ? Math.max(0, index) : index;
return stayInBounds ? max(0, index) : index;
}
/**
......@@ -915,7 +917,7 @@ public final class Util {
index++;
}
}
return stayInBounds ? Math.max(0, index) : index;
return stayInBounds ? max(0, index) : index;
}
/**
......@@ -989,7 +991,7 @@ public final class Util {
index--;
}
}
return stayInBounds ? Math.min(array.length - 1, index) : index;
return stayInBounds ? min(array.length - 1, index) : index;
}
/**
......@@ -1022,7 +1024,7 @@ public final class Util {
index--;
}
}
return stayInBounds ? Math.min(array.length - 1, index) : index;
return stayInBounds ? min(array.length - 1, index) : index;
}
/**
......@@ -1060,7 +1062,7 @@ public final class Util {
index--;
}
}
return stayInBounds ? Math.min(list.size() - 1, index) : index;
return stayInBounds ? min(list.size() - 1, index) : index;
}
/**
......@@ -2226,7 +2228,7 @@ public final class Util {
for (int i = removedItemsLength - 1; i >= 0; i--) {
removedItems.addFirst(items.remove(fromIndex + i));
}
items.addAll(Math.min(newFromIndex, items.size()), removedItems);
items.addAll(min(newFromIndex, items.size()), removedItems);
}
/** Returns whether the table exists in the database. */
......
......@@ -15,6 +15,8 @@
*/
package com.google.android.exoplayer2;
import static java.lang.Math.max;
import androidx.annotation.Nullable;
import com.google.android.exoplayer2.decoder.DecoderInputBuffer;
import com.google.android.exoplayer2.source.SampleStream;
......@@ -383,7 +385,7 @@ public abstract class BaseRenderer implements Renderer, RendererCapabilities {
return streamIsFinal ? C.RESULT_BUFFER_READ : C.RESULT_NOTHING_READ;
}
buffer.timeUs += streamOffsetUs;
readingPositionUs = Math.max(readingPositionUs, buffer.timeUs);
readingPositionUs = max(readingPositionUs, buffer.timeUs);
} else if (result == C.RESULT_FORMAT_READ) {
Format format = Assertions.checkNotNull(formatHolder.format);
if (format.subsampleOffsetUs != Format.OFFSET_SAMPLE_RELATIVE) {
......
......@@ -15,6 +15,9 @@
*/
package com.google.android.exoplayer2;
import static java.lang.Math.max;
import static java.lang.Math.min;
/** Default {@link ControlDispatcher}. */
public class DefaultControlDispatcher implements ControlDispatcher {
......@@ -174,9 +177,9 @@ public class DefaultControlDispatcher implements ControlDispatcher {
long positionMs = player.getCurrentPosition() + offsetMs;
long durationMs = player.getDuration();
if (durationMs != C.TIME_UNSET) {
positionMs = Math.min(positionMs, durationMs);
positionMs = min(positionMs, durationMs);
}
positionMs = Math.max(positionMs, 0);
positionMs = max(positionMs, 0);
player.seekTo(player.getCurrentWindowIndex(), positionMs);
}
}
......@@ -15,6 +15,9 @@
*/
package com.google.android.exoplayer2;
import static java.lang.Math.max;
import static java.lang.Math.min;
import androidx.annotation.Nullable;
import com.google.android.exoplayer2.source.TrackGroupArray;
import com.google.android.exoplayer2.trackselection.TrackSelectionArray;
......@@ -386,10 +389,10 @@ public class DefaultLoadControl implements LoadControl {
// duration to keep enough media buffered for a playout duration of minBufferUs.
long mediaDurationMinBufferUs =
Util.getMediaDurationForPlayoutDuration(minBufferUs, playbackSpeed);
minBufferUs = Math.min(mediaDurationMinBufferUs, maxBufferUs);
minBufferUs = min(mediaDurationMinBufferUs, maxBufferUs);
}
// Prevent playback from getting stuck if minBufferUs is too small.
minBufferUs = Math.max(minBufferUs, 500_000);
minBufferUs = max(minBufferUs, 500_000);
if (bufferedDurationUs < minBufferUs) {
isBuffering = prioritizeTimeOverSizeThresholds || !targetBufferSizeReached;
if (!isBuffering && bufferedDurationUs < 500_000) {
......@@ -430,7 +433,7 @@ public class DefaultLoadControl implements LoadControl {
targetBufferSize += getDefaultBufferSize(renderers[i].getTrackType());
}
}
return Math.max(DEFAULT_MIN_BUFFER_SIZE, targetBufferSize);
return max(DEFAULT_MIN_BUFFER_SIZE, targetBufferSize);
}
private void reset(boolean resetAllocator) {
......
......@@ -18,6 +18,8 @@ package com.google.android.exoplayer2;
import static com.google.android.exoplayer2.util.Assertions.checkNotNull;
import static com.google.android.exoplayer2.util.Assertions.checkState;
import static com.google.android.exoplayer2.util.Util.castNonNull;
import static java.lang.Math.max;
import static java.lang.Math.min;
import android.annotation.SuppressLint;
import android.os.Handler;
......@@ -457,8 +459,7 @@ import java.util.concurrent.TimeoutException;
&& newFromIndex >= 0);
Timeline oldTimeline = getCurrentTimeline();
pendingOperationAcks++;
newFromIndex =
Math.min(newFromIndex, mediaSourceHolderSnapshots.size() - (toIndex - fromIndex));
newFromIndex = min(newFromIndex, mediaSourceHolderSnapshots.size() - (toIndex - fromIndex));
Util.moveItems(mediaSourceHolderSnapshots, fromIndex, toIndex, newFromIndex);
Timeline newTimeline = createMaskingTimeline();
PlaybackInfo newPlaybackInfo =
......@@ -1240,7 +1241,7 @@ import java.util.concurrent.TimeoutException;
checkState(!newPeriodId.isAd());
// A forward seek within the playing period (timeline did not change).
long maskedTotalBufferedDurationUs =
Math.max(
max(
0,
playbackInfo.totalBufferedDurationUs - (newContentPositionUs - oldContentPositionUs));
long maskedBufferedPositionUs = playbackInfo.bufferedPositionUs;
......
......@@ -15,6 +15,9 @@
*/
package com.google.android.exoplayer2;
import static java.lang.Math.max;
import static java.lang.Math.min;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
......@@ -1122,7 +1125,7 @@ import java.util.concurrent.atomic.AtomicBoolean;
if (newPlayingPeriodHolder.info.durationUs != C.TIME_UNSET
&& periodPositionUs >= newPlayingPeriodHolder.info.durationUs) {
// Make sure seek position doesn't exceed period duration.
periodPositionUs = Math.max(0, newPlayingPeriodHolder.info.durationUs - 1);
periodPositionUs = max(0, newPlayingPeriodHolder.info.durationUs - 1);
}
if (newPlayingPeriodHolder.hasEnabledTracks) {
periodPositionUs = newPlayingPeriodHolder.mediaPeriod.seekToUs(periodPositionUs);
......@@ -1415,7 +1418,7 @@ import java.util.concurrent.atomic.AtomicBoolean;
// Correct next index if necessary (e.g. after seeking, timeline changes, or new messages)
int currentPeriodIndex =
playbackInfo.timeline.getIndexOfPeriod(playbackInfo.periodId.periodUid);
int nextPendingMessageIndex = Math.min(nextPendingMessageIndexHint, pendingMessages.size());
int nextPendingMessageIndex = min(nextPendingMessageIndexHint, pendingMessages.size());
PendingMessageInfo previousInfo =
nextPendingMessageIndex > 0 ? pendingMessages.get(nextPendingMessageIndex - 1) : null;
while (previousInfo != null
......@@ -1543,8 +1546,7 @@ import java.util.concurrent.atomic.AtomicBoolean;
queue.removeAfter(periodHolder);
if (periodHolder.prepared) {
long loadingPeriodPositionUs =
Math.max(
periodHolder.info.startPositionUs, periodHolder.toPeriodTime(rendererPositionUs));
max(periodHolder.info.startPositionUs, periodHolder.toPeriodTime(rendererPositionUs));
periodHolder.applyTrackSelection(newTrackSelectorResult, loadingPeriodPositionUs, false);
}
}
......@@ -1696,7 +1698,7 @@ import java.util.concurrent.atomic.AtomicBoolean;
if (readingPositionUs == C.TIME_END_OF_SOURCE) {
return C.TIME_END_OF_SOURCE;
} else {
maxReadPositionUs = Math.max(readingPositionUs, maxReadPositionUs);
maxReadPositionUs = max(readingPositionUs, maxReadPositionUs);
}
}
return maxReadPositionUs;
......@@ -2162,7 +2164,7 @@ import java.util.concurrent.atomic.AtomicBoolean;
}
long totalBufferedDurationUs =
bufferedPositionInLoadingPeriodUs - loadingPeriodHolder.toPeriodTime(rendererPositionUs);
return Math.max(0, totalBufferedDurationUs);
return max(0, totalBufferedDurationUs);
}
private void updateLoadControlTrackSelection(
......
......@@ -15,6 +15,8 @@
*/
package com.google.android.exoplayer2;
import static java.lang.Math.max;
import androidx.annotation.Nullable;
import com.google.android.exoplayer2.source.ClippingMediaPeriod;
import com.google.android.exoplayer2.source.EmptySampleStream;
......@@ -182,7 +184,7 @@ import org.checkerframework.checker.nullness.compatqual.NullableType;
long requestedStartPositionUs = info.startPositionUs;
if (info.durationUs != C.TIME_UNSET && requestedStartPositionUs >= info.durationUs) {
// Make sure start position doesn't exceed period duration.
requestedStartPositionUs = Math.max(0, info.durationUs - 1);
requestedStartPositionUs = max(0, info.durationUs - 1);
}
long newStartPositionUs =
applyTrackSelection(
......
......@@ -15,6 +15,8 @@
*/
package com.google.android.exoplayer2;
import static java.lang.Math.max;
import android.os.Handler;
import android.util.Pair;
import androidx.annotation.Nullable;
......@@ -635,7 +637,7 @@ import com.google.common.collect.ImmutableList;
period,
nextWindowIndex,
/* windowPositionUs= */ C.TIME_UNSET,
/* defaultPositionProjectionUs= */ Math.max(0, bufferedDurationUs));
/* defaultPositionProjectionUs= */ max(0, bufferedDurationUs));
if (defaultPosition == null) {
return null;
}
......@@ -692,7 +694,7 @@ import com.google.common.collect.ImmutableList;
period,
period.windowIndex,
/* windowPositionUs= */ C.TIME_UNSET,
/* defaultPositionProjectionUs= */ Math.max(0, bufferedDurationUs));
/* defaultPositionProjectionUs= */ max(0, bufferedDurationUs));
if (defaultPosition == null) {
return null;
}
......@@ -774,7 +776,7 @@ import com.google.common.collect.ImmutableList;
: 0;
if (durationUs != C.TIME_UNSET && startPositionUs >= durationUs) {
// Ensure start position doesn't exceed duration.
startPositionUs = Math.max(0, durationUs - 1);
startPositionUs = max(0, durationUs - 1);
}
return new MediaPeriodInfo(
id,
......@@ -809,7 +811,7 @@ import com.google.common.collect.ImmutableList;
: endPositionUs;
if (durationUs != C.TIME_UNSET && startPositionUs >= durationUs) {
// Ensure start position doesn't exceed duration.
startPositionUs = Math.max(0, durationUs - 1);
startPositionUs = max(0, durationUs - 1);
}
return new MediaPeriodInfo(
id,
......
......@@ -15,6 +15,9 @@
*/
package com.google.android.exoplayer2;
import static java.lang.Math.max;
import static java.lang.Math.min;
import android.os.Handler;
import androidx.annotation.Nullable;
import com.google.android.exoplayer2.analytics.AnalyticsCollector;
......@@ -228,9 +231,9 @@ import java.util.Set;
if (fromIndex == toIndex || fromIndex == newFromIndex) {
return createTimeline();
}
int startIndex = Math.min(fromIndex, newFromIndex);
int startIndex = min(fromIndex, newFromIndex);
int newEndIndex = newFromIndex + (toIndex - fromIndex) - 1;
int endIndex = Math.max(newEndIndex, toIndex - 1);
int endIndex = max(newEndIndex, toIndex - 1);
int windowOffset = mediaSourceHolders.get(startIndex).firstWindowIndexInChild;
Util.moveItems(mediaSourceHolders, fromIndex, toIndex, newFromIndex);
for (int i = startIndex; i <= endIndex; i++) {
......
......@@ -15,6 +15,9 @@
*/
package com.google.android.exoplayer2.analytics;
import static java.lang.Math.max;
import static java.lang.Math.min;
import android.os.SystemClock;
import androidx.annotation.IntDef;
import androidx.annotation.Nullable;
......@@ -276,7 +279,7 @@ public final class PlaybackStats {
if (firstReportedTimeMs == C.TIME_UNSET) {
firstReportedTimeMs = stats.firstReportedTimeMs;
} else if (stats.firstReportedTimeMs != C.TIME_UNSET) {
firstReportedTimeMs = Math.min(firstReportedTimeMs, stats.firstReportedTimeMs);
firstReportedTimeMs = min(firstReportedTimeMs, stats.firstReportedTimeMs);
}
foregroundPlaybackCount += stats.foregroundPlaybackCount;
abandonedBeforeReadyCount += stats.abandonedBeforeReadyCount;
......@@ -295,7 +298,7 @@ public final class PlaybackStats {
if (maxRebufferTimeMs == C.TIME_UNSET) {
maxRebufferTimeMs = stats.maxRebufferTimeMs;
} else if (stats.maxRebufferTimeMs != C.TIME_UNSET) {
maxRebufferTimeMs = Math.max(maxRebufferTimeMs, stats.maxRebufferTimeMs);
maxRebufferTimeMs = max(maxRebufferTimeMs, stats.maxRebufferTimeMs);
}
adPlaybackCount += stats.adPlaybackCount;
totalVideoFormatHeightTimeMs += stats.totalVideoFormatHeightTimeMs;
......
......@@ -15,6 +15,8 @@
*/
package com.google.android.exoplayer2.analytics;
import static java.lang.Math.max;
import android.os.SystemClock;
import androidx.annotation.Nullable;
import com.google.android.exoplayer2.C;
......@@ -792,7 +794,7 @@ public final class PlaybackStatsListener
long buildTimeMs = SystemClock.elapsedRealtime();
playbackStateDurationsMs =
Arrays.copyOf(this.playbackStateDurationsMs, PlaybackStats.PLAYBACK_STATE_COUNT);
long lastStateDurationMs = Math.max(0, buildTimeMs - currentPlaybackStateStartTimeMs);
long lastStateDurationMs = max(0, buildTimeMs - currentPlaybackStateStartTimeMs);
playbackStateDurationsMs[currentPlaybackState] += lastStateDurationMs;
maybeUpdateMaxRebufferTimeMs(buildTimeMs);
maybeRecordVideoFormatTime(buildTimeMs);
......
......@@ -16,6 +16,8 @@
package com.google.android.exoplayer2.audio;
import static com.google.android.exoplayer2.util.Util.castNonNull;
import static java.lang.Math.max;
import static java.lang.Math.min;
import android.media.AudioTimestamp;
import android.media.AudioTrack;
......@@ -251,7 +253,7 @@ import java.lang.reflect.Method;
positionUs = systemTimeUs + smoothedPlayheadOffsetUs;
}
if (!sourceEnded) {
positionUs = Math.max(0, positionUs - latencyUs);
positionUs = max(0, positionUs - latencyUs);
}
}
......@@ -472,7 +474,7 @@ import java.lang.reflect.Method;
* 1000L
- bufferSizeUs;
// Check that the latency is non-negative.
latencyUs = Math.max(latencyUs, 0);
latencyUs = max(latencyUs, 0);
// Check that the latency isn't too large.
if (latencyUs > MAX_LATENCY_US) {
listener.onInvalidLatency(latencyUs);
......@@ -537,7 +539,7 @@ import java.lang.reflect.Method;
// Simulate the playback head position up to the total number of frames submitted.
long elapsedTimeSinceStopUs = (SystemClock.elapsedRealtime() * 1000) - stopTimestampUs;
long framesSinceStop = (elapsedTimeSinceStopUs * outputSampleRate) / C.MICROS_PER_SECOND;
return Math.min(endPlaybackHeadPosition, stopPlaybackHeadPosition + framesSinceStop);
return min(endPlaybackHeadPosition, stopPlaybackHeadPosition + framesSinceStop);
}
int state = audioTrack.getPlayState();
......
......@@ -15,6 +15,8 @@
*/
package com.google.android.exoplayer2.audio;
import static java.lang.Math.max;
import android.media.audiofx.Virtualizer;
import android.os.Handler;
import android.os.SystemClock;
......@@ -666,7 +668,7 @@ public abstract class DecoderAudioRenderer extends BaseRenderer implements Media
currentPositionUs =
allowPositionDiscontinuity
? newCurrentPositionUs
: Math.max(currentPositionUs, newCurrentPositionUs);
: max(currentPositionUs, newCurrentPositionUs);
allowPositionDiscontinuity = false;
}
}
......
......@@ -15,6 +15,9 @@
*/
package com.google.android.exoplayer2.audio;
import static java.lang.Math.max;
import static java.lang.Math.min;
import android.annotation.SuppressLint;
import android.media.AudioFormat;
import android.media.AudioManager;
......@@ -471,7 +474,7 @@ public final class DefaultAudioSink implements AudioSink {
return CURRENT_POSITION_NOT_SET;
}
long positionUs = audioTrackPositionTracker.getCurrentPositionUs(sourceEnded);
positionUs = Math.min(positionUs, configuration.framesToDurationUs(getWrittenFrames()));
positionUs = min(positionUs, configuration.framesToDurationUs(getWrittenFrames()));
return applySkipping(applyMediaPositionParameters(positionUs));
}
......@@ -644,7 +647,7 @@ public final class DefaultAudioSink implements AudioSink {
}
}
startMediaTimeUs = Math.max(0, presentationTimeUs);
startMediaTimeUs = max(0, presentationTimeUs);
startMediaTimeUsNeedsSync = false;
applyPlaybackSpeedAndSkipSilence(presentationTimeUs);
......@@ -876,7 +879,7 @@ public final class DefaultAudioSink implements AudioSink {
// Work out how many bytes we can write without the risk of blocking.
int bytesToWrite = audioTrackPositionTracker.getAvailableBufferSize(writtenPcmBytes);
if (bytesToWrite > 0) {
bytesToWrite = Math.min(bytesRemaining, bytesToWrite);
bytesToWrite = min(bytesRemaining, bytesToWrite);
bytesWritten = audioTrack.write(preV21OutputBuffer, preV21OutputBufferOffset, bytesToWrite);
if (bytesWritten > 0) {
preV21OutputBufferOffset += bytesWritten;
......@@ -1232,7 +1235,7 @@ public final class DefaultAudioSink implements AudioSink {
new MediaPositionParameters(
playbackSpeed,
skipSilenceEnabled,
/* mediaTimeUs= */ Math.max(0, presentationTimeUs),
/* mediaTimeUs= */ max(0, presentationTimeUs),
/* audioTrackPositionUs= */ configuration.framesToDurationUs(getWrittenFrames())));
setupAudioProcessors();
if (listener != null) {
......@@ -1871,8 +1874,7 @@ public final class DefaultAudioSink implements AudioSink {
int multipliedBufferSize = minBufferSize * BUFFER_MULTIPLICATION_FACTOR;
int minAppBufferSize = (int) durationUsToFrames(MIN_BUFFER_DURATION_US) * outputPcmFrameSize;
int maxAppBufferSize =
Math.max(
minBufferSize, (int) durationUsToFrames(MAX_BUFFER_DURATION_US) * outputPcmFrameSize);
max(minBufferSize, (int) durationUsToFrames(MAX_BUFFER_DURATION_US) * outputPcmFrameSize);
return Util.constrainValue(multipliedBufferSize, minAppBufferSize, maxAppBufferSize);
}
......
......@@ -16,6 +16,7 @@
package com.google.android.exoplayer2.audio;
import static com.google.android.exoplayer2.util.Assertions.checkNotNull;
import static java.lang.Math.max;
import android.annotation.SuppressLint;
import android.content.Context;
......@@ -363,7 +364,7 @@ public class MediaCodecAudioRenderer extends MediaCodecRenderer implements Media
for (Format streamFormat : streamFormats) {
int streamSampleRate = streamFormat.sampleRate;
if (streamSampleRate != Format.NO_VALUE) {
maxSampleRate = Math.max(maxSampleRate, streamSampleRate);
maxSampleRate = max(maxSampleRate, streamSampleRate);
}
}
return maxSampleRate == -1 ? CODEC_OPERATING_RATE_UNSET : (maxSampleRate * operatingRate);
......@@ -674,7 +675,7 @@ public class MediaCodecAudioRenderer extends MediaCodecRenderer implements Media
for (Format streamFormat : streamFormats) {
if (codecInfo.isSeamlessAdaptationSupported(
format, streamFormat, /* isNewFormatComplete= */ false)) {
maxInputSize = Math.max(maxInputSize, getCodecMaxInputSize(codecInfo, streamFormat));
maxInputSize = max(maxInputSize, getCodecMaxInputSize(codecInfo, streamFormat));
}
}
return maxInputSize;
......@@ -750,7 +751,7 @@ public class MediaCodecAudioRenderer extends MediaCodecRenderer implements Media
currentPositionUs =
allowPositionDiscontinuity
? newCurrentPositionUs
: Math.max(currentPositionUs, newCurrentPositionUs);
: max(currentPositionUs, newCurrentPositionUs);
allowPositionDiscontinuity = false;
}
}
......
......@@ -15,6 +15,8 @@
*/
package com.google.android.exoplayer2.audio;
import static java.lang.Math.min;
import androidx.annotation.IntDef;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.util.Assertions;
......@@ -218,7 +220,7 @@ public final class SilenceSkippingAudioProcessor extends BaseAudioProcessor {
int limit = inputBuffer.limit();
// Check if there's any noise within the maybe silence buffer duration.
inputBuffer.limit(Math.min(limit, inputBuffer.position() + maybeSilenceBuffer.length));
inputBuffer.limit(min(limit, inputBuffer.position() + maybeSilenceBuffer.length));
int noiseLimit = findNoiseLimit(inputBuffer);
if (noiseLimit == inputBuffer.position()) {
// The buffer contains the start of possible silence.
......@@ -248,7 +250,7 @@ public final class SilenceSkippingAudioProcessor extends BaseAudioProcessor {
state = STATE_NOISY;
} else {
// Fill as much of the maybe silence buffer as possible.
int bytesToWrite = Math.min(maybeSilenceInputSize, maybeSilenceBufferRemaining);
int bytesToWrite = min(maybeSilenceInputSize, maybeSilenceBufferRemaining);
inputBuffer.limit(inputBuffer.position() + bytesToWrite);
inputBuffer.get(maybeSilenceBuffer, maybeSilenceBufferSize, bytesToWrite);
maybeSilenceBufferSize += bytesToWrite;
......@@ -320,7 +322,7 @@ public final class SilenceSkippingAudioProcessor extends BaseAudioProcessor {
* position.
*/
private void updatePaddingBuffer(ByteBuffer input, byte[] buffer, int size) {
int fromInputSize = Math.min(input.remaining(), paddingSize);
int fromInputSize = min(input.remaining(), paddingSize);
int fromBufferSize = paddingSize - fromInputSize;
System.arraycopy(
/* src= */ buffer,
......
......@@ -16,6 +16,8 @@
*/
package com.google.android.exoplayer2.audio;
import static java.lang.Math.min;
import com.google.android.exoplayer2.util.Assertions;
import java.nio.ShortBuffer;
import java.util.Arrays;
......@@ -99,7 +101,7 @@ import java.util.Arrays;
* @param buffer A {@link ShortBuffer} into which output will be written.
*/
public void getOutput(ShortBuffer buffer) {
int framesToRead = Math.min(buffer.remaining() / channelCount, outputFrameCount);
int framesToRead = min(buffer.remaining() / channelCount, outputFrameCount);
buffer.put(outputBuffer, 0, framesToRead * channelCount);
outputFrameCount -= framesToRead;
System.arraycopy(
......@@ -199,7 +201,7 @@ import java.util.Arrays;
}
private int copyInputToOutput(int positionFrames) {
int frameCount = Math.min(maxRequiredFrameCount, remainingInputToCopyFrameCount);
int frameCount = min(maxRequiredFrameCount, remainingInputToCopyFrameCount);
copyToOutput(inputBuffer, positionFrames, frameCount);
remainingInputToCopyFrameCount -= frameCount;
return frameCount;
......
......@@ -15,6 +15,8 @@
*/
package com.google.android.exoplayer2.audio;
import static java.lang.Math.min;
import androidx.annotation.Nullable;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.util.Assertions;
......@@ -198,7 +200,7 @@ public final class TeeAudioProcessor extends BaseAudioProcessor {
private void writeBuffer(ByteBuffer buffer) throws IOException {
RandomAccessFile randomAccessFile = Assertions.checkNotNull(this.randomAccessFile);
while (buffer.hasRemaining()) {
int bytesToWrite = Math.min(buffer.remaining(), scratchBuffer.length);
int bytesToWrite = min(buffer.remaining(), scratchBuffer.length);
buffer.get(scratchBuffer, 0, bytesToWrite);
randomAccessFile.write(scratchBuffer, 0, bytesToWrite);
bytesWritten += bytesToWrite;
......
......@@ -15,6 +15,8 @@
*/
package com.google.android.exoplayer2.audio;
import static java.lang.Math.min;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.util.Util;
import java.nio.ByteBuffer;
......@@ -86,7 +88,7 @@ import java.nio.ByteBuffer;
}
// Trim any pending start bytes from the input buffer.
int trimBytes = Math.min(remaining, pendingTrimStartBytes);
int trimBytes = min(remaining, pendingTrimStartBytes);
trimmedFrameCount += trimBytes / inputAudioFormat.bytesPerFrame;
pendingTrimStartBytes -= trimBytes;
inputBuffer.position(position + trimBytes);
......
......@@ -15,12 +15,14 @@
*/
package com.google.android.exoplayer2.decoder;
import static java.lang.Math.max;
/**
* Maintains decoder event counts, for debugging purposes only.
* <p>
* Counters should be written from the playback thread only. Counters may be read from any thread.
* To ensure that the counter values are made visible across threads, users of this class should
* invoke {@link #ensureUpdated()} prior to reading and after writing.
*
* <p>Counters should be written from the playback thread only. Counters may be read from any
* thread. To ensure that the counter values are made visible across threads, users of this class
* should invoke {@link #ensureUpdated()} prior to reading and after writing.
*/
public final class DecoderCounters {
......@@ -117,8 +119,8 @@ public final class DecoderCounters {
renderedOutputBufferCount += other.renderedOutputBufferCount;
skippedOutputBufferCount += other.skippedOutputBufferCount;
droppedBufferCount += other.droppedBufferCount;
maxConsecutiveDroppedBufferCount = Math.max(maxConsecutiveDroppedBufferCount,
other.maxConsecutiveDroppedBufferCount);
maxConsecutiveDroppedBufferCount =
max(maxConsecutiveDroppedBufferCount, other.maxConsecutiveDroppedBufferCount);
droppedToKeyframeCount += other.droppedToKeyframeCount;
addVideoFrameProcessingOffsets(
other.totalVideoFrameProcessingOffsetUs, other.videoFrameProcessingOffsetCount);
......
......@@ -16,6 +16,7 @@
package com.google.android.exoplayer2.drm;
import static com.google.android.exoplayer2.util.Assertions.checkState;
import static java.lang.Math.min;
import android.annotation.SuppressLint;
import android.media.NotProvisionedException;
......@@ -451,7 +452,7 @@ import org.checkerframework.checker.nullness.qual.RequiresNonNull;
}
Pair<Long, Long> pair =
Assertions.checkNotNull(WidevineUtil.getLicenseDurationRemainingSec(this));
return Math.min(pair.first, pair.second);
return min(pair.first, pair.second);
}
private void postKeyRequest(byte[] scope, int type, boolean allowRetry) {
......
......@@ -16,6 +16,7 @@
package com.google.android.exoplayer2.mediacodec;
import static com.google.android.exoplayer2.util.Assertions.checkState;
import static java.lang.Math.max;
import android.annotation.TargetApi;
import android.media.MediaCodec;
......@@ -1354,10 +1355,9 @@ public abstract class MediaCodecRenderer extends BaseRenderer {
// TODO(b/158483277): Find the root cause of why a gap is introduced in MP3 playback when using
// presentationTimeUs from the c2Mp3TimestampTracker.
if (c2Mp3TimestampTracker != null) {
largestQueuedPresentationTimeUs = Math.max(largestQueuedPresentationTimeUs, buffer.timeUs);
largestQueuedPresentationTimeUs = max(largestQueuedPresentationTimeUs, buffer.timeUs);
} else {
largestQueuedPresentationTimeUs =
Math.max(largestQueuedPresentationTimeUs, presentationTimeUs);
largestQueuedPresentationTimeUs = max(largestQueuedPresentationTimeUs, presentationTimeUs);
}
buffer.flip();
if (buffer.hasSupplementalData()) {
......
......@@ -15,6 +15,8 @@
*/
package com.google.android.exoplayer2.mediacodec;
import static java.lang.Math.max;
import android.annotation.SuppressLint;
import android.media.MediaCodecInfo.CodecCapabilities;
import android.media.MediaCodecInfo.CodecProfileLevel;
......@@ -206,11 +208,11 @@ public final class MediaCodecUtil {
getDecoderInfo(MimeTypes.VIDEO_H264, /* secure= */ false, /* tunneling= */ false);
if (decoderInfo != null) {
for (CodecProfileLevel profileLevel : decoderInfo.getProfileLevels()) {
result = Math.max(avcLevelToMaxFrameSize(profileLevel.level), result);
result = max(avcLevelToMaxFrameSize(profileLevel.level), result);
}
// We assume support for at least 480p (SDK_INT >= 21) or 360p (SDK_INT < 21), which are
// the levels mandated by the Android CDD.
result = Math.max(result, Util.SDK_INT >= 21 ? (720 * 480) : (480 * 360));
result = max(result, Util.SDK_INT >= 21 ? (720 * 480) : (480 * 360));
}
maxH264DecodableFrameSize = result;
}
......
......@@ -25,6 +25,7 @@ import static com.google.android.exoplayer2.offline.Download.STATE_REMOVING;
import static com.google.android.exoplayer2.offline.Download.STATE_RESTARTING;
import static com.google.android.exoplayer2.offline.Download.STATE_STOPPED;
import static com.google.android.exoplayer2.offline.Download.STOP_REASON_NONE;
import static java.lang.Math.min;
import android.content.Context;
import android.os.Handler;
......@@ -1389,7 +1390,7 @@ public final class DownloadManager {
}
private static int getRetryDelayMillis(int errorCount) {
return Math.min((errorCount - 1) * 1000, 5000);
return min((errorCount - 1) * 1000, 5000);
}
}
......
......@@ -15,6 +15,9 @@
*/
package com.google.android.exoplayer2.source;
import static java.lang.Math.max;
import static java.lang.Math.min;
import androidx.annotation.IntDef;
import androidx.annotation.Nullable;
import com.google.android.exoplayer2.C;
......@@ -296,9 +299,9 @@ public final class ClippingMediaSource extends CompositeMediaSource<Void> {
return C.TIME_UNSET;
}
long startMs = C.usToMs(startUs);
long clippedTimeMs = Math.max(0, mediaTimeMs - startMs);
long clippedTimeMs = max(0, mediaTimeMs - startMs);
if (endUs != C.TIME_END_OF_SOURCE) {
clippedTimeMs = Math.min(C.usToMs(endUs) - startMs, clippedTimeMs);
clippedTimeMs = min(C.usToMs(endUs) - startMs, clippedTimeMs);
}
return clippedTimeMs;
}
......@@ -329,11 +332,11 @@ public final class ClippingMediaSource extends CompositeMediaSource<Void> {
throw new IllegalClippingException(IllegalClippingException.REASON_INVALID_PERIOD_COUNT);
}
Window window = timeline.getWindow(0, new Window());
startUs = Math.max(0, startUs);
startUs = max(0, startUs);
if (!window.isPlaceholder && startUs != 0 && !window.isSeekable) {
throw new IllegalClippingException(IllegalClippingException.REASON_NOT_SEEKABLE_TO_START);
}
long resolvedEndUs = endUs == C.TIME_END_OF_SOURCE ? window.durationUs : Math.max(0, endUs);
long resolvedEndUs = endUs == C.TIME_END_OF_SOURCE ? window.durationUs : max(0, endUs);
if (window.durationUs != C.TIME_UNSET) {
if (resolvedEndUs > window.durationUs) {
resolvedEndUs = window.durationUs;
......@@ -358,9 +361,9 @@ public final class ClippingMediaSource extends CompositeMediaSource<Void> {
window.durationUs = durationUs;
window.isDynamic = isDynamic;
if (window.defaultPositionUs != C.TIME_UNSET) {
window.defaultPositionUs = Math.max(window.defaultPositionUs, startUs);
window.defaultPositionUs = endUs == C.TIME_UNSET ? window.defaultPositionUs
: Math.min(window.defaultPositionUs, endUs);
window.defaultPositionUs = max(window.defaultPositionUs, startUs);
window.defaultPositionUs =
endUs == C.TIME_UNSET ? window.defaultPositionUs : min(window.defaultPositionUs, endUs);
window.defaultPositionUs -= startUs;
}
long startMs = C.usToMs(startUs);
......
......@@ -15,6 +15,8 @@
*/
package com.google.android.exoplayer2.source;
import static java.lang.Math.min;
import com.google.android.exoplayer2.C;
/**
......@@ -34,7 +36,7 @@ public class CompositeSequenceableLoader implements SequenceableLoader {
for (SequenceableLoader loader : loaders) {
long loaderBufferedPositionUs = loader.getBufferedPositionUs();
if (loaderBufferedPositionUs != C.TIME_END_OF_SOURCE) {
bufferedPositionUs = Math.min(bufferedPositionUs, loaderBufferedPositionUs);
bufferedPositionUs = min(bufferedPositionUs, loaderBufferedPositionUs);
}
}
return bufferedPositionUs == Long.MAX_VALUE ? C.TIME_END_OF_SOURCE : bufferedPositionUs;
......@@ -46,7 +48,7 @@ public class CompositeSequenceableLoader implements SequenceableLoader {
for (SequenceableLoader loader : loaders) {
long loaderNextLoadPositionUs = loader.getNextLoadPositionUs();
if (loaderNextLoadPositionUs != C.TIME_END_OF_SOURCE) {
nextLoadPositionUs = Math.min(nextLoadPositionUs, loaderNextLoadPositionUs);
nextLoadPositionUs = min(nextLoadPositionUs, loaderNextLoadPositionUs);
}
}
return nextLoadPositionUs == Long.MAX_VALUE ? C.TIME_END_OF_SOURCE : nextLoadPositionUs;
......
......@@ -15,6 +15,9 @@
*/
package com.google.android.exoplayer2.source;
import static java.lang.Math.max;
import static java.lang.Math.min;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
......@@ -804,8 +807,8 @@ public final class ConcatenatingMediaSource extends CompositeMediaSource<MediaSo
}
private void moveMediaSourceInternal(int currentIndex, int newIndex) {
int startIndex = Math.min(currentIndex, newIndex);
int endIndex = Math.max(currentIndex, newIndex);
int startIndex = min(currentIndex, newIndex);
int endIndex = max(currentIndex, newIndex);
int windowOffset = mediaSourceHolders.get(startIndex).firstWindowIndexInChild;
mediaSourceHolders.add(newIndex, mediaSourceHolders.remove(currentIndex));
for (int i = startIndex; i <= endIndex; i++) {
......
......@@ -15,6 +15,8 @@
*/
package com.google.android.exoplayer2.source;
import static java.lang.Math.min;
import android.net.Uri;
import androidx.annotation.Nullable;
import com.google.android.exoplayer2.C;
......@@ -85,7 +87,7 @@ import java.util.Map;
return C.RESULT_END_OF_INPUT;
}
}
int bytesRead = upstream.read(buffer, offset, Math.min(bytesUntilMetadata, readLength));
int bytesRead = upstream.read(buffer, offset, min(bytesUntilMetadata, readLength));
if (bytesRead != C.RESULT_END_OF_INPUT) {
bytesUntilMetadata -= bytesRead;
}
......
......@@ -15,6 +15,8 @@
*/
package com.google.android.exoplayer2.source;
import static java.lang.Math.max;
import android.util.Pair;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
......@@ -244,7 +246,7 @@ public final class MaskingMediaSource extends CompositeMediaSource<Void> {
if (periodDurationUs != C.TIME_UNSET) {
// Ensure the overridden position doesn't exceed the period duration.
if (preparePositionOverrideUs >= periodDurationUs) {
preparePositionOverrideUs = Math.max(0, periodDurationUs - 1);
preparePositionOverrideUs = max(0, periodDurationUs - 1);
}
}
maskingPeriod.overridePreparePositionUs(preparePositionOverrideUs);
......
......@@ -15,6 +15,8 @@
*/
package com.google.android.exoplayer2.source;
import static java.lang.Math.max;
import androidx.annotation.Nullable;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.FormatHolder;
......@@ -442,7 +444,7 @@ import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
FormatHolder formatHolder, DecoderInputBuffer buffer, boolean formatRequired) {
int readResult = sampleStream.readData(formatHolder, buffer, formatRequired);
if (readResult == C.RESULT_BUFFER_READ) {
buffer.timeUs = Math.max(0, buffer.timeUs + timeOffsetUs);
buffer.timeUs = max(0, buffer.timeUs + timeOffsetUs);
}
return readResult;
}
......
......@@ -15,6 +15,9 @@
*/
package com.google.android.exoplayer2.source;
import static java.lang.Math.max;
import static java.lang.Math.min;
import android.net.Uri;
import android.os.Handler;
import androidx.annotation.Nullable;
......@@ -394,8 +397,8 @@ import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
int trackCount = sampleQueues.length;
for (int i = 0; i < trackCount; i++) {
if (trackIsAudioVideoFlags[i] && !sampleQueues[i].isLastSampleQueued()) {
largestQueuedTimestampUs = Math.min(largestQueuedTimestampUs,
sampleQueues[i].getLargestQueuedTimestampUs());
largestQueuedTimestampUs =
min(largestQueuedTimestampUs, sampleQueues[i].getLargestQueuedTimestampUs());
}
}
}
......@@ -909,8 +912,8 @@ import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
private long getLargestQueuedTimestampUs() {
long largestQueuedTimestampUs = Long.MIN_VALUE;
for (SampleQueue sampleQueue : sampleQueues) {
largestQueuedTimestampUs = Math.max(largestQueuedTimestampUs,
sampleQueue.getLargestQueuedTimestampUs());
largestQueuedTimestampUs =
max(largestQueuedTimestampUs, sampleQueue.getLargestQueuedTimestampUs());
}
return largestQueuedTimestampUs;
}
......@@ -1068,8 +1071,7 @@ import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
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);
long timeUs = !seenIcyMetadata ? seekTimeUs : max(getLargestQueuedTimestampUs(), seekTimeUs);
int length = metadata.bytesLeft();
TrackOutput icyTrackOutput = Assertions.checkNotNull(this.icyTrackOutput);
icyTrackOutput.sampleData(metadata, length);
......
......@@ -15,6 +15,8 @@
*/
package com.google.android.exoplayer2.source;
import static java.lang.Math.min;
import androidx.annotation.Nullable;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.decoder.CryptoInfo;
......@@ -304,7 +306,7 @@ import java.util.Arrays;
advanceReadTo(absolutePosition);
int remaining = length;
while (remaining > 0) {
int toCopy = Math.min(remaining, (int) (readAllocationNode.endPosition - absolutePosition));
int toCopy = min(remaining, (int) (readAllocationNode.endPosition - absolutePosition));
Allocation allocation = readAllocationNode.allocation;
target.put(allocation.data, readAllocationNode.translateOffset(absolutePosition), toCopy);
remaining -= toCopy;
......@@ -326,7 +328,7 @@ import java.util.Arrays;
advanceReadTo(absolutePosition);
int remaining = length;
while (remaining > 0) {
int toCopy = Math.min(remaining, (int) (readAllocationNode.endPosition - absolutePosition));
int toCopy = min(remaining, (int) (readAllocationNode.endPosition - absolutePosition));
Allocation allocation = readAllocationNode.allocation;
System.arraycopy(
allocation.data,
......@@ -392,7 +394,7 @@ import java.util.Arrays;
allocator.allocate(),
new AllocationNode(writeAllocationNode.endPosition, allocationLength));
}
return Math.min(length, (int) (writeAllocationNode.endPosition - totalBytesWritten));
return min(length, (int) (writeAllocationNode.endPosition - totalBytesWritten));
}
/**
......
......@@ -16,6 +16,7 @@
package com.google.android.exoplayer2.source;
import static com.google.android.exoplayer2.util.Assertions.checkArgument;
import static java.lang.Math.max;
import android.os.Looper;
import android.util.Log;
......@@ -713,7 +714,7 @@ public class SampleQueue implements TrackOutput {
int size,
@Nullable CryptoData cryptoData) {
isLastSampleQueued = (sampleFlags & C.BUFFER_FLAG_LAST_SAMPLE) != 0;
largestQueuedTimestampUs = Math.max(largestQueuedTimestampUs, timeUs);
largestQueuedTimestampUs = max(largestQueuedTimestampUs, timeUs);
int relativeEndIndex = getRelativeIndex(length);
timesUs[relativeEndIndex] = timeUs;
......@@ -776,7 +777,7 @@ public class SampleQueue implements TrackOutput {
return timeUs > largestDiscardedTimestampUs;
}
long largestReadTimestampUs =
Math.max(largestDiscardedTimestampUs, getLargestTimestamp(readPosition));
max(largestDiscardedTimestampUs, getLargestTimestamp(readPosition));
if (largestReadTimestampUs >= timeUs) {
return false;
}
......@@ -797,7 +798,7 @@ public class SampleQueue implements TrackOutput {
int discardCount = getWriteIndex() - discardFromIndex;
checkArgument(0 <= discardCount && discardCount <= (length - readPosition));
length -= discardCount;
largestQueuedTimestampUs = Math.max(largestDiscardedTimestampUs, getLargestTimestamp(length));
largestQueuedTimestampUs = max(largestDiscardedTimestampUs, getLargestTimestamp(length));
isLastSampleQueued = discardCount == 0 && isLastSampleQueued;
if (length != 0) {
int relativeLastWriteIndex = getRelativeIndex(length - 1);
......@@ -894,7 +895,7 @@ public class SampleQueue implements TrackOutput {
*/
private long discardSamples(int discardCount) {
largestDiscardedTimestampUs =
Math.max(largestDiscardedTimestampUs, getLargestTimestamp(discardCount));
max(largestDiscardedTimestampUs, getLargestTimestamp(discardCount));
length -= discardCount;
absoluteFirstIndex += discardCount;
relativeFirstIndex += discardCount;
......@@ -928,7 +929,7 @@ public class SampleQueue implements TrackOutput {
long largestTimestampUs = Long.MIN_VALUE;
int relativeSampleIndex = getRelativeIndex(length - 1);
for (int i = 0; i < length; i++) {
largestTimestampUs = Math.max(largestTimestampUs, timesUs[relativeSampleIndex]);
largestTimestampUs = max(largestTimestampUs, timesUs[relativeSampleIndex]);
if ((flags[relativeSampleIndex] & C.BUFFER_FLAG_KEY_FRAME) != 0) {
break;
}
......
......@@ -15,6 +15,8 @@
*/
package com.google.android.exoplayer2.source;
import static java.lang.Math.min;
import android.net.Uri;
import androidx.annotation.Nullable;
import com.google.android.exoplayer2.C;
......@@ -303,7 +305,7 @@ public final class SilenceMediaSource extends BaseMediaSource {
return C.RESULT_BUFFER_READ;
}
int bytesToWrite = (int) Math.min(SILENCE_SAMPLE.length, bytesRemaining);
int bytesToWrite = (int) min(SILENCE_SAMPLE.length, bytesRemaining);
buffer.ensureSpaceForWrite(bytesToWrite);
buffer.data.put(SILENCE_SAMPLE, /* offset= */ 0, bytesToWrite);
buffer.timeUs = getAudioPositionUs(positionBytes);
......
......@@ -15,6 +15,8 @@
*/
package com.google.android.exoplayer2.source.ads;
import static java.lang.Math.max;
import android.net.Uri;
import androidx.annotation.CheckResult;
import androidx.annotation.IntDef;
......@@ -213,7 +215,7 @@ public final class AdPlaybackState {
@CheckResult
private static @AdState int[] copyStatesWithSpaceForAdCount(@AdState int[] states, int count) {
int oldStateCount = states.length;
int newStateCount = Math.max(count, oldStateCount);
int newStateCount = max(count, oldStateCount);
states = Arrays.copyOf(states, newStateCount);
Arrays.fill(states, oldStateCount, newStateCount, AD_STATE_UNAVAILABLE);
return states;
......@@ -222,7 +224,7 @@ public final class AdPlaybackState {
@CheckResult
private static long[] copyDurationsUsWithSpaceForAdCount(long[] durationsUs, int count) {
int oldDurationsUsCount = durationsUs.length;
int newDurationsUsCount = Math.max(count, oldDurationsUsCount);
int newDurationsUsCount = max(count, oldDurationsUsCount);
durationsUs = Arrays.copyOf(durationsUs, newDurationsUsCount);
Arrays.fill(durationsUs, oldDurationsUsCount, newDurationsUsCount, C.TIME_UNSET);
return durationsUs;
......
......@@ -15,6 +15,9 @@
*/
package com.google.android.exoplayer2.source.chunk;
import static java.lang.Math.max;
import static java.lang.Math.min;
import android.os.Looper;
import androidx.annotation.Nullable;
import com.google.android.exoplayer2.C;
......@@ -235,9 +238,9 @@ public class ChunkSampleStream<T extends ChunkSource> implements SampleStream, S
BaseMediaChunk lastCompletedMediaChunk = lastMediaChunk.isLoadCompleted() ? lastMediaChunk
: mediaChunks.size() > 1 ? mediaChunks.get(mediaChunks.size() - 2) : null;
if (lastCompletedMediaChunk != null) {
bufferedPositionUs = Math.max(bufferedPositionUs, lastCompletedMediaChunk.endTimeUs);
bufferedPositionUs = max(bufferedPositionUs, lastCompletedMediaChunk.endTimeUs);
}
return Math.max(bufferedPositionUs, primarySampleQueue.getLargestQueuedTimestampUs());
return max(bufferedPositionUs, primarySampleQueue.getLargestQueuedTimestampUs());
}
}
......@@ -682,7 +685,7 @@ public class ChunkSampleStream<T extends ChunkSource> implements SampleStream, S
primarySampleIndexToMediaChunkIndex(discardToSampleIndex, /* minChunkIndex= */ 0);
// Don't discard any chunks that we haven't reported the primary format change for yet.
discardToMediaChunkIndex =
Math.min(discardToMediaChunkIndex, nextNotifyPrimaryFormatMediaChunkIndex);
min(discardToMediaChunkIndex, nextNotifyPrimaryFormatMediaChunkIndex);
if (discardToMediaChunkIndex > 0) {
Util.removeRange(mediaChunks, /* fromIndex= */ 0, /* toIndex= */ discardToMediaChunkIndex);
nextNotifyPrimaryFormatMediaChunkIndex -= discardToMediaChunkIndex;
......@@ -749,7 +752,7 @@ public class ChunkSampleStream<T extends ChunkSource> implements SampleStream, S
BaseMediaChunk firstRemovedChunk = mediaChunks.get(chunkIndex);
Util.removeRange(mediaChunks, /* fromIndex= */ chunkIndex, /* toIndex= */ mediaChunks.size());
nextNotifyPrimaryFormatMediaChunkIndex =
Math.max(nextNotifyPrimaryFormatMediaChunkIndex, mediaChunks.size());
max(nextNotifyPrimaryFormatMediaChunkIndex, mediaChunks.size());
primarySampleQueue.discardUpstreamSamples(firstRemovedChunk.getFirstSampleIndex(0));
for (int i = 0; i < embeddedSampleQueues.length; i++) {
embeddedSampleQueues[i].discardUpstreamSamples(firstRemovedChunk.getFirstSampleIndex(i + 1));
......
......@@ -15,6 +15,8 @@
*/
package com.google.android.exoplayer2.text.cea;
import static java.lang.Math.min;
import android.graphics.Color;
import android.graphics.Typeface;
import android.text.Layout.Alignment;
......@@ -629,7 +631,7 @@ public final class Cea608Decoder extends CeaDecoder {
@Nullable Cue cue = cueBuilders.get(i).build(/* forcedPositionAnchor= */ Cue.TYPE_UNSET);
cueBuilderCues.add(cue);
if (cue != null) {
positionAnchor = Math.min(positionAnchor, cue.positionAnchor);
positionAnchor = min(positionAnchor, cue.positionAnchor);
}
}
......@@ -880,7 +882,7 @@ public final class Cea608Decoder extends CeaDecoder {
rolledUpCaptions.add(buildCurrentLine());
captionStringBuilder.setLength(0);
cueStyles.clear();
int numRows = Math.min(captionRowCount, row);
int numRows = min(captionRowCount, row);
while (rolledUpCaptions.size() >= numRows) {
rolledUpCaptions.remove(0);
}
......
......@@ -15,6 +15,8 @@
*/
package com.google.android.exoplayer2.text.dvb;
import static java.lang.Math.min;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
......@@ -163,10 +165,14 @@ import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
+ displayDefinition.horizontalPositionMinimum;
int baseVerticalAddress = pageRegion.verticalAddress
+ displayDefinition.verticalPositionMinimum;
int clipRight = Math.min(baseHorizontalAddress + regionComposition.width,
displayDefinition.horizontalPositionMaximum);
int clipBottom = Math.min(baseVerticalAddress + regionComposition.height,
displayDefinition.verticalPositionMaximum);
int clipRight =
min(
baseHorizontalAddress + regionComposition.width,
displayDefinition.horizontalPositionMaximum);
int clipBottom =
min(
baseVerticalAddress + regionComposition.height,
displayDefinition.verticalPositionMaximum);
canvas.clipRect(baseHorizontalAddress, baseVerticalAddress, clipRight, clipBottom);
ClutDefinition clutDefinition = subtitleService.cluts.get(regionComposition.clutId);
if (clutDefinition == null) {
......
......@@ -15,6 +15,8 @@
*/
package com.google.android.exoplayer2.text.pgs;
import static java.lang.Math.min;
import android.graphics.Bitmap;
import androidx.annotation.Nullable;
import com.google.android.exoplayer2.text.Cue;
......@@ -182,7 +184,7 @@ public final class PgsDecoder extends SimpleSubtitleDecoder {
int position = bitmapData.getPosition();
int limit = bitmapData.limit();
if (position < limit && sectionLength > 0) {
int bytesToRead = Math.min(sectionLength, limit - position);
int bytesToRead = min(sectionLength, limit - position);
buffer.readBytes(bitmapData.getData(), position, bytesToRead);
bitmapData.setPosition(position + bytesToRead);
}
......
......@@ -16,6 +16,7 @@
package com.google.android.exoplayer2.text.webvtt;
import static com.google.android.exoplayer2.text.span.SpanUtil.addOrReplaceSpan;
import static java.lang.Math.min;
import static java.lang.annotation.RetentionPolicy.SOURCE;
import android.graphics.Color;
......@@ -285,9 +286,12 @@ public final class WebvttCueParser {
case CHAR_AMPERSAND:
int semiColonEndIndex = markup.indexOf(CHAR_SEMI_COLON, pos + 1);
int spaceEndIndex = markup.indexOf(CHAR_SPACE, pos + 1);
int entityEndIndex = semiColonEndIndex == -1 ? spaceEndIndex
: (spaceEndIndex == -1 ? semiColonEndIndex
: Math.min(semiColonEndIndex, spaceEndIndex));
int entityEndIndex =
semiColonEndIndex == -1
? spaceEndIndex
: (spaceEndIndex == -1
? semiColonEndIndex
: min(semiColonEndIndex, spaceEndIndex));
if (entityEndIndex != -1) {
applyEntity(markup.substring(pos + 1, entityEndIndex), spannedText);
if (entityEndIndex == spaceEndIndex) {
......@@ -809,7 +813,7 @@ public final class WebvttCueParser {
.setLineAnchor(lineAnchor)
.setPosition(position)
.setPositionAnchor(positionAnchor)
.setSize(Math.min(size, deriveMaxSize(positionAnchor, position)))
.setSize(min(size, deriveMaxSize(positionAnchor, position)))
.setVerticalType(verticalType);
if (text != null) {
......
......@@ -15,6 +15,8 @@
*/
package com.google.android.exoplayer2.trackselection;
import static java.lang.Math.max;
import androidx.annotation.CallSuper;
import androidx.annotation.Nullable;
import com.google.android.exoplayer2.C;
......@@ -543,7 +545,7 @@ public class AdaptiveTrackSelection extends BaseTrackSelection {
@Override
public long getAllocatedBandwidth() {
long totalBandwidth = (long) (bandwidthMeter.getBitrateEstimate() * bandwidthFraction);
long allocatableBandwidth = Math.max(0L, totalBandwidth - reservedBandwidth);
long allocatableBandwidth = max(0L, totalBandwidth - reservedBandwidth);
if (allocationCheckpoints == null) {
return allocatableBandwidth;
}
......
......@@ -15,6 +15,8 @@
*/
package com.google.android.exoplayer2.trackselection;
import static java.lang.Math.max;
import android.os.SystemClock;
import androidx.annotation.Nullable;
import com.google.android.exoplayer2.C;
......@@ -160,7 +162,7 @@ public abstract class BaseTrackSelection implements TrackSelection {
return false;
}
excludeUntilTimes[index] =
Math.max(
max(
excludeUntilTimes[index],
Util.addWithOverflowDefault(nowMs, exclusionDurationMs, Long.MAX_VALUE));
return true;
......
......@@ -15,6 +15,9 @@
*/
package com.google.android.exoplayer2.trackselection;
import static java.lang.Math.max;
import static java.lang.Math.min;
import android.util.Pair;
import androidx.annotation.IntDef;
import androidx.annotation.Nullable;
......@@ -191,7 +194,7 @@ public abstract class MappingTrackSelector extends TrackSelector {
default:
throw new IllegalStateException();
}
bestRendererSupport = Math.max(bestRendererSupport, trackRendererSupport);
bestRendererSupport = max(bestRendererSupport, trackRendererSupport);
}
}
return bestRendererSupport;
......@@ -218,7 +221,7 @@ public abstract class MappingTrackSelector extends TrackSelector {
@RendererSupport int bestRendererSupport = RENDERER_SUPPORT_NO_TRACKS;
for (int i = 0; i < rendererCount; i++) {
if (rendererTrackTypes[i] == trackType) {
bestRendererSupport = Math.max(bestRendererSupport, getRendererSupport(i));
bestRendererSupport = max(bestRendererSupport, getRendererSupport(i));
}
}
return bestRendererSupport;
......@@ -307,13 +310,13 @@ public abstract class MappingTrackSelector extends TrackSelector {
multipleMimeTypes |= !Util.areEqual(firstSampleMimeType, sampleMimeType);
}
adaptiveSupport =
Math.min(
min(
adaptiveSupport,
RendererCapabilities.getAdaptiveSupport(
rendererFormatSupports[rendererIndex][groupIndex][i]));
}
return multipleMimeTypes
? Math.min(adaptiveSupport, rendererMixedMimeTypeAdaptiveSupports[rendererIndex])
? min(adaptiveSupport, rendererMixedMimeTypeAdaptiveSupports[rendererIndex])
: adaptiveSupport;
}
......@@ -502,7 +505,7 @@ public abstract class MappingTrackSelector extends TrackSelector {
int trackFormatSupportLevel =
RendererCapabilities.getFormatSupport(
rendererCapability.supportsFormat(group.getFormat(trackIndex)));
formatSupportLevel = Math.max(formatSupportLevel, trackFormatSupportLevel);
formatSupportLevel = max(formatSupportLevel, trackFormatSupportLevel);
}
boolean rendererIsUnassociated = rendererTrackGroupCounts[rendererIndex] == 0;
if (formatSupportLevel > bestFormatSupportLevel
......
......@@ -16,6 +16,7 @@
package com.google.android.exoplayer2.upstream;
import static com.google.android.exoplayer2.util.Util.castNonNull;
import static java.lang.Math.min;
import android.content.Context;
import android.content.res.AssetManager;
......@@ -102,8 +103,8 @@ public final class AssetDataSource extends BaseDataSource {
int bytesRead;
try {
int bytesToRead = bytesRemaining == C.LENGTH_UNSET ? readLength
: (int) Math.min(bytesRemaining, readLength);
int bytesToRead =
bytesRemaining == C.LENGTH_UNSET ? readLength : (int) min(bytesRemaining, readLength);
bytesRead = castNonNull(inputStream).read(buffer, offset, bytesToRead);
} catch (IOException e) {
throw new AssetDataSourceException(e);
......
......@@ -15,6 +15,8 @@
*/
package com.google.android.exoplayer2.upstream;
import static java.lang.Math.min;
import android.net.Uri;
import androidx.annotation.Nullable;
import com.google.android.exoplayer2.C;
......@@ -65,7 +67,7 @@ public final class ByteArrayDataSource extends BaseDataSource {
return C.RESULT_END_OF_INPUT;
}
readLength = Math.min(readLength, bytesRemaining);
readLength = min(readLength, bytesRemaining);
System.arraycopy(data, readPosition, buffer, offset, readLength);
readPosition += readLength;
bytesRemaining -= readLength;
......
......@@ -16,6 +16,7 @@
package com.google.android.exoplayer2.upstream;
import static com.google.android.exoplayer2.util.Util.castNonNull;
import static java.lang.Math.min;
import android.content.ContentResolver;
import android.content.Context;
......@@ -125,8 +126,8 @@ public final class ContentDataSource extends BaseDataSource {
int bytesRead;
try {
int bytesToRead = bytesRemaining == C.LENGTH_UNSET ? readLength
: (int) Math.min(bytesRemaining, readLength);
int bytesToRead =
bytesRemaining == C.LENGTH_UNSET ? readLength : (int) min(bytesRemaining, readLength);
bytesRead = castNonNull(inputStream).read(buffer, offset, bytesToRead);
} catch (IOException e) {
throw new ContentDataSourceException(e);
......
......@@ -16,6 +16,7 @@
package com.google.android.exoplayer2.upstream;
import static com.google.android.exoplayer2.util.Util.castNonNull;
import static java.lang.Math.min;
import android.net.Uri;
import android.util.Base64;
......@@ -85,7 +86,7 @@ public final class DataSchemeDataSource extends BaseDataSource {
if (remainingBytes == 0) {
return C.RESULT_END_OF_INPUT;
}
readLength = Math.min(readLength, remainingBytes);
readLength = min(readLength, remainingBytes);
System.arraycopy(castNonNull(data), readPosition, buffer, offset, readLength);
readPosition += readLength;
bytesTransferred(readLength);
......
......@@ -15,6 +15,8 @@
*/
package com.google.android.exoplayer2.upstream;
import static java.lang.Math.max;
import androidx.annotation.Nullable;
import com.google.android.exoplayer2.util.Assertions;
import com.google.android.exoplayer2.util.Util;
......@@ -115,8 +117,10 @@ public final class DefaultAllocator implements Allocator {
@Override
public synchronized void release(Allocation[] allocations) {
if (availableCount + allocations.length >= availableAllocations.length) {
availableAllocations = Arrays.copyOf(availableAllocations,
Math.max(availableAllocations.length * 2, availableCount + allocations.length));
availableAllocations =
Arrays.copyOf(
availableAllocations,
max(availableAllocations.length * 2, availableCount + allocations.length));
}
for (Allocation allocation : allocations) {
availableAllocations[availableCount++] = allocation;
......@@ -129,7 +133,7 @@ public final class DefaultAllocator implements Allocator {
@Override
public synchronized void trim() {
int targetAllocationCount = Util.ceilDivide(targetBufferSize, individualAllocationSize);
int targetAvailableCount = Math.max(0, targetAllocationCount - allocatedCount);
int targetAvailableCount = max(0, targetAllocationCount - allocatedCount);
if (targetAvailableCount >= availableCount) {
// We're already at or below the target.
return;
......@@ -156,7 +160,7 @@ public final class DefaultAllocator implements Allocator {
}
}
// lowIndex is the index of the first allocation not backed by an initial block.
targetAvailableCount = Math.max(targetAvailableCount, lowIndex);
targetAvailableCount = max(targetAvailableCount, lowIndex);
if (targetAvailableCount >= availableCount) {
// We're already at or below the target.
return;
......
......@@ -15,6 +15,9 @@
*/
package com.google.android.exoplayer2.upstream;
import static java.lang.Math.max;
import static java.lang.Math.min;
import android.net.Uri;
import android.text.TextUtils;
import androidx.annotation.Nullable;
......@@ -634,7 +637,7 @@ public class DefaultHttpDataSource extends BaseDataSource implements HttpDataSou
// increase it.
Log.w(TAG, "Inconsistent headers [" + contentLengthHeader + "] [" + contentRangeHeader
+ "]");
contentLength = Math.max(contentLength, contentLengthFromRange);
contentLength = max(contentLength, contentLengthFromRange);
}
} catch (NumberFormatException e) {
Log.e(TAG, "Unexpected Content-Range [" + contentRangeHeader + "]");
......@@ -664,7 +667,7 @@ public class DefaultHttpDataSource extends BaseDataSource implements HttpDataSou
}
while (bytesSkipped != bytesToSkip) {
int readLength = (int) Math.min(bytesToSkip - bytesSkipped, skipBuffer.length);
int readLength = (int) min(bytesToSkip - bytesSkipped, skipBuffer.length);
int read = inputStream.read(skipBuffer, 0, readLength);
if (Thread.currentThread().isInterrupted()) {
throw new InterruptedIOException();
......@@ -703,7 +706,7 @@ public class DefaultHttpDataSource extends BaseDataSource implements HttpDataSou
if (bytesRemaining == 0) {
return C.RESULT_END_OF_INPUT;
}
readLength = (int) Math.min(readLength, bytesRemaining);
readLength = (int) min(readLength, bytesRemaining);
}
int read = inputStream.read(buffer, offset, readLength);
......
......@@ -15,6 +15,8 @@
*/
package com.google.android.exoplayer2.upstream;
import static java.lang.Math.min;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.ParserException;
import com.google.android.exoplayer2.upstream.HttpDataSource.InvalidResponseCodeException;
......@@ -91,7 +93,7 @@ public class DefaultLoadErrorHandlingPolicy implements LoadErrorHandlingPolicy {
|| exception instanceof FileNotFoundException
|| exception instanceof UnexpectedLoaderException
? C.TIME_UNSET
: Math.min((loadErrorInfo.errorCount - 1) * 1000, 5000);
: min((loadErrorInfo.errorCount - 1) * 1000, 5000);
}
/**
......
......@@ -16,6 +16,7 @@
package com.google.android.exoplayer2.upstream;
import static com.google.android.exoplayer2.util.Util.castNonNull;
import static java.lang.Math.min;
import android.net.Uri;
import android.text.TextUtils;
......@@ -111,8 +112,7 @@ public final class FileDataSource extends BaseDataSource {
} else {
int bytesRead;
try {
bytesRead =
castNonNull(file).read(buffer, offset, (int) Math.min(bytesRemaining, readLength));
bytesRead = castNonNull(file).read(buffer, offset, (int) min(bytesRemaining, readLength));
} catch (IOException e) {
throw new FileDataSourceException(e);
}
......
......@@ -15,6 +15,8 @@
*/
package com.google.android.exoplayer2.upstream;
import static java.lang.Math.min;
import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Looper;
......@@ -516,7 +518,7 @@ public final class Loader implements LoaderErrorThrower {
}
private long getRetryDelayMillis() {
return Math.min((errorCount - 1) * 1000, 5000);
return min((errorCount - 1) * 1000, 5000);
}
}
......
......@@ -16,6 +16,7 @@
package com.google.android.exoplayer2.upstream;
import static com.google.android.exoplayer2.util.Util.castNonNull;
import static java.lang.Math.min;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
......@@ -141,8 +142,8 @@ public final class RawResourceDataSource extends BaseDataSource {
int bytesRead;
try {
int bytesToRead = bytesRemaining == C.LENGTH_UNSET ? readLength
: (int) Math.min(bytesRemaining, readLength);
int bytesToRead =
bytesRemaining == C.LENGTH_UNSET ? readLength : (int) min(bytesRemaining, readLength);
bytesRead = castNonNull(inputStream).read(buffer, offset, bytesToRead);
} catch (IOException e) {
throw new RawResourceDataSourceException(e);
......
......@@ -15,6 +15,8 @@
*/
package com.google.android.exoplayer2.upstream;
import static java.lang.Math.min;
import android.net.Uri;
import androidx.annotation.Nullable;
import com.google.android.exoplayer2.C;
......@@ -137,7 +139,7 @@ public final class UdpDataSource extends BaseDataSource {
}
int packetOffset = packet.getLength() - packetRemaining;
int bytesToRead = Math.min(packetRemaining, readLength);
int bytesToRead = min(packetRemaining, readLength);
System.arraycopy(packetBuffer, packetOffset, buffer, offset, bytesToRead);
packetRemaining -= bytesToRead;
return bytesToRead;
......
......@@ -17,6 +17,7 @@ package com.google.android.exoplayer2.upstream.cache;
import static com.google.android.exoplayer2.util.Assertions.checkNotNull;
import static com.google.android.exoplayer2.util.Util.castNonNull;
import static java.lang.Math.min;
import androidx.annotation.Nullable;
import com.google.android.exoplayer2.C;
......@@ -207,7 +208,7 @@ public final class CacheDataSink implements DataSink {
openNextOutputStream(dataSpec);
}
int bytesToWrite =
(int) Math.min(length - bytesWritten, dataSpecFragmentSize - outputStreamBytesWritten);
(int) min(length - bytesWritten, dataSpecFragmentSize - outputStreamBytesWritten);
castNonNull(outputStream).write(buffer, offset + bytesWritten, bytesToWrite);
bytesWritten += bytesToWrite;
outputStreamBytesWritten += bytesToWrite;
......@@ -234,7 +235,7 @@ public final class CacheDataSink implements DataSink {
long length =
dataSpec.length == C.LENGTH_UNSET
? C.LENGTH_UNSET
: Math.min(dataSpec.length - dataSpecBytesWritten, dataSpecFragmentSize);
: min(dataSpec.length - dataSpecBytesWritten, dataSpecFragmentSize);
file =
cache.startFile(
castNonNull(dataSpec.key), dataSpec.position + dataSpecBytesWritten, length);
......
......@@ -17,6 +17,7 @@ package com.google.android.exoplayer2.upstream.cache;
import static com.google.android.exoplayer2.util.Assertions.checkNotNull;
import static com.google.android.exoplayer2.util.Util.castNonNull;
import static java.lang.Math.min;
import android.net.Uri;
import androidx.annotation.IntDef;
......@@ -700,7 +701,7 @@ public final class CacheDataSource implements DataSource {
long positionInFile = readPosition - filePositionOffset;
long length = nextSpan.length - positionInFile;
if (bytesRemaining != C.LENGTH_UNSET) {
length = Math.min(length, bytesRemaining);
length = min(length, bytesRemaining);
}
nextDataSpec =
requestDataSpec
......@@ -719,7 +720,7 @@ public final class CacheDataSource implements DataSource {
} else {
length = nextSpan.length;
if (bytesRemaining != C.LENGTH_UNSET) {
length = Math.min(length, bytesRemaining);
length = min(length, bytesRemaining);
}
}
nextDataSpec =
......
......@@ -17,6 +17,8 @@ package com.google.android.exoplayer2.upstream.cache;
import static com.google.android.exoplayer2.util.Assertions.checkArgument;
import static com.google.android.exoplayer2.util.Assertions.checkState;
import static java.lang.Math.max;
import static java.lang.Math.min;
import androidx.annotation.Nullable;
import com.google.android.exoplayer2.C;
......@@ -157,7 +159,7 @@ import java.util.TreeSet;
SimpleCacheSpan ceilSpan = cachedSpans.ceiling(lookupSpan);
if (ceilSpan != null) {
long holeLength = ceilSpan.position - position;
length = length == C.LENGTH_UNSET ? holeLength : Math.min(holeLength, length);
length = length == C.LENGTH_UNSET ? holeLength : min(holeLength, length);
}
return SimpleCacheSpan.createHole(key, position, length);
}
......@@ -179,7 +181,7 @@ import java.util.TreeSet;
SimpleCacheSpan span = getSpan(position, length);
if (span.isHoleSpan()) {
// We don't have a span covering the start of the queried region.
return -Math.min(span.isOpenEnded() ? Long.MAX_VALUE : span.length, length);
return -min(span.isOpenEnded() ? Long.MAX_VALUE : span.length, length);
}
long queryEndPosition = position + length;
if (queryEndPosition < 0) {
......@@ -195,14 +197,14 @@ import java.util.TreeSet;
}
// We expect currentEndPosition to always equal (next.position + next.length), but
// perform a max check anyway to guard against the existence of overlapping spans.
currentEndPosition = Math.max(currentEndPosition, next.position + next.length);
currentEndPosition = max(currentEndPosition, next.position + next.length);
if (currentEndPosition >= queryEndPosition) {
// We've found spans covering the queried region.
break;
}
}
}
return Math.min(currentEndPosition - position, length);
return min(currentEndPosition - position, length);
}
/**
......
......@@ -15,6 +15,8 @@
*/
package com.google.android.exoplayer2.upstream.cache;
import static java.lang.Math.min;
import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.database.Cursor;
......@@ -391,13 +393,13 @@ import org.checkerframework.checker.nullness.compatqual.NullableType;
// large) valueSize was read. In such cases the implementation below is expected to throw
// IOException from one of the readFully calls, due to the end of the input being reached.
int bytesRead = 0;
int nextBytesToRead = Math.min(valueSize, INCREMENTAL_METADATA_READ_LENGTH);
int nextBytesToRead = min(valueSize, INCREMENTAL_METADATA_READ_LENGTH);
byte[] value = Util.EMPTY_BYTE_ARRAY;
while (bytesRead != valueSize) {
value = Arrays.copyOf(value, bytesRead + nextBytesToRead);
input.readFully(value, bytesRead, nextBytesToRead);
bytesRead += nextBytesToRead;
nextBytesToRead = Math.min(valueSize - bytesRead, INCREMENTAL_METADATA_READ_LENGTH);
nextBytesToRead = min(valueSize - bytesRead, INCREMENTAL_METADATA_READ_LENGTH);
}
metadata.put(name, value);
}
......
......@@ -16,6 +16,7 @@
package com.google.android.exoplayer2.upstream.crypto;
import static com.google.android.exoplayer2.util.Util.castNonNull;
import static java.lang.Math.min;
import androidx.annotation.Nullable;
import com.google.android.exoplayer2.upstream.DataSink;
......@@ -83,7 +84,7 @@ public final class AesCipherDataSink implements DataSink {
// Use scratch space. The original data remains intact.
int bytesProcessed = 0;
while (bytesProcessed < length) {
int bytesToProcess = Math.min(length - bytesProcessed, scratch.length);
int bytesToProcess = min(length - bytesProcessed, scratch.length);
castNonNull(cipher)
.update(data, offset + bytesProcessed, bytesToProcess, scratch, /* outOffset= */ 0);
wrappedDataSink.write(scratch, /* offset= */ 0, bytesToProcess);
......
......@@ -15,6 +15,8 @@
*/
package com.google.android.exoplayer2.util;
import static java.lang.Math.min;
import android.os.SystemClock;
import android.text.TextUtils;
import android.view.Surface;
......@@ -162,14 +164,14 @@ public class EventLogger implements AnalyticsListener {
+ windowCount
+ ", reason="
+ getTimelineChangeReasonString(reason));
for (int i = 0; i < Math.min(periodCount, MAX_TIMELINE_ITEM_LINES); i++) {
for (int i = 0; i < min(periodCount, MAX_TIMELINE_ITEM_LINES); i++) {
eventTime.timeline.getPeriod(i, period);
logd(" " + "period [" + getTimeString(period.getDurationMs()) + "]");
}
if (periodCount > MAX_TIMELINE_ITEM_LINES) {
logd(" ...");
}
for (int i = 0; i < Math.min(windowCount, MAX_TIMELINE_ITEM_LINES); i++) {
for (int i = 0; i < min(windowCount, MAX_TIMELINE_ITEM_LINES); i++) {
eventTime.timeline.getWindow(i, window);
logd(
" "
......
......@@ -15,6 +15,8 @@
*/
package com.google.android.exoplayer2.util;
import static java.lang.Math.max;
import java.io.IOException;
import java.util.Collections;
import java.util.PriorityQueue;
......@@ -59,7 +61,7 @@ public final class PriorityTaskManager {
public void add(int priority) {
synchronized (lock) {
queue.add(priority);
highestPriority = Math.max(highestPriority, priority);
highestPriority = max(highestPriority, priority);
}
}
......
......@@ -15,6 +15,8 @@
*/
package com.google.android.exoplayer2.video;
import static java.lang.Math.max;
import android.os.Handler;
import android.os.SystemClock;
import android.view.Surface;
......@@ -505,7 +507,7 @@ public abstract class DecoderVideoRenderer extends BaseRenderer {
droppedFrames += droppedBufferCount;
consecutiveDroppedFrameCount += droppedBufferCount;
decoderCounters.maxConsecutiveDroppedBufferCount =
Math.max(consecutiveDroppedFrameCount, decoderCounters.maxConsecutiveDroppedBufferCount);
max(consecutiveDroppedFrameCount, decoderCounters.maxConsecutiveDroppedBufferCount);
if (maxDroppedFramesToNotify > 0 && droppedFrames >= maxDroppedFramesToNotify) {
maybeNotifyDroppedFrames();
}
......
......@@ -15,6 +15,9 @@
*/
package com.google.android.exoplayer2.video;
import static java.lang.Math.max;
import static java.lang.Math.min;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
......@@ -620,7 +623,7 @@ public class MediaCodecVideoRenderer extends MediaCodecRenderer {
for (Format streamFormat : streamFormats) {
float streamFrameRate = streamFormat.frameRate;
if (streamFrameRate != Format.NO_VALUE) {
maxFrameRate = Math.max(maxFrameRate, streamFrameRate);
maxFrameRate = max(maxFrameRate, streamFrameRate);
}
}
return maxFrameRate == -1 ? CODEC_OPERATING_RATE_UNSET : (maxFrameRate * operatingRate);
......@@ -1041,8 +1044,8 @@ public class MediaCodecVideoRenderer extends MediaCodecRenderer {
decoderCounters.droppedBufferCount += droppedBufferCount;
droppedFrames += droppedBufferCount;
consecutiveDroppedFrameCount += droppedBufferCount;
decoderCounters.maxConsecutiveDroppedBufferCount = Math.max(consecutiveDroppedFrameCount,
decoderCounters.maxConsecutiveDroppedBufferCount);
decoderCounters.maxConsecutiveDroppedBufferCount =
max(consecutiveDroppedFrameCount, decoderCounters.maxConsecutiveDroppedBufferCount);
if (maxDroppedFramesToNotify > 0 && droppedFrames >= maxDroppedFramesToNotify) {
maybeNotifyDroppedFrames();
}
......@@ -1354,7 +1357,7 @@ public class MediaCodecVideoRenderer extends MediaCodecRenderer {
int scaledMaxInputSize =
(int) (maxInputSize * INITIAL_FORMAT_MAX_INPUT_SIZE_SCALE_FACTOR);
// Avoid exceeding the maximum expected for the codec.
maxInputSize = Math.min(scaledMaxInputSize, codecMaxInputSize);
maxInputSize = min(scaledMaxInputSize, codecMaxInputSize);
}
}
return new CodecMaxValues(maxWidth, maxHeight, maxInputSize);
......@@ -1365,19 +1368,19 @@ public class MediaCodecVideoRenderer extends MediaCodecRenderer {
format, streamFormat, /* isNewFormatComplete= */ false)) {
haveUnknownDimensions |=
(streamFormat.width == Format.NO_VALUE || streamFormat.height == Format.NO_VALUE);
maxWidth = Math.max(maxWidth, streamFormat.width);
maxHeight = Math.max(maxHeight, streamFormat.height);
maxInputSize = Math.max(maxInputSize, getMaxInputSize(codecInfo, streamFormat));
maxWidth = max(maxWidth, streamFormat.width);
maxHeight = max(maxHeight, streamFormat.height);
maxInputSize = max(maxInputSize, getMaxInputSize(codecInfo, streamFormat));
}
}
if (haveUnknownDimensions) {
Log.w(TAG, "Resolutions unknown. Codec max resolution: " + maxWidth + "x" + maxHeight);
Point codecMaxSize = getCodecMaxSize(codecInfo, format);
if (codecMaxSize != null) {
maxWidth = Math.max(maxWidth, codecMaxSize.x);
maxHeight = Math.max(maxHeight, codecMaxSize.y);
maxWidth = max(maxWidth, codecMaxSize.x);
maxHeight = max(maxHeight, codecMaxSize.y);
maxInputSize =
Math.max(
max(
maxInputSize,
getCodecMaxInputSize(codecInfo, format.sampleMimeType, maxWidth, maxHeight));
Log.w(TAG, "Codec max resolution adjusted to: " + maxWidth + "x" + maxHeight);
......
......@@ -16,6 +16,7 @@
package com.google.android.exoplayer2;
import static com.google.common.truth.Truth.assertThat;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
......@@ -29,7 +30,6 @@ import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.junit.After;
import org.junit.Before;
......@@ -117,7 +117,7 @@ public class PlayerMessageTest {
assertThat(message.experimental_blockUntilDelivered(TIMEOUT_MS, clock)).isTrue();
// Ensure experimental_blockUntilDelivered() entered the blocking loop.
verify(clock, Mockito.atLeast(2)).elapsedRealtime();
future.get(1, TimeUnit.SECONDS);
future.get(1, SECONDS);
} finally {
executorService.shutdown();
}
......
......@@ -16,6 +16,7 @@
package com.google.android.exoplayer2.audio;
import static com.google.common.truth.Truth.assertThat;
import static java.lang.Math.min;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import com.google.android.exoplayer2.C;
......@@ -320,7 +321,7 @@ public final class SilenceSkippingAudioProcessorTest {
ByteBuffer inputBuffer = ByteBuffer.allocate(sizeBytes).order(ByteOrder.nativeOrder());
ShortBuffer inputBufferAsShortBuffer = inputBuffer.asShortBuffer();
int limit = buffer.limit();
buffer.limit(Math.min(buffer.position() + sizeBytes / 2, limit));
buffer.limit(min(buffer.position() + sizeBytes / 2, limit));
inputBufferAsShortBuffer.put(buffer);
buffer.limit(limit);
inputBuffer.limit(inputBufferAsShortBuffer.position() * 2);
......
......@@ -16,6 +16,7 @@
package com.google.android.exoplayer2.offline;
import static com.google.common.truth.Truth.assertThat;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.robolectric.shadows.ShadowBaseLooper.shadowMainLooper;
import androidx.test.core.app.ApplicationProvider;
......@@ -46,7 +47,6 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.Before;
import org.junit.BeforeClass;
......@@ -433,7 +433,7 @@ public class DownloadHelperTest {
preparedLatch.countDown();
}
});
while (!preparedLatch.await(0, TimeUnit.MILLISECONDS)) {
while (!preparedLatch.await(0, MILLISECONDS)) {
shadowMainLooper().idleFor(shadowMainLooper().getNextScheduledTaskTime());
}
if (prepareException.get() != null) {
......
......@@ -16,6 +16,7 @@
package com.google.android.exoplayer2.source;
import static com.google.common.truth.Truth.assertThat;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
......@@ -38,7 +39,6 @@ import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
......@@ -413,7 +413,7 @@ public final class ConcatenatingMediaSourceTest {
createFakeMediaSource(),
Util.createHandlerForCurrentLooper(),
runnableInvoked::countDown));
runnableInvoked.await(MediaSourceTestRunner.TIMEOUT_MS, TimeUnit.MILLISECONDS);
runnableInvoked.await(MediaSourceTestRunner.TIMEOUT_MS, MILLISECONDS);
testThread.release();
assertThat(runnableInvoked.getCount()).isEqualTo(0);
......@@ -430,7 +430,7 @@ public final class ConcatenatingMediaSourceTest {
Arrays.asList(new MediaSource[] {createFakeMediaSource(), createFakeMediaSource()}),
Util.createHandlerForCurrentLooper(),
runnableInvoked::countDown));
runnableInvoked.await(MediaSourceTestRunner.TIMEOUT_MS, TimeUnit.MILLISECONDS);
runnableInvoked.await(MediaSourceTestRunner.TIMEOUT_MS, MILLISECONDS);
testThread.release();
assertThat(runnableInvoked.getCount()).isEqualTo(0);
......@@ -448,7 +448,7 @@ public final class ConcatenatingMediaSourceTest {
createFakeMediaSource(),
Util.createHandlerForCurrentLooper(),
runnableInvoked::countDown));
runnableInvoked.await(MediaSourceTestRunner.TIMEOUT_MS, TimeUnit.MILLISECONDS);
runnableInvoked.await(MediaSourceTestRunner.TIMEOUT_MS, MILLISECONDS);
testThread.release();
assertThat(runnableInvoked.getCount()).isEqualTo(0);
......@@ -466,7 +466,7 @@ public final class ConcatenatingMediaSourceTest {
Arrays.asList(new MediaSource[] {createFakeMediaSource(), createFakeMediaSource()}),
Util.createHandlerForCurrentLooper(),
runnableInvoked::countDown));
runnableInvoked.await(MediaSourceTestRunner.TIMEOUT_MS, TimeUnit.MILLISECONDS);
runnableInvoked.await(MediaSourceTestRunner.TIMEOUT_MS, MILLISECONDS);
testThread.release();
assertThat(runnableInvoked.getCount()).isEqualTo(0);
......@@ -483,7 +483,7 @@ public final class ConcatenatingMediaSourceTest {
mediaSource.removeMediaSource(
/* index */ 0, Util.createHandlerForCurrentLooper(), runnableInvoked::countDown);
});
runnableInvoked.await(MediaSourceTestRunner.TIMEOUT_MS, TimeUnit.MILLISECONDS);
runnableInvoked.await(MediaSourceTestRunner.TIMEOUT_MS, MILLISECONDS);
testThread.release();
assertThat(runnableInvoked.getCount()).isEqualTo(0);
......@@ -504,7 +504,7 @@ public final class ConcatenatingMediaSourceTest {
Util.createHandlerForCurrentLooper(),
runnableInvoked::countDown);
});
runnableInvoked.await(MediaSourceTestRunner.TIMEOUT_MS, TimeUnit.MILLISECONDS);
runnableInvoked.await(MediaSourceTestRunner.TIMEOUT_MS, MILLISECONDS);
testThread.release();
assertThat(runnableInvoked.getCount()).isEqualTo(0);
......@@ -652,9 +652,7 @@ public final class ConcatenatingMediaSourceTest {
callbackCalledCondition::countDown);
mediaSource.releaseSource(caller);
});
assertThat(
callbackCalledCondition.await(
MediaSourceTestRunner.TIMEOUT_MS, TimeUnit.MILLISECONDS))
assertThat(callbackCalledCondition.await(MediaSourceTestRunner.TIMEOUT_MS, MILLISECONDS))
.isTrue();
} finally {
testThread.release();
......@@ -1055,7 +1053,7 @@ public final class ConcatenatingMediaSourceTest {
new ShuffleOrder.UnshuffledShuffleOrder(/* length= */ 0),
Util.createHandlerForCurrentLooper(),
runnableInvoked::countDown));
runnableInvoked.await(MediaSourceTestRunner.TIMEOUT_MS, TimeUnit.MILLISECONDS);
runnableInvoked.await(MediaSourceTestRunner.TIMEOUT_MS, MILLISECONDS);
testThread.release();
assertThat(runnableInvoked.getCount()).isEqualTo(0);
......@@ -1146,8 +1144,7 @@ public final class ConcatenatingMediaSourceTest {
}
public Timeline assertTimelineChangeBlocking() throws InterruptedException {
assertThat(finishedLatch.await(MediaSourceTestRunner.TIMEOUT_MS, TimeUnit.MILLISECONDS))
.isTrue();
assertThat(finishedLatch.await(MediaSourceTestRunner.TIMEOUT_MS, MILLISECONDS)).isTrue();
if (error != null) {
throw error;
}
......
......@@ -16,6 +16,7 @@
package com.google.android.exoplayer2.upstream;
import static com.google.common.truth.Truth.assertThat;
import static java.lang.Math.min;
import static org.junit.Assert.fail;
import android.net.Uri;
......@@ -125,7 +126,7 @@ public final class ByteArrayDataSourceTest {
while (true) {
// Calculate a valid length for the next read, constraining by the specified output buffer
// length, write offset and maximum write length input parameters.
int requestedReadLength = Math.min(maxReadLength, outputBufferLength - writeOffset);
int requestedReadLength = min(maxReadLength, outputBufferLength - writeOffset);
assertThat(requestedReadLength).isGreaterThan(0);
int bytesRead = dataSource.read(outputBuffer, writeOffset, requestedReadLength);
......
......@@ -17,6 +17,7 @@ package com.google.android.exoplayer2.upstream.cache;
import static com.google.android.exoplayer2.testutil.CacheAsserts.assertCacheEmpty;
import static com.google.common.truth.Truth.assertThat;
import static java.lang.Math.min;
import static org.junit.Assert.fail;
import android.net.Uri;
......@@ -550,7 +551,7 @@ public final class CacheDataSourceTest {
int requestLength = (int) dataSpec.length;
int readLength = TEST_DATA.length - position;
if (requestLength != C.LENGTH_UNSET) {
readLength = Math.min(readLength, requestLength);
readLength = min(readLength, requestLength);
}
assertThat(cacheDataSource.open(dataSpec))
.isEqualTo(unknownLength ? requestLength : readLength);
......
......@@ -17,6 +17,7 @@ package com.google.android.exoplayer2.upstream.cache;
import static com.google.android.exoplayer2.testutil.CacheAsserts.assertCachedData;
import static com.google.common.truth.Truth.assertThat;
import static java.lang.Math.min;
import static org.junit.Assert.assertThrows;
import android.net.Uri;
......@@ -69,7 +70,7 @@ public final class CacheWriterTest {
for (int i = 0; i < spansAndGaps.length; i++) {
int spanOrGap = spansAndGaps[i];
if (position < spanOrGap) {
long left = Math.min(spanOrGap - position, length);
long left = min(spanOrGap - position, length);
return (i & 1) == 1 ? -left : left;
}
position -= spanOrGap;
......
......@@ -16,6 +16,7 @@
package com.google.android.exoplayer2.upstream.crypto;
import static com.google.common.truth.Truth.assertThat;
import static java.lang.Math.min;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import com.google.android.exoplayer2.testutil.TestUtil;
......@@ -100,7 +101,7 @@ public class AesFlushingCipherTest {
int offset = 0;
while (offset < data.length) {
int bytes = (1 + random.nextInt(50)) * 16;
bytes = Math.min(bytes, data.length - offset);
bytes = min(bytes, data.length - offset);
assertThat(bytes % 16).isEqualTo(0);
encryptCipher.updateInPlace(data, offset, bytes);
offset += bytes;
......@@ -113,7 +114,7 @@ public class AesFlushingCipherTest {
offset = 0;
while (offset < data.length) {
int bytes = (1 + random.nextInt(50)) * 16;
bytes = Math.min(bytes, data.length - offset);
bytes = min(bytes, data.length - offset);
assertThat(bytes % 16).isEqualTo(0);
decryptCipher.updateInPlace(data, offset, bytes);
offset += bytes;
......@@ -134,7 +135,7 @@ public class AesFlushingCipherTest {
int offset = 0;
while (offset < data.length) {
int bytes = 1 + random.nextInt(4095);
bytes = Math.min(bytes, data.length - offset);
bytes = min(bytes, data.length - offset);
encryptCipher.updateInPlace(data, offset, bytes);
offset += bytes;
}
......@@ -146,7 +147,7 @@ public class AesFlushingCipherTest {
offset = 0;
while (offset < data.length) {
int bytes = 1 + random.nextInt(4095);
bytes = Math.min(bytes, data.length - offset);
bytes = min(bytes, data.length - offset);
decryptCipher.updateInPlace(data, offset, bytes);
offset += bytes;
}
......@@ -166,7 +167,7 @@ public class AesFlushingCipherTest {
int offset = 0;
while (offset < data.length) {
int bytes = 1 + random.nextInt(4095);
bytes = Math.min(bytes, data.length - offset);
bytes = min(bytes, data.length - offset);
encryptCipher.updateInPlace(data, offset, bytes);
offset += bytes;
}
......@@ -185,7 +186,7 @@ public class AesFlushingCipherTest {
// Decrypt
while (remainingLength > 0) {
int bytes = 1 + random.nextInt(4095);
bytes = Math.min(bytes, remainingLength);
bytes = min(bytes, remainingLength);
decryptCipher.updateInPlace(data, offset, bytes);
offset += bytes;
remainingLength -= bytes;
......
......@@ -15,6 +15,8 @@
*/
package com.google.android.exoplayer2.source.dash;
import static java.lang.Math.min;
import android.util.Pair;
import android.util.SparseArray;
import android.util.SparseIntArray;
......@@ -585,7 +587,7 @@ import org.checkerframework.checker.nullness.compatqual.NullableType;
adaptationSetIdToIndex.get(
Integer.parseInt(adaptationSetId), /* valueIfKeyNotFound= */ -1);
if (otherAdaptationSetId != -1) {
mergedGroupIndex = Math.min(mergedGroupIndex, otherAdaptationSetId);
mergedGroupIndex = min(mergedGroupIndex, otherAdaptationSetId);
}
}
}
......
......@@ -16,6 +16,8 @@
package com.google.android.exoplayer2.source.dash;
import static com.google.android.exoplayer2.util.Assertions.checkNotNull;
import static java.lang.Math.max;
import static java.lang.Math.min;
import android.net.Uri;
import android.os.Handler;
......@@ -1035,7 +1037,7 @@ public final class DashMediaSource extends BaseMediaSource {
long liveStreamDurationUs = nowUnixTimeUs - C.msToUs(manifest.availabilityStartTimeMs);
long liveStreamEndPositionInLastPeriodUs = liveStreamDurationUs
- C.msToUs(manifest.getPeriod(lastPeriodIndex).startMs);
currentEndTimeUs = Math.min(liveStreamEndPositionInLastPeriodUs, currentEndTimeUs);
currentEndTimeUs = min(liveStreamEndPositionInLastPeriodUs, currentEndTimeUs);
if (manifest.timeShiftBufferDepthMs != C.TIME_UNSET) {
long timeShiftBufferDepthUs = C.msToUs(manifest.timeShiftBufferDepthMs);
long offsetInPeriodUs = currentEndTimeUs - timeShiftBufferDepthUs;
......@@ -1044,7 +1046,7 @@ public final class DashMediaSource extends BaseMediaSource {
offsetInPeriodUs += manifest.getPeriodDurationUs(--periodIndex);
}
if (periodIndex == 0) {
currentStartTimeUs = Math.max(currentStartTimeUs, offsetInPeriodUs);
currentStartTimeUs = max(currentStartTimeUs, offsetInPeriodUs);
} else {
// The time shift buffer starts after the earliest period.
// TODO: Does this ever happen?
......@@ -1070,8 +1072,8 @@ public final class DashMediaSource extends BaseMediaSource {
// The default start position is too close to the start of the live window. Set it to the
// minimum default start position provided the window is at least twice as big. Else set
// it to the middle of the window.
windowDefaultStartPositionUs = Math.min(MIN_LIVE_DEFAULT_START_POSITION_US,
windowDurationUs / 2);
windowDefaultStartPositionUs =
min(MIN_LIVE_DEFAULT_START_POSITION_US, windowDurationUs / 2);
}
}
long windowStartTimeMs = C.TIME_UNSET;
......@@ -1116,8 +1118,7 @@ public final class DashMediaSource extends BaseMediaSource {
minUpdatePeriodMs = 5000;
}
long nextLoadTimestampMs = manifestLoadStartTimestampMs + minUpdatePeriodMs;
long delayUntilNextLoadMs =
Math.max(0, nextLoadTimestampMs - SystemClock.elapsedRealtime());
long delayUntilNextLoadMs = max(0, nextLoadTimestampMs - SystemClock.elapsedRealtime());
scheduleManifestRefresh(delayUntilNextLoadMs);
}
}
......@@ -1148,7 +1149,7 @@ public final class DashMediaSource extends BaseMediaSource {
}
private long getManifestLoadRetryDelayMillis() {
return Math.min((staleManifestReloadAttempt - 1) * 1000, 5000);
return min((staleManifestReloadAttempt - 1) * 1000, 5000);
}
private <T> void startLoading(ParsingLoadable<T> loadable,
......@@ -1199,12 +1200,12 @@ public final class DashMediaSource extends BaseMediaSource {
} else if (!seenEmptyIndex) {
long firstSegmentNum = index.getFirstSegmentNum();
long adaptationSetAvailableStartTimeUs = index.getTimeUs(firstSegmentNum);
availableStartTimeUs = Math.max(availableStartTimeUs, adaptationSetAvailableStartTimeUs);
availableStartTimeUs = max(availableStartTimeUs, adaptationSetAvailableStartTimeUs);
if (segmentCount != DashSegmentIndex.INDEX_UNBOUNDED) {
long lastSegmentNum = firstSegmentNum + segmentCount - 1;
long adaptationSetAvailableEndTimeUs = index.getTimeUs(lastSegmentNum)
+ index.getDurationUs(lastSegmentNum, durationUs);
availableEndTimeUs = Math.min(availableEndTimeUs, adaptationSetAvailableEndTimeUs);
availableEndTimeUs = min(availableEndTimeUs, adaptationSetAvailableEndTimeUs);
}
}
}
......
......@@ -15,6 +15,9 @@
*/
package com.google.android.exoplayer2.source.dash;
import static java.lang.Math.max;
import static java.lang.Math.min;
import android.net.Uri;
import android.os.SystemClock;
import androidx.annotation.CheckResult;
......@@ -363,8 +366,7 @@ public class DefaultDashChunkSource implements DashChunkSource {
return;
}
int maxSegmentCount =
(int) Math.min(maxSegmentsPerLoad, lastAvailableSegmentNum - segmentNum + 1);
int maxSegmentCount = (int) min(maxSegmentsPerLoad, lastAvailableSegmentNum - segmentNum + 1);
if (periodDurationUs != C.TIME_UNSET) {
while (maxSegmentCount > 1
&& representationHolder.getSegmentStartTimeUs(segmentNum + maxSegmentCount - 1)
......@@ -759,8 +761,7 @@ public class DefaultDashChunkSource implements DashChunkSource {
long periodStartUs = C.msToUs(manifest.getPeriod(periodIndex).startMs);
long liveEdgeTimeInPeriodUs = liveEdgeTimeUs - periodStartUs;
long bufferDepthUs = C.msToUs(manifest.timeShiftBufferDepthMs);
return Math.max(
getFirstSegmentNum(), getSegmentNum(liveEdgeTimeInPeriodUs - bufferDepthUs));
return max(getFirstSegmentNum(), getSegmentNum(liveEdgeTimeInPeriodUs - bufferDepthUs));
}
return getFirstSegmentNum();
}
......
......@@ -15,6 +15,8 @@
*/
package com.google.android.exoplayer2.source.dash;
import static java.lang.Math.max;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.Format;
import com.google.android.exoplayer2.FormatHolder;
......@@ -122,8 +124,7 @@ import java.io.IOException;
@Override
public int skipData(long positionUs) {
int newIndex =
Math.max(currentIndex, Util.binarySearchCeil(eventTimesUs, positionUs, true, false));
int newIndex = max(currentIndex, Util.binarySearchCeil(eventTimesUs, positionUs, true, false));
int skipped = newIndex - currentIndex;
currentIndex = newIndex;
return skipped;
......
......@@ -15,6 +15,8 @@
*/
package com.google.android.exoplayer2.source.dash.manifest;
import static java.lang.Math.min;
import androidx.annotation.Nullable;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.source.dash.DashSegmentIndex;
......@@ -157,9 +159,11 @@ public abstract class SegmentBase {
long durationUs = (duration * C.MICROS_PER_SECOND) / timescale;
long segmentNum = startNumber + timeUs / durationUs;
// Ensure we stay within bounds.
return segmentNum < firstSegmentNum ? firstSegmentNum
: segmentCount == DashSegmentIndex.INDEX_UNBOUNDED ? segmentNum
: Math.min(segmentNum, firstSegmentNum + segmentCount - 1);
return segmentNum < firstSegmentNum
? firstSegmentNum
: segmentCount == DashSegmentIndex.INDEX_UNBOUNDED
? segmentNum
: min(segmentNum, firstSegmentNum + segmentCount - 1);
} else {
// The index cannot be unbounded. Identify the segment using binary search.
long lowIndex = firstSegmentNum;
......
......@@ -21,6 +21,7 @@ import static com.google.android.exoplayer2.source.dash.offline.DashDownloadTest
import static com.google.android.exoplayer2.testutil.CacheAsserts.assertCacheEmpty;
import static com.google.android.exoplayer2.testutil.CacheAsserts.assertCachedData;
import static com.google.common.truth.Truth.assertThat;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import android.content.Context;
import androidx.test.core.app.ApplicationProvider;
......@@ -48,7 +49,6 @@ import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
......@@ -205,8 +205,7 @@ public class DownloadManagerDashTest {
.appendReadData(TestUtil.buildTestData(5))
.endData();
handleDownloadRequest(fakeStreamKey1);
assertThat(downloadInProgressLatch.await(ASSERT_TRUE_TIMEOUT_MS, TimeUnit.MILLISECONDS))
.isTrue();
assertThat(downloadInProgressLatch.await(ASSERT_TRUE_TIMEOUT_MS, MILLISECONDS)).isTrue();
handleRemoveAction();
downloadManagerListener.blockUntilIdleAndThrowAnyFailure();
......
......@@ -15,6 +15,8 @@
*/
package com.google.android.exoplayer2.extractor;
import static java.lang.Math.max;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.util.Util;
......@@ -106,7 +108,7 @@ public class ConstantBitrateSeekMap implements SeekMap {
* @return The stream time in microseconds for the given stream position.
*/
private static long getTimeUsAtPosition(long position, long firstFrameBytePosition, int bitrate) {
return Math.max(0, position - firstFrameBytePosition)
return max(0, position - firstFrameBytePosition)
* C.BITS_PER_BYTE
* C.MICROS_PER_SECOND
/ bitrate;
......
......@@ -15,6 +15,8 @@
*/
package com.google.android.exoplayer2.extractor;
import static java.lang.Math.min;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.upstream.DataReader;
import com.google.android.exoplayer2.util.Assertions;
......@@ -85,8 +87,7 @@ public final class DefaultExtractorInput implements ExtractorInput {
public int skip(int length) throws IOException {
int bytesSkipped = skipFromPeekBuffer(length);
if (bytesSkipped == 0) {
bytesSkipped =
readFromUpstream(scratchSpace, 0, Math.min(length, scratchSpace.length), 0, true);
bytesSkipped = readFromUpstream(scratchSpace, 0, min(length, scratchSpace.length), 0, true);
}
commitBytesRead(bytesSkipped);
return bytesSkipped;
......@@ -96,7 +97,7 @@ public final class DefaultExtractorInput implements ExtractorInput {
public boolean skipFully(int length, boolean allowEndOfInput) throws IOException {
int bytesSkipped = skipFromPeekBuffer(length);
while (bytesSkipped < length && bytesSkipped != C.RESULT_END_OF_INPUT) {
int minLength = Math.min(length, bytesSkipped + scratchSpace.length);
int minLength = min(length, bytesSkipped + scratchSpace.length);
bytesSkipped =
readFromUpstream(scratchSpace, -bytesSkipped, minLength, bytesSkipped, allowEndOfInput);
}
......@@ -127,7 +128,7 @@ public final class DefaultExtractorInput implements ExtractorInput {
}
peekBufferLength += bytesPeeked;
} else {
bytesPeeked = Math.min(length, peekBufferRemainingBytes);
bytesPeeked = min(length, peekBufferRemainingBytes);
}
System.arraycopy(peekBuffer, peekBufferPosition, target, offset, bytesPeeked);
peekBufferPosition += bytesPeeked;
......@@ -217,7 +218,7 @@ public final class DefaultExtractorInput implements ExtractorInput {
* @return The number of bytes skipped.
*/
private int skipFromPeekBuffer(int length) {
int bytesSkipped = Math.min(peekBufferLength, length);
int bytesSkipped = min(peekBufferLength, length);
updatePeekBuffer(bytesSkipped);
return bytesSkipped;
}
......@@ -234,7 +235,7 @@ public final class DefaultExtractorInput implements ExtractorInput {
if (peekBufferLength == 0) {
return 0;
}
int peekBytes = Math.min(peekBufferLength, length);
int peekBytes = min(peekBufferLength, length);
System.arraycopy(peekBuffer, 0, target, offset, peekBytes);
updatePeekBuffer(peekBytes);
return peekBytes;
......
......@@ -15,6 +15,8 @@
*/
package com.google.android.exoplayer2.extractor;
import static java.lang.Math.min;
import androidx.annotation.Nullable;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.Format;
......@@ -44,7 +46,7 @@ public final class DummyTrackOutput implements TrackOutput {
public int sampleData(
DataReader input, int length, boolean allowEndOfInput, @SampleDataPart int sampleDataPart)
throws IOException {
int bytesToSkipByReading = Math.min(readBuffer.length, length);
int bytesToSkipByReading = min(readBuffer.length, length);
int bytesSkipped = input.read(readBuffer, /* offset= */ 0, bytesToSkipByReading);
if (bytesSkipped == C.RESULT_END_OF_INPUT) {
if (allowEndOfInput) {
......
......@@ -15,6 +15,8 @@
*/
package com.google.android.exoplayer2.extractor;
import static java.lang.Math.min;
import com.google.android.exoplayer2.util.Assertions;
/**
......@@ -68,7 +70,7 @@ public final class VorbisBitArray {
*/
public int readBits(int numBits) {
int tempByteOffset = byteOffset;
int bitsRead = Math.min(numBits, 8 - bitOffset);
int bitsRead = min(numBits, 8 - bitOffset);
int returnValue = ((data[tempByteOffset++] & 0xFF) >> bitOffset) & (0xFF >> (8 - bitsRead));
while (bitsRead < numBits) {
returnValue |= (data[tempByteOffset++] & 0xFF) << bitsRead;
......
......@@ -15,6 +15,8 @@
*/
package com.google.android.exoplayer2.extractor.flac;
import static java.lang.Math.max;
import com.google.android.exoplayer2.extractor.BinarySearchSeeker;
import com.google.android.exoplayer2.extractor.ExtractorInput;
import com.google.android.exoplayer2.extractor.FlacFrameReader;
......@@ -55,7 +57,7 @@ import java.io.IOException;
/* floorBytePosition= */ firstFramePosition,
/* ceilingBytePosition= */ inputLength,
/* approxBytesPerFrame= */ flacStreamMetadata.getApproxBytesPerFrame(),
/* minimumSearchRange= */ Math.max(
/* minimumSearchRange= */ max(
FlacConstants.MIN_FRAME_HEADER_SIZE, flacStreamMetadata.minFrameSize));
}
......@@ -81,7 +83,7 @@ import java.io.IOException;
long leftFramePosition = input.getPeekPosition();
input.advancePeekPosition(
Math.max(FlacConstants.MIN_FRAME_HEADER_SIZE, flacStreamMetadata.minFrameSize));
max(FlacConstants.MIN_FRAME_HEADER_SIZE, flacStreamMetadata.minFrameSize));
// Find right frame.
long rightFrameFirstSampleNumber = findNextFrame(input);
......
......@@ -16,6 +16,8 @@
package com.google.android.exoplayer2.extractor.flac;
import static com.google.android.exoplayer2.util.Util.castNonNull;
import static java.lang.Math.max;
import static java.lang.Math.min;
import androidx.annotation.IntDef;
import androidx.annotation.Nullable;
......@@ -224,7 +226,7 @@ public final class FlacExtractor implements Extractor {
}
Assertions.checkNotNull(flacStreamMetadata);
minFrameSize = Math.max(flacStreamMetadata.minFrameSize, FlacConstants.MIN_FRAME_HEADER_SIZE);
minFrameSize = max(flacStreamMetadata.minFrameSize, FlacConstants.MIN_FRAME_HEADER_SIZE);
castNonNull(trackOutput)
.format(flacStreamMetadata.getFormat(streamMarkerAndInfoBlock, id3Metadata));
......@@ -282,7 +284,7 @@ public final class FlacExtractor implements Extractor {
// Skip frame search on the bytes within the minimum frame size.
if (currentFrameBytesWritten < minFrameSize) {
buffer.skipBytes(Math.min(minFrameSize - currentFrameBytesWritten, buffer.bytesLeft()));
buffer.skipBytes(min(minFrameSize - currentFrameBytesWritten, buffer.bytesLeft()));
}
long nextFrameFirstSampleNumber = findFrame(buffer, foundEndOfInput);
......
......@@ -15,6 +15,8 @@
*/
package com.google.android.exoplayer2.extractor.flv;
import static java.lang.Math.max;
import androidx.annotation.IntDef;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.extractor.Extractor;
......@@ -284,7 +286,7 @@ public final class FlvExtractor implements Extractor {
private ParsableByteArray prepareTagData(ExtractorInput input) throws IOException {
if (tagDataSize > tagData.capacity()) {
tagData.reset(new byte[Math.max(tagData.capacity() * 2, tagDataSize)], 0);
tagData.reset(new byte[max(tagData.capacity() * 2, tagDataSize)], 0);
} else {
tagData.setPosition(0);
}
......
......@@ -15,6 +15,9 @@
*/
package com.google.android.exoplayer2.extractor.mkv;
import static java.lang.Math.max;
import static java.lang.Math.min;
import android.util.Pair;
import android.util.SparseArray;
import androidx.annotation.CallSuper;
......@@ -1301,7 +1304,7 @@ public class MatroskaExtractor implements Extractor {
}
if (scratch.capacity() < requiredLength) {
scratch.reset(
Arrays.copyOf(scratch.getData(), Math.max(scratch.getData().length * 2, requiredLength)),
Arrays.copyOf(scratch.getData(), max(scratch.getData().length * 2, requiredLength)),
scratch.limit());
}
input.readFully(scratch.getData(), scratch.limit(), requiredLength - scratch.limit());
......@@ -1600,7 +1603,7 @@ public class MatroskaExtractor implements Extractor {
*/
private void writeToTarget(ExtractorInput input, byte[] target, int offset, int length)
throws IOException {
int pendingStrippedBytes = Math.min(length, sampleStrippedBytes.bytesLeft());
int pendingStrippedBytes = min(length, sampleStrippedBytes.bytesLeft());
input.readFully(target, offset + pendingStrippedBytes, length - pendingStrippedBytes);
if (pendingStrippedBytes > 0) {
sampleStrippedBytes.readBytes(target, offset, pendingStrippedBytes);
......@@ -1616,7 +1619,7 @@ public class MatroskaExtractor implements Extractor {
int bytesWritten;
int strippedBytesLeft = sampleStrippedBytes.bytesLeft();
if (strippedBytesLeft > 0) {
bytesWritten = Math.min(length, strippedBytesLeft);
bytesWritten = min(length, strippedBytesLeft);
output.sampleData(sampleStrippedBytes, bytesWritten);
} else {
bytesWritten = output.sampleData(input, length, false);
......@@ -1747,7 +1750,7 @@ public class MatroskaExtractor implements Extractor {
return array;
} else {
// Double the size to avoid allocating constantly if the required length increases gradually.
return new int[Math.max(array.length * 2, length)];
return new int[max(array.length * 2, length)];
}
}
......
......@@ -15,6 +15,8 @@
*/
package com.google.android.exoplayer2.extractor.mp3;
import static java.lang.Math.max;
import androidx.annotation.Nullable;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.audio.MpegAudioUtil;
......@@ -68,7 +70,7 @@ import com.google.android.exoplayer2.util.Util;
timesUs[index] = (index * durationUs) / entryCount;
// Ensure positions do not fall within the frame containing the VBRI header. This constraint
// will normally only apply to the first entry in the table.
positions[index] = Math.max(position, minPosition);
positions[index] = max(position, minPosition);
int segmentSize;
switch (entrySize) {
case 1:
......
......@@ -17,6 +17,7 @@ package com.google.android.exoplayer2.extractor.mp4;
import static com.google.android.exoplayer2.util.Assertions.checkNotNull;
import static com.google.android.exoplayer2.util.MimeTypes.getMimeTypeFromMp4ObjectType;
import static java.lang.Math.max;
import android.util.Pair;
import androidx.annotation.Nullable;
......@@ -647,7 +648,7 @@ import org.checkerframework.checker.nullness.compatqual.NullableType;
long ptsUs = Util.scaleLargeTimestamp(pts, C.MICROS_PER_SECOND, track.movieTimescale);
long timeInSegmentUs =
Util.scaleLargeTimestamp(
Math.max(0, timestamps[j] - editMediaTime), C.MICROS_PER_SECOND, track.timescale);
max(0, timestamps[j] - editMediaTime), C.MICROS_PER_SECOND, track.timescale);
editedTimestamps[sampleIndex] = ptsUs + timeInSegmentUs;
if (copyMetadata && editedSizes[sampleIndex] > editedMaximumSize) {
editedMaximumSize = sizes[j];
......
......@@ -15,6 +15,9 @@
*/
package com.google.android.exoplayer2.extractor.mp4;
import static java.lang.Math.max;
import static java.lang.Math.min;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.util.Util;
......@@ -88,11 +91,11 @@ import com.google.android.exoplayer2.util.Util;
long sampleOffset = chunkOffsets[chunkIndex];
while (chunkSamplesRemaining > 0) {
int bufferSampleCount = Math.min(maxSampleCount, chunkSamplesRemaining);
int bufferSampleCount = min(maxSampleCount, chunkSamplesRemaining);
offsets[newSampleIndex] = sampleOffset;
sizes[newSampleIndex] = fixedSampleSize * bufferSampleCount;
maximumSize = Math.max(maximumSize, sizes[newSampleIndex]);
maximumSize = max(maximumSize, sizes[newSampleIndex]);
timestamps[newSampleIndex] = (timestampDeltaInTimeUnits * originalSampleIndex);
flags[newSampleIndex] = C.BUFFER_FLAG_KEY_FRAME;
......
......@@ -16,6 +16,7 @@
package com.google.android.exoplayer2.extractor.mp4;
import static com.google.android.exoplayer2.extractor.mp4.AtomParsers.parseTraks;
import static java.lang.Math.max;
import android.util.Pair;
import android.util.SparseArray;
......@@ -515,7 +516,7 @@ public class FragmentedMp4Extractor implements Extractor {
TrackBundle trackBundle = new TrackBundle(extractorOutput.track(i, track.type));
trackBundle.init(sampleTable, getDefaultSampleValues(defaultSampleValuesArray, track.id));
trackBundles.put(track.id, trackBundle);
durationUs = Math.max(durationUs, track.durationUs);
durationUs = max(durationUs, track.durationUs);
}
maybeInitExtraTracks();
extractorOutput.endTracks();
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment