From 77d7160432d4ea62081e0371b37165f036d1aba8 Mon Sep 17 00:00:00 2001 From: Yuriy Liskov Date: Sun, 29 Nov 2026 23:43:00 +0200 Subject: [PATCH 1/5] fix(ErrorFixerController): skip fix on tickle if the video is paused --- .../app/models/playback/controllers/ErrorFixerController.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/common/src/main/java/com/liskovsoft/smartyoutubetv2/common/app/models/playback/controllers/ErrorFixerController.java b/common/src/main/java/com/liskovsoft/smartyoutubetv2/common/app/models/playback/controllers/ErrorFixerController.java index 7954a86eeb0..9c3a810fbec 100644 --- a/common/src/main/java/com/liskovsoft/smartyoutubetv2/common/app/models/playback/controllers/ErrorFixerController.java +++ b/common/src/main/java/com/liskovsoft/smartyoutubetv2/common/app/models/playback/controllers/ErrorFixerController.java @@ -52,7 +52,7 @@ public void onTickle() { private void handleUnthrownErrorsIfNeeded() { // Handle only those errors where the video not playing but not sign of buffering - if (getPlayer() == null || mBufferingDetector.isBuffering()) { + if (getPlayer() == null || !getPlayer().getPlayWhenReady() || mBufferingDetector.isBuffering()) { return; } From 716105babbe6ae5ef71c8e8b602a096f89e3b649 Mon Sep 17 00:00:00 2001 From: Yuriy Liskov Date: Mon, 30 Nov 2026 00:05:05 +0200 Subject: [PATCH 2/5] fix(SABR): live stability and SABR module updates from electriceel fork (part 1) Co-authored-by: edgan <3506737+edgan@users.noreply.github.com> --- .../source/sabr/DefaultSabrChunkSource.java | 571 +++++++++++++++++- .../source/sabr/GoogleVideoHosts.java | 284 +++++++++ .../source/sabr/SabrLivePrefetcher.java | 390 ++++++++++++ .../source/sabr/SabrMediaSource.java | 11 +- .../source/sabr/SabrRefusedRequest.java | 89 +++ .../source/sabr/SabrSampleDeduplicator.java | 142 +++++ .../source/sabr/ValidatedNetwork.java | 30 + .../source/sabr/manifest/SabrCdnSelector.java | 208 ++----- .../source/sabr/manifest/SabrManifest.java | 440 +++++++++++++- .../sabr/manifest/SabrManifestParser.java | 176 +++++- .../source/sabr/manifest/SabrSession.java | 37 ++ .../source/sabr/parser/SabrProcessor.java | 87 ++- .../source/sabr/parser/SabrStream.java | 458 ++++++++++++-- .../adapter/SabrFragmentedMp4Adapter.java | 19 + .../parser/adapter/SabrMatroskaAdapter.java | 23 +- .../parser/exceptions/BrokenPartError.java | 17 + .../exceptions/BrokenResponseError.java | 76 +++ .../exceptions/MediaSegmentMismatchError.java | 19 + .../sabr/parser/exceptions/PoTokenError.java | 30 + .../parser/exceptions/SabrBackoffError.java | 2 +- .../parser/exceptions/SabrProtocolError.java | 95 +++ .../exceptions/SabrReloadPlayerError.java | 2 +- .../exceptions/SabrStreamConsumedError.java | 5 +- .../parser/exceptions/UnknownPartError.java | 13 + .../sabr/parser/misc/SabrExtractorInput.java | 159 ++++- .../source/sabr/parser/ump/UMPPart.java | 7 + .../sabr/DefaultSabrChunkSourceLiveTest.java | 289 +++++++++ .../source/sabr/GoogleVideoHostsTest.java | 117 ++++ .../source/sabr/SabrLivePrefetcherTest.java | 422 +++++++++++++ .../source/sabr/SabrRefusedRequestTest.java | 70 +++ .../sabr/SabrSampleDeduplicatorTest.java | 161 +++++ .../sabr/manifest/SabrCdnSelectorTest.java | 132 ++-- .../manifest/SabrManifestSessionTest.java | 64 ++ .../parser/SabrStreamBrokenResponseTest.java | 184 ++++++ .../sabr/parser/SabrStreamLiveTest.java | 148 +++++ .../adapter/SabrFragmentedMp4AdapterTest.java | 111 ++++ .../adapter/SabrMatroskaAdapterLiveTest.java | 170 ++++++ .../adapter/SabrMatroskaAdapterTest.java | 84 +++ .../exceptions/SabrProtocolErrorTest.java | 55 ++ .../parser/misc/SabrExtractorInputTest.java | 416 +++++++++++++ 40 files changed, 5434 insertions(+), 379 deletions(-) create mode 100644 exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/GoogleVideoHosts.java create mode 100644 exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/SabrLivePrefetcher.java create mode 100644 exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/SabrRefusedRequest.java create mode 100644 exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/SabrSampleDeduplicator.java create mode 100644 exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/ValidatedNetwork.java create mode 100644 exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/manifest/SabrSession.java create mode 100644 exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/parser/exceptions/BrokenPartError.java create mode 100644 exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/parser/exceptions/BrokenResponseError.java create mode 100644 exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/parser/exceptions/MediaSegmentMismatchError.java create mode 100644 exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/parser/exceptions/PoTokenError.java create mode 100644 exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/parser/exceptions/SabrProtocolError.java create mode 100644 exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/parser/exceptions/UnknownPartError.java create mode 100644 exoplayer-amzn-2.10.6/library/sabr/src/test/java/com/google/android/exoplayer2/source/sabr/DefaultSabrChunkSourceLiveTest.java create mode 100644 exoplayer-amzn-2.10.6/library/sabr/src/test/java/com/google/android/exoplayer2/source/sabr/GoogleVideoHostsTest.java create mode 100644 exoplayer-amzn-2.10.6/library/sabr/src/test/java/com/google/android/exoplayer2/source/sabr/SabrLivePrefetcherTest.java create mode 100644 exoplayer-amzn-2.10.6/library/sabr/src/test/java/com/google/android/exoplayer2/source/sabr/SabrRefusedRequestTest.java create mode 100644 exoplayer-amzn-2.10.6/library/sabr/src/test/java/com/google/android/exoplayer2/source/sabr/SabrSampleDeduplicatorTest.java create mode 100644 exoplayer-amzn-2.10.6/library/sabr/src/test/java/com/google/android/exoplayer2/source/sabr/manifest/SabrManifestSessionTest.java create mode 100644 exoplayer-amzn-2.10.6/library/sabr/src/test/java/com/google/android/exoplayer2/source/sabr/parser/SabrStreamBrokenResponseTest.java create mode 100644 exoplayer-amzn-2.10.6/library/sabr/src/test/java/com/google/android/exoplayer2/source/sabr/parser/SabrStreamLiveTest.java create mode 100644 exoplayer-amzn-2.10.6/library/sabr/src/test/java/com/google/android/exoplayer2/source/sabr/parser/adapter/SabrFragmentedMp4AdapterTest.java create mode 100644 exoplayer-amzn-2.10.6/library/sabr/src/test/java/com/google/android/exoplayer2/source/sabr/parser/adapter/SabrMatroskaAdapterLiveTest.java create mode 100644 exoplayer-amzn-2.10.6/library/sabr/src/test/java/com/google/android/exoplayer2/source/sabr/parser/adapter/SabrMatroskaAdapterTest.java create mode 100644 exoplayer-amzn-2.10.6/library/sabr/src/test/java/com/google/android/exoplayer2/source/sabr/parser/exceptions/SabrProtocolErrorTest.java create mode 100644 exoplayer-amzn-2.10.6/library/sabr/src/test/java/com/google/android/exoplayer2/source/sabr/parser/misc/SabrExtractorInputTest.java diff --git a/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/DefaultSabrChunkSource.java b/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/DefaultSabrChunkSource.java index 993c734ed1b..a80a43a26a7 100644 --- a/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/DefaultSabrChunkSource.java +++ b/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/DefaultSabrChunkSource.java @@ -13,6 +13,7 @@ import com.google.android.exoplayer2.extractor.TrackOutput; import com.google.android.exoplayer2.extractor.rawcc.RawCcExtractor; import com.google.android.exoplayer2.source.BehindLiveWindowException; +import com.google.android.exoplayer2.source.chunk.BaseMediaChunkOutput; import com.google.android.exoplayer2.source.chunk.Chunk; import com.google.android.exoplayer2.source.chunk.ChunkExtractorWrapper; import com.google.android.exoplayer2.source.chunk.ChunkHolder; @@ -29,12 +30,17 @@ import com.google.android.exoplayer2.source.sabr.parser.adapter.SabrFragmentedMp4Adapter; import com.google.android.exoplayer2.source.sabr.parser.adapter.SabrMatroskaAdapter; import com.google.android.exoplayer2.source.sabr.parser.SabrStream; -import com.google.android.exoplayer2.source.sabr.parser.exceptions.SabrPropagationError; +import com.google.android.exoplayer2.source.sabr.parser.exceptions.BrokenResponseError; +import com.google.android.exoplayer2.source.sabr.parser.exceptions.PoTokenError; +import com.google.android.exoplayer2.source.sabr.parser.exceptions.SabrReloadPlayerError; +import com.google.android.exoplayer2.source.sabr.parser.exceptions.SabrBackoffError; +import com.google.android.exoplayer2.source.sabr.parser.exceptions.SabrProtocolError; import com.google.android.exoplayer2.source.sabr.parser.models.AudioSelector; import com.google.android.exoplayer2.source.sabr.parser.models.CaptionSelector; import com.google.android.exoplayer2.source.sabr.parser.models.FormatSelector; import com.google.android.exoplayer2.source.sabr.parser.models.VideoSelector; import com.google.android.exoplayer2.source.sabr.protos.misc.FormatId; +import com.google.android.exoplayer2.source.sabr.protos.videostreaming.MediaHeader; import com.google.android.exoplayer2.trackselection.TrackSelection; import com.google.android.exoplayer2.upstream.DataSource; import com.google.android.exoplayer2.upstream.DataSpec; @@ -46,6 +52,7 @@ import com.google.android.exoplayer2.util.MimeTypes; import java.io.IOException; +import java.io.InterruptedIOException; import java.net.SocketTimeoutException; import java.util.ArrayList; import java.util.Collections; @@ -85,7 +92,7 @@ public SabrChunkSource createSabrChunkSource( if (transferListener != null) { dataSource.addTransferListener(transferListener); } - return new DefaultSabrChunkSource( + DefaultSabrChunkSource source = new DefaultSabrChunkSource( manifestLoaderErrorThrower, manifest, periodIndex, @@ -98,6 +105,8 @@ public SabrChunkSource createSabrChunkSource( enableEventMessageTrack, closedCaptionFormats, playerEmsgHandler); + source.enableLivePrefetch(dataSourceFactory, transferListener); + return source; } } @@ -105,6 +114,21 @@ public SabrChunkSource createSabrChunkSource( private static final String TAG = DefaultSabrChunkSource.class.getSimpleName(); private static final long END_OF_STREAM_SEEK_TOLERANCE_US = 500_000L; // 0.5 seconds private static final long NEAR_END_TOLERANCE_US = 700_000L; // 0.7 seconds + /** + * Of a media segment, about: the first media chunk's length, before any segment of its format is received + */ + private static final long DEFAULT_SEGMENT_DURATION_MS = 5_000; + /** + * Of a live stream at its head, the wait for its next segment (see maybeWaitForLiveSegment) + */ + private static final long MIN_LIVE_WAIT_MS = 250; + private static final long MAX_LIVE_WAIT_MS = 10_000; + /** + * The longest wait the server asks for before an init request is sent again (see maybeWaitForInit): a longer one fails the load + * (see SabrExtractorInput#MIN_SWALLOW_BACKOFF_MS) + */ + private static final long MAX_INIT_WAIT_MS = 15_000; + @Nullable private static volatile LiveHeadWaitListener liveHeadWaitListener; private final LoaderErrorThrower manifestLoaderErrorThrower; private final int[] adaptationSetIndices; private final int trackType; @@ -124,9 +148,44 @@ public SabrChunkSource createSabrChunkSource( private long liveEdgeTimeUs; @Nullable private final SabrStream sabrStream; + @Nullable private final SabrSampleDeduplicator sampleDeduplicator; private final Map sabrHeaders; private int nexChunkIdx = -1; private long pendingSeekTimeUs = C.TIME_UNSET; + /** + * Of a live stream: the next media chunk's request isn't sent before (elapsed realtime), see maybeWaitForLiveSegment + */ + private long nextLiveLoadTimeMs = C.TIME_UNSET; + /** + * Of a stream that isn't live: the next init chunk's request isn't sent before (elapsed realtime), see maybeWaitForInit + */ + private long nextInitLoadTimeMs = C.TIME_UNSET; + /** + * The stream's NextRequestPolicy count when the last init chunk's request was made (see SabrStream#getNextRequestPolicyCount) + */ + private int initRequestPolicyCount; + /** + * Of the last media chunk's request: its format's itag and the sequence number of the segment received last before it + */ + private int liveRequestItag = -1; + private long liveRequestSequenceNumber = -1; + /** + * Of a live stream with short segments (see SabrLivePrefetcher), null otherwise + */ + @Nullable private SabrLivePrefetcher livePrefetcher; + /** + * How many segments of the format the last response held (see maybePrefetch): 1 till one says, and after a seek + */ + private int liveSegmentsPerResponse = 1; + /** + * The newest segment's number when the last chunk was made, -1 for none since a seek + */ + private long livePrefetchSequenceNumber = -1; + /** + * Of the session the last chunk's request was made with (see SabrManifest#getSessionId): a track loads one chunk at a time, so + * a failed load is that chunk's + */ + private int chunkSessionId; /** * @param manifestLoaderErrorThrower Throws errors affecting loading of manifests. @@ -200,6 +259,17 @@ public DefaultSabrChunkSource( stream); } this.sabrStream = stream; + this.sampleDeduplicator = stream != null ? new SabrSampleDeduplicator(stream) : null; + } + + /** + * Of a live stream with segments of up to 2 s: the next ones are asked for while the player loads one (see SabrLivePrefetcher) + */ + /* package */ void enableLivePrefetch(DataSource.Factory dataSourceFactory, @Nullable TransferListener transferListener) { + if (sabrStream != null && manifest.isLive() + && manifest.liveSegmentTargetDurationSec <= SabrLivePrefetcher.MAX_SEGMENT_DURATION_SEC) { + livePrefetcher = new SabrLivePrefetcher(dataSourceFactory, transferListener); + } } @Override @@ -270,7 +340,11 @@ public int getPreferredQueueSize(long playbackPositionUs, List liveRequestSequenceNumber) { + return; // a new segment came + } + + int backoffMs = sabrStream.getBackoffTimeMs(); + long waitMs = backoffMs > 0 + ? Math.min(backoffMs, MAX_LIVE_WAIT_MS) + : Math.max(MIN_LIVE_WAIT_MS, manifest.liveSegmentTargetDurationSec * 1_000L / 4); + nextLiveLoadTimeMs = SystemClock.elapsedRealtime() + waitMs; + Log.d(TAG, "No new live segment: the next request waits " + waitMs + " ms"); + + LiveHeadWaitListener listener = liveHeadWaitListener; + + if (listener != null) { + listener.onLiveHeadWait(trackType, waitMs); + } + } + + /** + * Told when a live stream's request for the segment after its newest got none, the segment not there yet, and the next request + * waits (see maybeWaitForLiveSegment), e.g. for the app's diagnostics: a start at the head that waited for the stream had no row + * for it. On the loader's thread. + */ + public interface LiveHeadWaitListener { + /** + * @param trackType the chunk source's, e.g. C#TRACK_TYPE_VIDEO + * @param waitMs how long the next request waits + */ + void onLiveHeadWait(int trackType, long waitMs); + } + + public static void setLiveHeadWaitListener(@Nullable LiveHeadWaitListener listener) { + liveHeadWaitListener = listener; + } + + /** + * Of a live stream with short segments: the request for the next segment is served by its response asked for ahead, if any, and + * the ones after it are asked for, up to the head (see SabrLivePrefetcher) + * + * @return the data source of the chunk's request + */ + private DataSource maybePrefetch(int trackType, int iTag, boolean isSeek) { + SabrLivePrefetcher prefetcher = livePrefetcher; + + if (prefetcher == null || sabrStream == null) { + return dataSource; + } + + if (isSeek) { + prefetcher.clear(); // another time + liveSegmentsPerResponse = 1; + livePrefetchSequenceNumber = -1; + + // A retry at the head waits (see newMediaChunk): nothing after it exists yet. Nor of 1 s segments: a response holds the + // ones after the one asked for too (see prefetchAhead), so the seek's own brings the next ones, and asking for them as well + // would load them twice while the start waits + if (nextLiveLoadTimeMs != C.TIME_UNSET || manifest.liveSegmentTargetDurationSec < 2) { + return dataSource; + } + + // Which segment the seek brings first isn't known till it comes. Its number isn't worked out from the target's time: the + // head's time isn't known here, and from the target duration alone the number drifts (2 s segments of a 29.97 fps stream + // are 2.002 s), while one off asks for a segment the player doesn't read. The ones after it are asked for as soon as its + // header is read, while its media loads, not once the chunk is loaded: a live start fetched the 2 s segments it needed one + // after another, at about a second or more each (CQHM6BGP hMzTblhfTvc: ready at 4068 ms, after a second audio segment + // that took 1771 ms). + SabrManifest seekManifest = manifest; + int bitrate = trackSelection.getSelectedFormat().bitrate; + return new SabrLivePrefetcher.FirstSegmentDataSource(dataSource, + () -> prefetchAfterFirstSegment(prefetcher, seekManifest, trackType, iTag, bitrate)); + } + + MediaHeader last = sabrStream.getInitializedFormat(iTag); + + if (last == null || !sabrStream.hasSegmentStartTime(iTag) || !last.hasSequenceNumber()) { + return dataSource; + } + + updateLiveSegmentsPerResponse(last.getSequenceNumber()); + DataSource chunkDataSource = prefetcher.dataSourceFor(iTag, last.getSequenceNumber() + 1L, dataSource); + long targetDurationMs = manifest.liveSegmentTargetDurationSec * 1_000L; + int segmentsPerResponse = liveSegmentsPerResponse; + int maxPrefetchBytes = SabrLivePrefetcher.getMaxResponseBytes( + trackSelection.getSelectedFormat().bitrate, targetDurationMs, segmentsPerResponse); + // The one after last is the player's own request + prefetchAhead(prefetcher, manifest, trackType, iTag, last, 1, segmentsPerResponse, maxPrefetchBytes); + + return chunkDataSource; + } + + /** + * On a seek's chunk's loading thread, before each read (see SabrLivePrefetcher.FirstSegmentDataSource): once the seek's first + * segment came, the ones after it are asked for, the player's next request first + * + * @return whether it came + */ + private boolean prefetchAfterFirstSegment(SabrLivePrefetcher prefetcher, SabrManifest manifest, int trackType, int iTag, + int bitrate) { + SabrStream stream = Assertions.checkNotNull(sabrStream); + // Its header, read before its media: the segment ended only at its MEDIA_END, about when the player asks for the next itself + MediaHeader first = stream.getNewestLiveHeader(iTag); + + if (first == null || !first.hasSequenceNumber()) { + return false; + } + + int maxPrefetchBytes = SabrLivePrefetcher.getMaxResponseBytes(bitrate, manifest.liveSegmentTargetDurationSec * 1_000L, 1); + prefetchAhead(prefetcher, manifest, trackType, iTag, first, 0, 1, maxPrefetchBytes); + + return true; + } + + /** + * Asks for PREFETCH_COUNT segments after the newest one received, none past the head + * + * @param firstStep of the first one asked for, in responses past the one after last: 0 for that one + */ + private void prefetchAhead(SabrLivePrefetcher prefetcher, SabrManifest manifest, int trackType, int iTag, MediaHeader last, + int firstStep, int segmentsPerResponse, int maxPrefetchBytes) { + long head = Assertions.checkNotNull(sabrStream).getLiveHeadSequenceNumber(); + long targetDurationMs = manifest.liveSegmentTargetDurationSec * 1_000L; + + for (int k = firstStep; k < firstStep + SabrLivePrefetcher.PREFETCH_COUNT; k++) { + // A response holds the segments after the one asked for too (3 behind the head of a 1 s stream): the ones asked for ahead + // are as far apart. One by one, each segment came in 3 responses, and 2 of them weren't read: 3x the bytes for as long as + // the player stayed behind the head (2026-11-15). + long offset = (long) k * segmentsPerResponse; + long sequenceNumber = last.getSequenceNumber() + 1L + offset; + + if (head < 0 || sequenceNumber > head) { + break; // a later one would be held until it exists + } + + // As if the segment before it were the newest one received: its number, and its start about where it should be + MediaHeader before = last.toBuilder() + .setSequenceNumber((int) (sequenceNumber - 1)) + .setStartMs(last.getStartMs() + offset * targetDurationMs) + .build(); + DataSpec dataSpec = new DataSpec( + Uri.parse(manifest.getRequestUrl(trackType)), + DataSpec.HTTP_METHOD_POST, + manifest.createLiveRequestAfter(trackType, before).toByteArray(), + 0, 0, C.LENGTH_UNSET, null, 0, sabrHeaders); + prefetcher.prefetch(iTag, sequenceNumber, dataSpec, maxPrefetchBytes); + } + } + + /** + * The segments the last chunk brought: since the last chunk was made, one loaded (a track loads one at a time). One that brought + * none (failed, or at the head) says nothing. + */ + private void updateLiveSegmentsPerResponse(long lastSequenceNumber) { + long previous = livePrefetchSequenceNumber; + livePrefetchSequenceNumber = lastSequenceNumber; + + if (previous != -1 && lastSequenceNumber > previous) { + liveSegmentsPerResponse = (int) Math.min(lastSequenceNumber - previous, SabrLivePrefetcher.MAX_SEGMENTS_PER_RESPONSE); + } + } + + private long getLastSequenceNumber(int itag) { + MediaHeader mediaHeader = sabrStream != null ? sabrStream.getInitializedFormat(itag) : null; + + return mediaHeader != null && mediaHeader.hasSequenceNumber() ? mediaHeader.getSequenceNumber() : -1; + } + + private void resetSampleDeduplicator() { + if (sampleDeduplicator != null) { + sampleDeduplicator.reset(); + } } private static boolean isEndpointConnectionFailure(Chunk chunk, Exception error) { @@ -535,6 +887,42 @@ private static boolean isEndpointConnectionFailure(Chunk chunk, Exception error) return chunk.bytesLoaded() == 0 || hasCause(error, SocketTimeoutException.class); } + /** + * Of the chunk's response, e.g. "application/vnd.yt-ump" for "Content-Type": null when it had none. The name in any case (OkHttp + * tells it in lower case). + */ + @Nullable + private static String getResponseHeader(Chunk chunk, String name) { + Map> headers = chunk.getResponseHeaders(); + + if (headers == null) { + return null; + } + + for (Map.Entry> header : headers.entrySet()) { + if (name.equalsIgnoreCase(header.getKey()) && header.getValue() != null && !header.getValue().isEmpty()) { + return header.getValue().get(0); + } + } + + return null; + } + + /** + * -1 for none, or what isn't a number + */ + private static long parseLength(@Nullable String contentLength) { + if (contentLength == null) { + return -1; + } + + try { + return Long.parseLong(contentLength.trim()); + } catch (NumberFormatException e) { + return -1; + } + } + private static boolean hasCause(Throwable error, Class type) { for (Throwable cause = error; cause != null; cause = cause.getCause()) { if (type.isInstance(cause)) { @@ -612,6 +1000,7 @@ protected Chunk newInitializationChunk( // MOD: add protobuf data //DataSpec dataSpec = new DataSpec(requestUri.resolveUri(baseUrl), requestUri.start, // requestUri.length, representationHolder.representation.getCacheKey()); + chunkSessionId = manifest.getSessionId(); // before the request is made: one swapped in meanwhile is the next one's DataSpec dataSpec = new DataSpec( //Uri.parse(sabrStream.getRequestUrl()), Uri.parse(manifest.getRequestUrl(trackType)), @@ -626,7 +1015,20 @@ protected Chunk newInitializationChunk( 0, sabrHeaders); Log.e(TAG, "Load init chunk: track=" + trackType + ", rn=" + manifest.getSabrRequestNumber()); - return new InitializationChunk(dataSource, dataSpec, trackFormat, + + if (sabrStream != null) { + sabrStream.setInitRequest(true); // read up to the init segment only (see SabrExtractorInput) + initRequestPolicyCount = sabrStream.getNextRequestPolicyCount(); + } + + // The server asked to wait before it's asked again (see maybeWaitForInit). The chunk is loaded now, its request waits. + DataSource chunkDataSource = dataSource; + if (nextInitLoadTimeMs != C.TIME_UNSET) { + chunkDataSource = new DelayedOpenDataSource(dataSource, nextInitLoadTimeMs); + nextInitLoadTimeMs = C.TIME_UNSET; + } + + return new InitializationChunk(chunkDataSource, dataSpec, trackFormat, trackSelectionReason, trackSelectionData, representationHolder.extractorWrapper); } @@ -654,6 +1056,10 @@ protected Chunk newMediaChunk( } SabrStream sabrStream = Assertions.checkNotNull(this.sabrStream); + sabrStream.setInitRequest(false); + // A canceled load's (its call aborted by the seek, "Socket closed", see CancelableCalls in the app): not the new chunk's, whose + // completion would take it as its own, and leave the media network for a chunk that came empty + sabrStream.pollResponseError(); boolean isInit = nexChunkIdx == -1; FormatId formatId = formatSelector.getSelectedFormatId(); int iTag = formatId != null ? formatId.getItag() : -1; @@ -676,9 +1082,28 @@ protected Chunk newMediaChunk( //long durationMs = sabrStream.getSegmentDurationMs(trackType); long startTimeMs = sabrStream.getSegmentStartTimeMs(iTag); long durationMs = sabrStream.getSegmentDurationMs(iTag); + + // FIX: no media segment of the format received yet (the init chunk stops at its init segment, see SabrExtractorInput): + // the first media chunk is given a segment's length. Unset times overflow the buffered duration the player computes from + // them, and it never loads the video again. + if (durationMs <= 0) { + durationMs = DEFAULT_SEGMENT_DURATION_MS; + } + boolean isSabrTimeSet = startTimeMs >= 0 && durationMs > 0; - long startTimeUs = isSabrTimeSet ? startTimeMs * 1_000L : C.TIME_UNSET; + // The server's times are the media's: a live stream's timeline starts at its start segment's (see SabrManifestParser), a + // video's at 0 + long presentationTimeOffsetUs = representation.presentationTimeOffsetUs; + long startTimeUs = isSabrTimeSet ? startTimeMs * 1_000L - presentationTimeOffsetUs : C.TIME_UNSET; + + // FIX: of a live stream, with no segment of the format received since the seek (see SabrStream#reset): the time asked for, + // not the media's 0, which is far before the timeline's start (a negative buffered duration) + if (presentationTimeOffsetUs != 0 && !sabrStream.hasSegmentStartTime(iTag)) { + long requestedTimeUs = seekTimeUs != C.TIME_UNSET ? seekTimeUs : pendingSeekTimeUs; + startTimeUs = requestedTimeUs != C.TIME_UNSET ? requestedTimeUs : 0; + } + long endTimeUs = isSabrTimeSet ? startTimeUs + (durationMs * 1_000L) : C.TIME_UNSET; long clippedEndTimeUs = C.TIME_UNSET; int segmentCount = C.INDEX_UNSET; // TODO: replace with SABR value? @@ -687,13 +1112,31 @@ protected Chunk newMediaChunk( //String baseUrl = representation.baseUrl; //baseUrl = Utils.updateQuery(baseUrl, "rn", sabrStream.getIncSabrRequestNumber()); + int sessionId = manifest.getSessionId(); // before the request is made: one swapped in meanwhile is the next one's + if (sessionId != chunkSessionId && livePrefetcher != null) { + livePrefetcher.clear(); // asked for with the session before + } + chunkSessionId = sessionId; + + // A live stream at its head: the next segment doesn't exist yet. The chunk is loaded now, its request waits: a chunk source + // that gives none isn't asked again until a load ends (the player stalled). Also a seek retried after an answer with no media + // (see getNextChunk): the seek's target may be the head's next segment. + DataSource chunkDataSource = maybePrefetch(trackType, iTag, isSeek); + if (nextLiveLoadTimeMs != C.TIME_UNSET) { + if (chunkDataSource == dataSource) { + chunkDataSource = new DelayedOpenDataSource(dataSource, nextLiveLoadTimeMs); + } + nextLiveLoadTimeMs = C.TIME_UNSET; + } + DataSpec dataSpec = new DataSpec( //Uri.parse(sabrStream.getRequestUrl()), Uri.parse(manifest.getRequestUrl(trackType)), //segmentUri.resolveUri(baseUrl), DataSpec.HTTP_METHOD_POST, //sabrStream.createVideoPlaybackAbrRequest(trackType, false).toByteArray(), - manifest.createVideoPlaybackAbrRequest(trackType, false, seekTimeUs).toByteArray(), + manifest.createVideoPlaybackAbrRequest(trackType, false, + seekTimeUs != C.TIME_UNSET ? seekTimeUs + presentationTimeOffsetUs : C.TIME_UNSET).toByteArray(), 0, 0, C.LENGTH_UNSET, //segmentUri.start, //segmentUri.start, @@ -701,11 +1144,16 @@ protected Chunk newMediaChunk( representation.getCacheKey(), 0, sabrHeaders); - long sampleOffsetUs = -representation.presentationTimeOffsetUs; + if (manifest.isLive()) { + liveRequestItag = iTag; + liveRequestSequenceNumber = !isSeek && sabrStream.hasSegmentStartTime(iTag) ? getLastSequenceNumber(iTag) : -1; + } + + long sampleOffsetUs = -presentationTimeOffsetUs; Log.e(TAG, "Load media chunk: track=" + trackType + ", rn=" + manifest.getSabrRequestNumber() + ", startTimeMs=" + startTimeMs + ", backoffTimeMs=" + sabrStream.getBackoffTimeMs()); return new ContainerMediaChunk( - dataSource, + chunkDataSource, dataSpec, trackFormat, trackSelectionReason, @@ -717,7 +1165,13 @@ protected Chunk newMediaChunk( firstSegmentNum, segmentCount, sampleOffsetUs, - representationHolder.extractorWrapper); + representationHolder.extractorWrapper) { + @Override + protected ChunkExtractorWrapper.TrackOutputProvider getTrackOutputProvider(BaseMediaChunkOutput output) { + // FIX: a response that ends mid-segment makes the server send that segment again + return sampleDeduplicator != null ? sampleDeduplicator.wrap(this, output) : output; + } + }; //if (representationHolder.extractorWrapper == null) { // long endTimeUs = representationHolder.getSegmentEndTimeUs(firstSegmentNum); @@ -865,6 +1319,97 @@ private static FormatSelector createFormatSelector(int trackType, TrackSelection // } //} + /** + * Loaded while a new session is asked for (see SabrManifest#requestSessionRefresh): it makes no request, and ends once the session + * is in or the ask failed. The next chunk is then made with what there is. A chunk source that gives no chunk isn't asked again + * until a load ends, and the track would load no more. + */ + /* package */ static final class SessionWaitChunk extends Chunk { + private static final long POLL_MS = 50; + private final SabrManifest manifest; + private volatile boolean canceled; + + SessionWaitChunk(DataSource dataSource, Format trackFormat, int trackSelectionReason, @Nullable Object trackSelectionData, + SabrManifest manifest) { + super(dataSource, new DataSpec(Uri.EMPTY), C.DATA_TYPE_UNKNOWN, trackFormat, trackSelectionReason, trackSelectionData, + C.TIME_UNSET, C.TIME_UNSET); + this.manifest = manifest; + } + + @Override + public void cancelLoad() { + canceled = true; + } + + /** + * @throws InterruptedException canceled (the loader interrupts its thread), e.g. by a seek + */ + @Override + public void load() throws InterruptedException { + // It times out (see SabrManifest#isSessionRefreshPending) + while (!canceled && manifest.isSessionRefreshPending()) { + Thread.sleep(POLL_MS); + } + } + } + + /** + * Opens no earlier than a time (elapsed realtime): a live stream's request for a segment that doesn't exist yet (see + * maybeWaitForLiveSegment), or an init request the server asked to wait for (see maybeWaitForInit). The wait ends early when the + * load is canceled (the loader interrupts its thread). + */ + /* package */ static final class DelayedOpenDataSource implements DataSource { + private final DataSource upstream; + private final long openNotBeforeMs; + + DelayedOpenDataSource(DataSource upstream, long openNotBeforeMs) { + this.upstream = upstream; + this.openNotBeforeMs = openNotBeforeMs; + } + + @Override + public void addTransferListener(TransferListener transferListener) { + upstream.addTransferListener(transferListener); + } + + @Override + public long open(DataSpec dataSpec) throws IOException { + long waitMs = openNotBeforeMs - SystemClock.elapsedRealtime(); + + if (waitMs > 0) { + try { + Thread.sleep(waitMs); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new InterruptedIOException("Canceled while waiting to send the request"); + } + } + + return upstream.open(dataSpec); + } + + @Override + public int read(byte[] buffer, int offset, int readLength) throws IOException { + return upstream.read(buffer, offset, readLength); + } + + @Nullable + @Override + public Uri getUri() { + return upstream.getUri(); + } + + @Override + public Map> getResponseHeaders() { + return upstream.getResponseHeaders(); + } + + @Override + public void close() throws IOException { + upstream.close(); + } + } + /** Holds information about a snapshot of a single {@link Representation}. */ protected static final class RepresentationHolder { diff --git a/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/GoogleVideoHosts.java b/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/GoogleVideoHosts.java new file mode 100644 index 00000000000..ab2f88ddbec --- /dev/null +++ b/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/GoogleVideoHosts.java @@ -0,0 +1,284 @@ +package com.google.android.exoplayer2.source.sabr; + +import androidx.annotation.Nullable; +import androidx.annotation.VisibleForTesting; + +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.net.URLDecoder; +import java.util.HashMap; +import java.util.Map; + +/** + * The other hosts a signed googlevideo URL can be asked on, as the YouTube app builds them (21.44), and the media networks that + * failed lately. Both the SABR and the DASH requests use them. No Android dependency: plain JUnit tests. + */ +public final class GoogleVideoHosts { + private static final String GOOGLEVIDEO_SUFFIX = ".googlevideo.com"; + private static final String A1_SUFFIX = ".a1" + GOOGLEVIDEO_SUFFIX; + @VisibleForTesting + static final String REDIRECTOR_HOST = "redirector" + GOOGLEVIDEO_SUFFIX; + private static final String VIDEOPLAYBACK_PATH = "/videoplayback"; + /** + * How long a media network that failed to answer stays skipped. Restarting the engine or reloading the video builds new + * requests from the same player response, which would otherwise go to the broken network again (e.g. an ISP-hosted cache node + * that hangs on cache misses). + */ + private static final long FAILED_NETWORK_TTL_MS = 30 * 60 * 1_000; + private static final Map sFailedNetworks = new HashMap<>(); + + private GoogleVideoHosts() { + } + + /** + * The URL on the fallback host the YouTube app switches to: {@code r{fvip}---{mn[1]}.googlevideo.com}, with + * {@code fallback_count=1}. Null when the URL doesn't name one (no fvip or a single network) or is already on it. + */ + public static @Nullable String toFallbackUrl(@Nullable String url) { + URI uri = parse(url); + String host = uri != null ? uri.getHost() : null; + + if (host == null || !host.endsWith(GOOGLEVIDEO_SUFFIX)) { + return null; + } + + String fvip = getQueryParameter(uri.getRawQuery(), "fvip"); + String networks = getQueryParameter(uri.getRawQuery(), "mn"); + + if (!isHostLabel(fvip) || networks == null) { + return null; + } + + String[] network = networks.split(","); + + if (network.length < 2 || !isHostLabel(network[1])) { + return null; + } + + String fallbackHost = "r" + fvip + "---" + network[1] + GOOGLEVIDEO_SUFFIX; + + if (fallbackHost.equalsIgnoreCase(host)) { + return null; + } + + String result = replaceHost(url, uri, fallbackHost); + + return result != null ? appendQueryParameter(result, "fallback_count", "1") : null; + } + + /** + * The URL on the redirector, which answers with a redirect to a host that works: the YouTube app's last resort. Only for a GET: + * OkHttp follows a 302 to a POST with a GET, without its body. Null when the URL isn't a media one with its parameters in the + * query (e.g. a manifest, or a live segment's path-style URL), or is on the redirector already. + */ + public static @Nullable String toRedirectorUrl(@Nullable String url) { + URI uri = parse(url); + String host = uri != null ? uri.getHost() : null; + + if (extractNetwork(host) == null || !VIDEOPLAYBACK_PATH.equals(uri.getRawPath())) { + return null; + } + + String result = replaceHost(url, uri, REDIRECTOR_HOST); + + if (result == null) { + return null; + } + + result = appendQueryParameter(result, "cmo", "pf=1"); + + return host.endsWith(A1_SUFFIX) ? appendQueryParameter(result, "cmo", "td=a1.googlevideo.com") : result; + } + + /** + * Whether two URLs ask for the same media on the same host: host, path and signatures as the YouTube app compares them. Other + * parameters (e.g. the request number or the segment) don't count. + */ + public static boolean isSameMedia(@Nullable String url, @Nullable String other) { + URI uri = parse(url); + URI otherUri = parse(other); + + if (uri == null || otherUri == null) { + return false; + } + + return equalsIgnoreCase(uri.getHost(), otherUri.getHost()) + && equals(uri.getRawPath(), otherUri.getRawPath()) + && equals(getQueryParameter(uri.getRawQuery(), "signature"), getQueryParameter(otherUri.getRawQuery(), "signature")) + && equals(getQueryParameter(uri.getRawQuery(), "sig"), getQueryParameter(otherUri.getRawQuery(), "sig")) + && equals(getQueryParameter(uri.getRawQuery(), "lsig"), getQueryParameter(otherUri.getRawQuery(), "lsig")); + } + + public static @Nullable String getHost(@Nullable String url) { + URI uri = parse(url); + + return uri != null ? uri.getHost() : null; + } + + /** + * Skips the media network of this URL's host for a while (see FAILED_NETWORK_TTL_MS) + */ + public static void markNetworkFailed(@Nullable String url) { + String network = extractNetwork(getHost(url)); + + if (network == null) { + return; + } + + synchronized (sFailedNetworks) { + sFailedNetworks.put(network, nowMs() + FAILED_NETWORK_TTL_MS); + } + } + + public static boolean isNetworkFailed(@Nullable String url) { + String network = extractNetwork(getHost(url)); + + if (network == null) { + return false; + } + + synchronized (sFailedNetworks) { + Long expiresAt = sFailedNetworks.get(network); + + if (expiresAt == null) { + return false; + } + + if (expiresAt <= nowMs()) { + sFailedNetworks.remove(network); + return false; + } + + return true; + } + } + + /** + * Not skipped anymore: e.g. every host of a URL failed, and the first is tried again (see SabrCdnSelector) + */ + public static void clearNetworkFailed(@Nullable String url) { + String network = extractNetwork(getHost(url)); + + if (network == null) { + return; + } + + synchronized (sFailedNetworks) { + sFailedNetworks.remove(network); + } + } + + @VisibleForTesting + public static void clearFailedNetworks() { + synchronized (sFailedNetworks) { + sFailedNetworks.clear(); + } + } + + private static long nowMs() { + return System.nanoTime() / 1_000_000; // monotonic, no Android dependency + } + + /** + * The media network of a host: sn-4gxb5u-qo3l of rr1---sn-4gxb5u-qo3l.googlevideo.com + */ + private static @Nullable String extractNetwork(@Nullable String host) { + if (host == null || !host.endsWith(GOOGLEVIDEO_SUFFIX)) { + return null; + } + + int networkStart = host.indexOf("---"); + int networkEnd = host.length() - GOOGLEVIDEO_SUFFIX.length(); + + if (networkStart < 0 || networkStart + 3 >= networkEnd) { + return null; + } + + return host.substring(networkStart + 3, networkEnd).toLowerCase(); + } + + private static boolean isHostLabel(@Nullable String value) { + return value != null && value.matches("[A-Za-z0-9-]+"); + } + + private static @Nullable URI parse(@Nullable String url) { + if (url == null) { + return null; + } + + try { + return URI.create(url); + } catch (IllegalArgumentException e) { + return null; + } + } + + private static @Nullable String getQueryParameter(@Nullable String rawQuery, String key) { + if (rawQuery == null) { + return null; + } + + for (String pair : rawQuery.split("&")) { + int separator = pair.indexOf('='); + String rawKey = separator >= 0 ? pair.substring(0, separator) : pair; + + if (key.equals(decode(rawKey))) { + return decode(separator >= 0 ? pair.substring(separator + 1) : ""); + } + } + + return null; + } + + private static String appendQueryParameter(String url, String key, String value) { + int fragmentStart = url.indexOf('#'); + String base = fragmentStart >= 0 ? url.substring(0, fragmentStart) : url; + String fragment = fragmentStart >= 0 ? url.substring(fragmentStart) : ""; + String separator = base.indexOf('?') < 0 ? "?" : base.endsWith("?") || base.endsWith("&") ? "" : "&"; + + return base + separator + encode(key) + "=" + encode(value) + fragment; + } + + private static String decode(String value) { + try { + return URLDecoder.decode(value, "UTF-8"); + } catch (UnsupportedEncodingException | IllegalArgumentException e) { + return value; + } + } + + private static String encode(String value) { + try { + return java.net.URLEncoder.encode(value, "UTF-8"); + } catch (UnsupportedEncodingException e) { + throw new IllegalStateException(e); + } + } + + private static @Nullable String replaceHost(String url, URI uri, String host) { + String oldAuthority = uri.getRawAuthority(); + + if (oldAuthority == null || uri.getRawUserInfo() != null) { + return null; + } + + String newAuthority = uri.getPort() >= 0 ? host + ":" + uri.getPort() : host; + int authorityStart = url.indexOf("//" + oldAuthority); + + if (authorityStart < 0) { + return null; + } + + authorityStart += 2; + + return url.substring(0, authorityStart) + newAuthority + url.substring(authorityStart + oldAuthority.length()); + } + + private static boolean equals(@Nullable String a, @Nullable String b) { + return a == null ? b == null : a.equals(b); + } + + private static boolean equalsIgnoreCase(@Nullable String a, @Nullable String b) { + return a == null ? b == null : a.equalsIgnoreCase(b); + } +} diff --git a/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/SabrLivePrefetcher.java b/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/SabrLivePrefetcher.java new file mode 100644 index 00000000000..7a0e47f8ff5 --- /dev/null +++ b/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/SabrLivePrefetcher.java @@ -0,0 +1,390 @@ +package com.google.android.exoplayer2.source.sabr; + +import android.net.Uri; +import android.os.SystemClock; + +import androidx.annotation.Nullable; +import androidx.annotation.VisibleForTesting; + +import com.google.android.exoplayer2.C; +import com.google.android.exoplayer2.upstream.DataSource; +import com.google.android.exoplayer2.upstream.DataSpec; +import com.google.android.exoplayer2.upstream.TransferListener; +import com.google.android.exoplayer2.util.Log; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InterruptedIOException; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executor; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * Asks for the next segments of a live stream with short segments (ultra low latency: 1 s) while the player loads one, as + * LiveSegmentPrefetcher does for DASH. An edge answers a SABR request for a segment it hasn't cached in about a second however old + * the segment is, and the player asks for one segment of a track at a time: 1 s segments came at 0.8x of real time, and the stream + * stalled every 25 s (seen 2026-11-15). Requests in parallel are answered in the same time each.
+ * A response fetched ahead is the one the player's own request for that segment gets: it's read from memory then, not asked again. + * Only segments the server said exist (see LiveMetadata) are asked for ahead: a later one is held until it exists.
+ * Asked for on the playback thread, and on a seek's chunk's loading thread (see FirstSegmentDataSource). + */ +final class SabrLivePrefetcher { + private static final String TAG = SabrLivePrefetcher.class.getSimpleName(); + /** + * Asked for past the one the player loads: with it, 1 + 3 requests of about a second each are going on for 1 s segments + */ + static final int PREFETCH_COUNT = 3; + /** + * Prefetched for segments shorter than this: a 5 s segment is loaded faster than it plays + */ + static final int MAX_SEGMENT_DURATION_SEC = 2; + /** + * Of a response asked for ahead that holds one segment, in segments of the format's bitrate (one more for each further segment it + * holds): a bigger one is the server's burst toward its readahead (15 s, seen at the start of a stream on 2026-11-15: over 8 MB for + * a 2 s segment of 1440p), not a segment + */ + private static final float MAX_RESPONSE_SEGMENTS = 2.5f; + /** + * Of the segments a response is taken to hold (see DefaultSabrChunkSource#maybePrefetch): 3 behind the head of a 1 s stream + * (2026-11-15). More is a burst toward the readahead, which MAX_RESPONSE_SEGMENTS still tells. + */ + static final int MAX_SEGMENTS_PER_RESPONSE = 4; + private static final int MIN_RESPONSE_BYTES = 1024 * 1024; + private static final int MAX_RESPONSE_BYTES = 12 * 1024 * 1024; + /** + * After a burst, nothing is asked for ahead for this long: the server sends plenty, and the requests ahead would each be answered + * with the same burst + */ + private static final long BURST_PAUSE_MS = 10_000; + /** + * The player waits for a response asked for ahead at most this long, then asks itself + */ + private static final long WAIT_MS = 10_000; + private static final int READ_BUFFER_BYTES = 32 * 1024; + private static final Executor sExecutor = createExecutor(); + private final DataSource.Factory dataSourceFactory; + @Nullable private final TransferListener transferListener; + /** + * Of the format asked for ahead, by the sequence number of the segment each response is for + */ + private final Map fetches = new TreeMap<>(); + private int itag = -1; + /** + * Nothing is asked for ahead before (elapsed realtime), see BURST_PAUSE_MS + */ + private volatile long pausedUntilMs; + + SabrLivePrefetcher(DataSource.Factory dataSourceFactory, @Nullable TransferListener transferListener) { + this.dataSourceFactory = dataSourceFactory; + this.transferListener = transferListener; + } + + /** + * The player's request for a segment: served by the response fetched ahead for it, if any. The ones for earlier segments won't be. + * + * @param upstream asked when there's none, or when it failed + */ + synchronized DataSource dataSourceFor(int itag, long sequenceNumber, DataSource upstream) { + if (itag != this.itag) { + return upstream; + } + + Fetch fetch = null; + + for (Iterator> it = fetches.entrySet().iterator(); it.hasNext(); ) { + Map.Entry entry = it.next(); + + if (entry.getKey() > sequenceNumber) { + break; + } + + if (entry.getKey() == sequenceNumber) { + fetch = entry.getValue(); + } + + it.remove(); + } + + return fetch != null ? new PrefetchedDataSource(fetch, upstream) : upstream; + } + + /** + * Asks for the segment ahead, unless it was already + * + * @param dataSpec the request for it (see SabrManifest#createLiveRequestAfter) + */ + synchronized void prefetch(int itag, long sequenceNumber, DataSpec dataSpec, int maxBytes) { + if (itag != this.itag) { + clear(); + this.itag = itag; + } + + if (fetches.containsKey(sequenceNumber) || SystemClock.elapsedRealtime() < pausedUntilMs) { + return; + } + + DataSource dataSource = dataSourceFactory.createDataSource(); + + if (transferListener != null) { + dataSource.addTransferListener(transferListener); // what's fetched counts in the bandwidth estimate + } + + Fetch fetch = new Fetch(sequenceNumber); + fetches.put(sequenceNumber, fetch); + sExecutor.execute(() -> fetch.load(dataSource, dataSpec, maxBytes, + () -> pausedUntilMs = SystemClock.elapsedRealtime() + BURST_PAUSE_MS)); + } + + /** + * Of a response asked for ahead: about its segments of the format, a few more at most (see MAX_RESPONSE_SEGMENTS) + * + * @param bitrate the format's, in bits per second + * @param segments how many a response holds (see MAX_SEGMENTS_PER_RESPONSE) + */ + static int getMaxResponseBytes(int bitrate, long segmentDurationMs, int segments) { + long segmentBytes = bitrate > 0 ? bitrate / 8L * segmentDurationMs / 1_000 : 0; + long maxBytes = (long) (segmentBytes * (segments - 1 + MAX_RESPONSE_SEGMENTS)); + + return (int) Math.max(MIN_RESPONSE_BYTES, Math.min(MAX_RESPONSE_BYTES, maxBytes)); + } + + /** + * A seek or another format: what's asked for ahead won't be read + */ + synchronized void clear() { + fetches.clear(); + itag = -1; + } + + private static Executor createExecutor() { + AtomicInteger count = new AtomicInteger(); + ThreadPoolExecutor executor = new ThreadPoolExecutor( + PREFETCH_COUNT * 2, PREFETCH_COUNT * 2, 30, TimeUnit.SECONDS, new LinkedBlockingQueue<>(), runnable -> { + Thread thread = new Thread(runnable, "SabrLivePrefetcher-" + count.incrementAndGet()); + thread.setDaemon(true); + return thread; + }); + executor.allowCoreThreadTimeOut(true); + return executor; + } + + /** + * A response asked for ahead + */ + @VisibleForTesting + static final class Fetch { + final long sequenceNumber; + private final CountDownLatch done = new CountDownLatch(1); + @Nullable private volatile byte[] data; + @Nullable private volatile IOException error; + + Fetch(long sequenceNumber) { + this.sequenceNumber = sequenceNumber; + } + + /** + * @param onBurst run when the response is a burst, bigger than the given size (see MAX_RESPONSE_SEGMENTS), before it's done + */ + void load(DataSource dataSource, DataSpec dataSpec, int maxBytes, Runnable onBurst) { + long startMs = SystemClock.elapsedRealtime(); + + try { + dataSource.open(dataSpec); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + byte[] buffer = new byte[READ_BUFFER_BYTES]; + int read; + + while ((read = dataSource.read(buffer, 0, buffer.length)) != C.RESULT_END_OF_INPUT) { + out.write(buffer, 0, read); + + if (out.size() > maxBytes) { + onBurst.run(); + throw new IOException("A burst: over " + maxBytes + " bytes"); + } + } + + data = out.toByteArray(); + Log.d(TAG, "Segment " + sequenceNumber + ": " + out.size() + " bytes in " + + (SystemClock.elapsedRealtime() - startMs) + " ms"); + } catch (IOException | RuntimeException e) { + error = e instanceof IOException ? (IOException) e : new IOException(e); + Log.w(TAG, "Segment " + sequenceNumber + " failed: " + e.getMessage()); + } finally { + try { + dataSource.close(); + } catch (IOException ignored) { + // read already + } + + done.countDown(); + } + } + + /** + * @return the response, null when it failed or didn't come in time + */ + @Nullable + byte[] await(long timeoutMs) throws InterruptedIOException { + try { + if (!done.await(timeoutMs, TimeUnit.MILLISECONDS)) { + return null; + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new InterruptedIOException("Canceled while waiting for a segment asked for ahead"); + } + + return error == null ? data : null; + } + + @VisibleForTesting + void complete(@Nullable byte[] data, @Nullable IOException error) { + this.data = data; + this.error = error; + done.countDown(); + } + } + + /** + * Of a live seek's chunk: which segment it brings first isn't known before it comes, so the ones after it are asked for as soon as + * it has (see DefaultSabrChunkSource#maybePrefetch), not once the chunk is loaded. The check runs before each read, on the chunk's + * loading thread, till it says it's done: the extractor has parsed what was read before. Not once the load was canceled. + */ + @VisibleForTesting + static final class FirstSegmentDataSource implements DataSource { + interface Check { + /** + * @return whether it's done: not run again + */ + boolean run(); + } + + private final DataSource upstream; + private final Check check; + private boolean isDone; + + FirstSegmentDataSource(DataSource upstream, Check check) { + this.upstream = upstream; + this.check = check; + } + + @Override + public void addTransferListener(TransferListener transferListener) { + upstream.addTransferListener(transferListener); + } + + @Override + public long open(DataSpec dataSpec) throws IOException { + return upstream.open(dataSpec); + } + + @Override + public int read(byte[] buffer, int offset, int readLength) throws IOException { + if (!isDone && !Thread.currentThread().isInterrupted()) { + isDone = check.run(); + } + + return upstream.read(buffer, offset, readLength); + } + + @Nullable + @Override + public Uri getUri() { + return upstream.getUri(); + } + + @Override + public Map> getResponseHeaders() { + return upstream.getResponseHeaders(); + } + + @Override + public void close() throws IOException { + upstream.close(); + } + } + + /** + * Reads the response asked for ahead, else (it failed, or didn't come in time) asks upstream + */ + @VisibleForTesting + static final class PrefetchedDataSource implements DataSource { + private final Fetch fetch; + private final DataSource upstream; + @Nullable private byte[] data; + private int position; + private boolean isUpstream; + @Nullable private Uri uri; + + PrefetchedDataSource(Fetch fetch, DataSource upstream) { + this.fetch = fetch; + this.upstream = upstream; + } + + @Override + public void addTransferListener(TransferListener transferListener) { + upstream.addTransferListener(transferListener); + } + + @Override + public long open(DataSpec dataSpec) throws IOException { + data = fetch.await(WAIT_MS); + uri = dataSpec.uri; + + if (data == null) { + Log.w(TAG, "Segment " + fetch.sequenceNumber + " asked for ahead didn't come: asking again"); + isUpstream = true; + return upstream.open(dataSpec); + } + + // A load retried after an error resumes where it stopped (see ContainerMediaChunk#load) + position = (int) Math.min(Math.max(dataSpec.position, 0), data.length); + return data.length - position; + } + + @Override + public int read(byte[] buffer, int offset, int readLength) throws IOException { + if (isUpstream) { + return upstream.read(buffer, offset, readLength); + } + + if (data == null || position >= data.length) { + return C.RESULT_END_OF_INPUT; + } + + int length = Math.min(readLength, data.length - position); + System.arraycopy(data, position, buffer, offset, length); + position += length; + return length; + } + + @Nullable + @Override + public Uri getUri() { + return isUpstream ? upstream.getUri() : uri; + } + + @Override + public Map> getResponseHeaders() { + return isUpstream ? upstream.getResponseHeaders() : Collections.emptyMap(); + } + + @Override + public void close() throws IOException { + if (isUpstream) { + isUpstream = false; + upstream.close(); + } + + data = null; + } + } +} diff --git a/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/SabrMediaSource.java b/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/SabrMediaSource.java index 6db85c0ee8b..1385af96941 100644 --- a/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/SabrMediaSource.java +++ b/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/SabrMediaSource.java @@ -85,6 +85,13 @@ private SabrMediaSource( manifestLoadErrorThrower = new ManifestLoadErrorThrower(); } + /** + * What it plays, e.g. for its streams to be fetched again (see SabrManifestParser#refresh) + */ + public SabrManifest getManifest() { + return manifest; + } + @Override protected void prepareSourceInternal(@Nullable TransferListener mediaTransferListener) { this.mediaTransferListener = mediaTransferListener; @@ -104,10 +111,6 @@ protected void releaseSourceInternal() { periodsById.clear(); } - public SabrManifest getManifest() { - return manifest; - } - @Override public void maybeThrowSourceInfoRefreshError() throws IOException { manifestLoadErrorThrower.maybeThrowError(); diff --git a/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/SabrRefusedRequest.java b/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/SabrRefusedRequest.java new file mode 100644 index 00000000000..d2f1335e6bb --- /dev/null +++ b/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/SabrRefusedRequest.java @@ -0,0 +1,89 @@ +package com.google.android.exoplayer2.source.sabr; + +import androidx.annotation.Nullable; + +import com.google.android.exoplayer2.upstream.HttpDataSource.InvalidResponseCodeException; + +/** + * The last request SABR's media server refused with HTTP 401 or 403 (see DefaultSabrChunkSource#onChunkLoadError): what it asked for + * and how old its session was, kept with the error it came as. A SabrProtocolError carries them itself (see + * SabrProtocolError#setRequest), a response code can't: the app finds them by the error the player fails with. WVE7ZKDD #1, #2: a 403 + * on a rewind 87 s into the session, and whether the seek or a server change drew it couldn't be told. + */ +public final class SabrRefusedRequest { + @Nullable private static volatile SabrRefusedRequest last; + + private final InvalidResponseCodeException error; + /** + * What it asked for (see SabrManifest#describeRequest), null when not known + */ + @Nullable public final String request; + /** + * How long before the session in use had been swapped in (see SabrManifest#getSessionAgeMs), -1 for the stream's first one + */ + public final long sessionAgeMs; + + private SabrRefusedRequest(InvalidResponseCodeException error, @Nullable String request, long sessionAgeMs) { + this.error = error; + this.request = request; + this.sessionAgeMs = sessionAgeMs; + } + + /** + * A load of the track failed: kept when its server refused it + */ + static void onLoadError(Throwable error, @Nullable String request, long sessionAgeMs) { + InvalidResponseCodeException refusal = findRefusal(error); + + if (refusal != null) { + last = new SabrRefusedRequest(refusal, request, sessionAgeMs); + } + } + + /** + * Of the refusal the error is, or came from: null when it's none, or another than the last one kept + */ + @Nullable + public static SabrRefusedRequest of(@Nullable Throwable error) { + SabrRefusedRequest refused = last; + + if (refused == null) { + return null; + } + + for (Throwable cause = error; cause != null; cause = cause.getCause()) { + if (cause == refused.error) { + return refused; + } + + if (cause.getCause() == cause) { + break; + } + } + + return null; + } + + @Nullable + private static InvalidResponseCodeException findRefusal(@Nullable Throwable error) { + for (Throwable cause = error; cause != null; cause = cause.getCause()) { + if (cause instanceof InvalidResponseCodeException) { + int code = ((InvalidResponseCodeException) cause).responseCode; + return code == 401 || code == 403 ? (InvalidResponseCodeException) cause : null; + } + + if (cause.getCause() == cause) { + break; + } + } + + return null; + } + + /** + * For the tests: none kept + */ + public static void resetForTesting() { + last = null; + } +} diff --git a/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/SabrSampleDeduplicator.java b/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/SabrSampleDeduplicator.java new file mode 100644 index 00000000000..27d79634fa6 --- /dev/null +++ b/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/SabrSampleDeduplicator.java @@ -0,0 +1,142 @@ +package com.google.android.exoplayer2.source.sabr; + +import android.util.SparseArray; + +import androidx.annotation.Nullable; + +import com.google.android.exoplayer2.Format; +import com.google.android.exoplayer2.extractor.ExtractorInput; +import com.google.android.exoplayer2.extractor.TrackOutput; +import com.google.android.exoplayer2.source.chunk.Chunk; +import com.google.android.exoplayer2.source.chunk.ChunkExtractorWrapper.TrackOutputProvider; +import com.google.android.exoplayer2.source.sabr.parser.SabrStream; +import com.google.android.exoplayer2.util.Log; +import com.google.android.exoplayer2.util.ParsableByteArray; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +/** + * Keeps the samples of a segment that the server sends again from being queued twice. + *

+ * A response can end in the middle of a segment, e.g. when a read times out and SabrMatroskaAdapter or + * SabrFragmentedMp4Adapter ends the chunk. The stream time only advances when a segment ends, so the next + * request asks for the same segment and the server sends all of it again. Without this, its first + * samples would be queued a second time and the video would fall seconds behind the audio. + */ +/* package */ final class SabrSampleDeduplicator { + private static final String TAG = SabrSampleDeduplicator.class.getSimpleName(); + private final SabrStream sabrStream; + private final SparseArray segments = new SparseArray<>(); + + private static final class Segment { + private int itag = -1; + private long sequenceNumber = -1; + /** The chunk that queued each sample of the segment, by sample time */ + private final Map queuedSamples = new HashMap<>(); + @Nullable private Chunk resentBy; + } + + /* package */ SabrSampleDeduplicator(SabrStream sabrStream) { + this.sabrStream = sabrStream; + } + + /** + * Wraps the outputs of a media chunk so that the samples another chunk already queued are dropped. + */ + /* package */ TrackOutputProvider wrap(Chunk chunk, TrackOutputProvider output) { + SparseArray trackOutputs = new SparseArray<>(); + + return (id, type) -> { + TrackOutput trackOutput = trackOutputs.get(id); + + if (trackOutput == null) { + trackOutput = new DeduplicatingTrackOutput(output.track(id, type), id, chunk); + trackOutputs.put(id, trackOutput); + } + + return trackOutput; + }; + } + + /** + * Forgets the queued samples. Call it when the sample queue is reset or chunks are discarded from it, + * so that a segment loaded again isn't mistaken for a repeat. + */ + /* package */ void reset() { + segments.clear(); + } + + /** + * False if an earlier chunk already queued this sample of the segment. + */ + /* package */ boolean shouldQueue(int trackId, Chunk chunk, int itag, long sequenceNumber, long timeUs) { + Segment segment = segments.get(trackId); + + if (segment == null) { + segment = new Segment(); + segments.put(trackId, segment); + } + + if (segment.itag != itag || segment.sequenceNumber != sequenceNumber) { + segment.itag = itag; + segment.sequenceNumber = sequenceNumber; + segment.queuedSamples.clear(); + segment.resentBy = null; + } + + Chunk queuedBy = segment.queuedSamples.get(timeUs); + + if (queuedBy != null && queuedBy != chunk) { + if (segment.resentBy != chunk) { + segment.resentBy = chunk; + Log.w(TAG, "Segment " + sequenceNumber + " of itag " + itag + + " was sent again, dropping the samples already queued"); + } + + return false; + } + + segment.queuedSamples.put(timeUs, chunk); + + return true; + } + + private final class DeduplicatingTrackOutput implements TrackOutput { + private final TrackOutput output; + private final int trackId; + private final Chunk chunk; + + private DeduplicatingTrackOutput(TrackOutput output, int trackId, Chunk chunk) { + this.output = output; + this.trackId = trackId; + this.chunk = chunk; + } + + @Override + public void format(Format format) { + output.format(format); + } + + @Override + public int sampleData(ExtractorInput input, int length, boolean allowEndOfInput) + throws IOException, InterruptedException { + return output.sampleData(input, length, allowEndOfInput); + } + + @Override + public void sampleData(ParsableByteArray data, int length) { + output.sampleData(data, length); + } + + @Override + public void sampleMetadata(long timeUs, int flags, int size, int offset, @Nullable CryptoData cryptoData) { + // The data of a dropped sample stays in the queue unreferenced, and the offset of the next sample + // skips it. SampleQueue does the same while it waits for a keyframe. + if (shouldQueue(trackId, chunk, sabrStream.getSegmentItag(), sabrStream.getSegmentSequenceNumber(), timeUs)) { + output.sampleMetadata(timeUs, flags, size, offset, cryptoData); + } + } + } +} diff --git a/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/ValidatedNetwork.java b/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/ValidatedNetwork.java new file mode 100644 index 00000000000..2a6c8bcefe1 --- /dev/null +++ b/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/ValidatedNetwork.java @@ -0,0 +1,30 @@ +package com.google.android.exoplayer2.source.sabr; + +import androidx.annotation.Nullable; + +import java.util.function.BooleanSupplier; + +/** + * Whether the device has a network that reaches the internet, as the app knows it (the library has no Context). With none, a + * request that can't connect says nothing about its host: no other host is tried and none is marked failed, or one Wi-Fi drop + * would keep the player off its media network for half an hour (see GoogleVideoHosts#markNetworkFailed). + */ +public final class ValidatedNetwork { + private static volatile @Nullable BooleanSupplier sSupplier; + + private ValidatedNetwork() { + } + + public static void setSupplier(@Nullable BooleanSupplier supplier) { + sSupplier = supplier; + } + + /** + * True when the app didn't say (e.g. in tests): today's behaviour + */ + public static boolean isAvailable() { + BooleanSupplier supplier = sSupplier; + + return supplier == null || supplier.getAsBoolean(); + } +} diff --git a/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/manifest/SabrCdnSelector.java b/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/manifest/SabrCdnSelector.java index fb491001206..3b1fa981b2e 100644 --- a/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/manifest/SabrCdnSelector.java +++ b/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/manifest/SabrCdnSelector.java @@ -1,27 +1,17 @@ package com.google.android.exoplayer2.source.sabr.manifest; import androidx.annotation.Nullable; -import androidx.annotation.VisibleForTesting; -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.net.URLDecoder; +import com.google.android.exoplayer2.source.sabr.GoogleVideoHosts; + import java.util.ArrayList; -import java.util.HashMap; import java.util.List; -import java.util.Map; -/** Selects equivalent Googlevideo media networks advertised by a signed SABR URL. */ +/** + * Selects the host of a signed SABR URL: the one given, then the fallback host the YouTube app switches to + * (see GoogleVideoHosts#toFallbackUrl). Never the redirector: SABR requests are POSTs, which a redirect turns into GETs. + */ final class SabrCdnSelector { - private static final String GOOGLEVIDEO_SUFFIX = ".googlevideo.com"; - /** - * How long a media network that failed to answer stays skipped. Restarting the engine or - * reloading the video builds a new manifest (and selector) from the same player response, - * which would otherwise send the first request to the broken network again - * (e.g. an ISP-hosted cache node that hangs on cache misses). - */ - private static final long FAILED_NETWORK_TTL_MS = 30 * 60 * 1_000; - private static final Map sFailedNetworks = new HashMap<>(); private final List candidateUrls = new ArrayList<>(); private int selectedIndex; @@ -31,7 +21,13 @@ public SabrCdnSelector(@Nullable String initialUrl) { } candidateUrls.add(initialUrl); - addAlternateUrls(initialUrl); + + String fallbackUrl = GoogleVideoHosts.toFallbackUrl(initialUrl); + + if (fallbackUrl != null) { + candidateUrls.add(fallbackUrl); + } + skipFailedNetworks(); } @@ -54,121 +50,59 @@ public synchronized boolean maybeAdvance(@Nullable String failedUrl) { return true; } + GoogleVideoHosts.markNetworkFailed(failedUrl); + if (selectedIndex + 1 >= candidateUrls.size()) { + // The last one failed too: with every host failed, the next selection starts again from the first (see + // skipFailedNetworks). Before, the first stayed skipped for half an hour, and the next playbacks went to the one that + // failed last (AWHPECZK). + forgetFailuresIfAllFailed(); return false; } - markFailed(getHost(failedUrl)); selectedIndex++; return true; } private void skipFailedNetworks() { - // Keep the last candidate as a fallback even if it failed too. - while (selectedIndex + 1 < candidateUrls.size() - && isFailed(extractNetwork(getHost(candidateUrls.get(selectedIndex))))) { - selectedIndex++; - } - } - - private static void markFailed(@Nullable String host) { - String network = extractNetwork(host); - - if (network == null) { + // Every host failed lately (e.g. the DASH requests' marks): the first one again + if (forgetFailuresIfAllFailed()) { return; } - synchronized (sFailedNetworks) { - sFailedNetworks.put(network, nowMs() + FAILED_NETWORK_TTL_MS); - } - } - - @VisibleForTesting - static void clearFailedNetworks() { - synchronized (sFailedNetworks) { - sFailedNetworks.clear(); + // Keep the last candidate as a fallback even if it failed too. + while (selectedIndex + 1 < candidateUrls.size() + && GoogleVideoHosts.isNetworkFailed(candidateUrls.get(selectedIndex))) { + selectedIndex++; } } - private static long nowMs() { - return System.nanoTime() / 1_000_000; // monotonic, no Android dependency (plain JUnit tests) - } - - private static boolean isFailed(@Nullable String network) { - if (network == null) { - return false; - } - - synchronized (sFailedNetworks) { - Long expiresAt = sFailedNetworks.get(network); - - if (expiresAt == null) { - return false; - } - - if (expiresAt <= nowMs()) { - sFailedNetworks.remove(network); + /** + * @return whether every host had failed: none is skipped then + */ + private boolean forgetFailuresIfAllFailed() { + for (String url : candidateUrls) { + if (!GoogleVideoHosts.isNetworkFailed(url)) { return false; } - - return true; - } - } - - private void addAlternateUrls(String initialUrl) { - URI initialUri; - - try { - initialUri = URI.create(initialUrl); - } catch (IllegalArgumentException e) { - return; } - String initialHost = initialUri.getHost(); - String currentNetwork = extractNetwork(initialHost); - String networksValue = getQueryParameter(initialUri.getRawQuery(), "mn"); - - if (initialHost == null || currentNetwork == null || networksValue == null) { - return; + for (String url : candidateUrls) { + GoogleVideoHosts.clearNetworkFailed(url); } - String[] networks = networksValue.split(","); - int currentNetworkIndex = -1; - - for (int i = 0; i < networks.length; i++) { - if (currentNetwork.equals(networks[i])) { - currentNetworkIndex = i; - break; - } - } - - if (currentNetworkIndex < 0) { - return; - } - - for (int i = currentNetworkIndex + 1; i < networks.length; i++) { - if (!networks[i].matches("[A-Za-z0-9-]+")) { - continue; - } - - String host = "rr" + (i + 1) + "---" + networks[i] + GOOGLEVIDEO_SUFFIX; - String alternateUrl = replaceAuthority(initialUrl, initialUri, host); - - if (alternateUrl != null) { - candidateUrls.add(alternateUrl); - } - } + return true; } private int findCandidateIndex(@Nullable String url) { - String failedHost = getHost(url); + String failedHost = GoogleVideoHosts.getHost(url); if (failedHost == null) { return -1; } for (int i = 0; i < candidateUrls.size(); i++) { - String candidateHost = getHost(candidateUrls.get(i)); + String candidateHost = GoogleVideoHosts.getHost(candidateUrls.get(i)); if (candidateHost != null && candidateHost.equalsIgnoreCase(failedHost)) { return i; @@ -177,74 +111,4 @@ private int findCandidateIndex(@Nullable String url) { return -1; } - - private static @Nullable String getHost(@Nullable String url) { - if (url == null) { - return null; - } - - try { - return URI.create(url).getHost(); - } catch (IllegalArgumentException e) { - return null; - } - } - - private static @Nullable String extractNetwork(@Nullable String host) { - if (host == null || !host.endsWith(GOOGLEVIDEO_SUFFIX)) { - return null; - } - - int networkStart = host.indexOf("---"); - int networkEnd = host.length() - GOOGLEVIDEO_SUFFIX.length(); - - if (networkStart < 0 || networkStart + 3 >= networkEnd) { - return null; - } - - return host.substring(networkStart + 3, networkEnd); - } - - private static @Nullable String getQueryParameter(@Nullable String rawQuery, String key) { - if (rawQuery == null) { - return null; - } - - for (String pair : rawQuery.split("&")) { - int separator = pair.indexOf('='); - String rawKey = separator >= 0 ? pair.substring(0, separator) : pair; - - if (key.equals(decode(rawKey))) { - return decode(separator >= 0 ? pair.substring(separator + 1) : ""); - } - } - - return null; - } - - private static String decode(String value) { - try { - return URLDecoder.decode(value, "UTF-8"); - } catch (UnsupportedEncodingException e) { - throw new IllegalStateException(e); - } - } - - private static @Nullable String replaceAuthority(String url, URI uri, String host) { - String oldAuthority = uri.getRawAuthority(); - - if (oldAuthority == null) { - return null; - } - - String newAuthority = uri.getPort() >= 0 ? host + ":" + uri.getPort() : host; - int authorityStart = url.indexOf(oldAuthority); - - if (authorityStart < 0) { - return null; - } - - return url.substring(0, authorityStart) + newAuthority - + url.substring(authorityStart + oldAuthority.length()); - } } diff --git a/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/manifest/SabrManifest.java b/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/manifest/SabrManifest.java index 79ad7829ca1..ce1499c996a 100644 --- a/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/manifest/SabrManifest.java +++ b/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/manifest/SabrManifest.java @@ -1,10 +1,12 @@ package com.google.android.exoplayer2.source.sabr.manifest; +import android.os.SystemClock; import android.util.Base64; import android.util.Pair; import androidx.annotation.NonNull; import androidx.annotation.Nullable; +import androidx.annotation.VisibleForTesting; import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.Format; @@ -25,16 +27,20 @@ import com.google.android.exoplayer2.source.sabr.protos.videostreaming.TimeRange; import com.google.android.exoplayer2.source.sabr.protos.videostreaming.VideoPlaybackAbrRequest; import com.google.protobuf.ByteString; +import com.liskovsoft.sharedutils.mylogger.Log; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; /** * Represents a SABR media presentation */ public class SabrManifest implements FilterableManifest { + private static final String TAG = SabrManifest.class.getSimpleName(); + /** * The {@code availabilityStartTime} value in milliseconds since epoch, or {@link C#TIME_UNSET} if * not present. @@ -84,14 +90,99 @@ public class SabrManifest implements FilterableManifest { @Nullable public final String visitorCookie; + /** + * Of {@link #liveSegmentTargetDurationSec}: the stream isn't live + */ + public static final int NOT_LIVE = -1; + + /** + * A live stream's segment length (see SabrManifestParser), {@link #NOT_LIVE} for a video or a finished stream + */ + public final int liveSegmentTargetDurationSec; + + /** + * A new session asked for (see requestSessionRefresh) and not given in this long: it failed + */ + @VisibleForTesting + static final long SESSION_REFRESH_TIMEOUT_MS = 30_000; + /** + * Asked for again this soon after a new session was swapped in: it didn't help + */ + @VisibleForTesting + static final long MIN_SESSION_LIFETIME_MS = 60_000; + private final String videoId; - private final SabrCdnSelector cdnSelector; - private final String videoPlaybackUstreamerConfig; - private final String poToken; + /** + * The streams' session: replaced when they're fetched again (see refreshSession, requestSessionRefresh) + */ + private SabrCdnSelector cdnSelector; + private volatile String videoPlaybackUstreamerConfig; + private volatile String poToken; private final ClientInfo clientInfo; private final Map sabrStreams; private int sabrRequestNumber = -1; private final FormatSelector emptySelector; + @Nullable private SessionRefresher sessionRefresher; + /** + * Of the session in use: the next one's is one more (see getSessionId) + */ + private int sessionId; + /** + * When the session in use was swapped in (SystemClock#elapsedRealtime), -1 for the first one + */ + private long sessionStartMs = -1; + /** + * How the session in use came, one of the SESSION_ constants (see describeRequest). A refusal 38-95 ms into a new session + * (0CW972QK, H8ZP1GPV) didn't come again with sessions the app asked for in a burst of seeks on the emulator (2026-11-23): the + * server's asks, with their reload token, were the difference left. + */ + private volatile String sessionOrigin = SESSION_FIRST; + /** + * Of the session being asked for (see requestSessionRefresh) + */ + private String pendingSessionOrigin; + static final String SESSION_FIRST = "first"; + static final String SESSION_ASKED = "server-asked"; + static final String SESSION_ASKED_WITH_TOKEN = "server-asked with a token"; + static final String SESSION_REFETCHED = "refetched"; + /** + * When the new session being asked for was (SystemClock#elapsedRealtime), -1 for none + */ + private long sessionRefreshStartMs = -1; + /** + * A new session was asked for and not had, or didn't help: the next ask for one fails the stream, which the app reloads with the + * video. Not after another one was swapped in (see refreshSession). + */ + private boolean isSessionRefreshFailed; + /** + * Of each track, its last request (see describeRequest): what one the server refused asked for (see SabrProtocolError#setRequest). + * Made on the loading threads. + */ + private final Map lastRequests = new ConcurrentHashMap<>(); + + /** + * Asks for the player response again when the server asks for it (see SabrReloadPlayerError), e.g. as the session expires about + * 6 h into a video + */ + public interface SessionRefresher { + /** + * Called on the playback thread, once per ask: the player response is fetched on another thread, and its session given to + * the callback. + * + * @param reloadPlaybackToken the server's, for the player request (see ReloadPlayerResponse), null if it gave none + */ + void refresh(@Nullable String reloadPlaybackToken, SessionCallback callback); + } + + public interface SessionCallback { + /** + * On any thread + * + * @param session null when there's none (e.g. the fetch failed) + * @return whether it was swapped in: not one of another client, without the stream's formats, or late + */ + boolean onSession(@Nullable SabrSession session); + } public SabrManifest( long availabilityStartTimeMs, @@ -131,6 +222,31 @@ public SabrManifest( String videoId, ClientInfo clientInfo, @Nullable String visitorCookie) { + this( + availabilityStartTimeMs, durationMs, minBufferTimeMs, dynamic, minUpdatePeriodMs, + timeShiftBufferDepthMs, suggestedPresentationDelayMs, publishTimeMs, periods, + serverAbrStreamingUrl, videoPlaybackUstreamerConfig, poToken, videoId, clientInfo, + visitorCookie, NOT_LIVE); + } + + public SabrManifest( + long availabilityStartTimeMs, + long durationMs, + long minBufferTimeMs, + boolean dynamic, + long minUpdatePeriodMs, + long timeShiftBufferDepthMs, + long suggestedPresentationDelayMs, + long publishTimeMs, + List periods, + String serverAbrStreamingUrl, + String videoPlaybackUstreamerConfig, + String poToken, + String videoId, + ClientInfo clientInfo, + @Nullable String visitorCookie, + int liveSegmentTargetDurationSec) { + this.liveSegmentTargetDurationSec = liveSegmentTargetDurationSec; this.availabilityStartTimeMs = availabilityStartTimeMs; this.durationMs = durationMs; this.minBufferTimeMs = minBufferTimeMs; @@ -173,6 +289,13 @@ public SabrManifest copy(List streamKeys) { return null; } + /** + * A live stream's, not a finished one's (see {@link #liveSegmentTargetDurationSec}) + */ + public final boolean isLive() { + return liveSegmentTargetDurationSec != NOT_LIVE; + } + public final String getVideoId() { return videoId; } @@ -184,11 +307,12 @@ public synchronized SabrStream getSabrStream(int trackType) { return sabrStream; } + boolean isLive = isLive(); sabrStream = new SabrStream( cdnSelector.getCurrentUrl(), videoPlaybackUstreamerConfig, clientInfo, - -1, + isLive ? liveSegmentTargetDurationSec : -1, -1, -1, poToken, @@ -196,6 +320,8 @@ public synchronized SabrStream getSabrStream(int trackType) { videoId, durationMs ); + // The server's media headers of a live stream have no duration: estimated from the target (see SabrProcessor) + sabrStream.setLive(isLive); sabrStreams.put(trackType, sabrStream); @@ -221,6 +347,188 @@ public synchronized boolean maybeUseNextCdn(String failedUrl) { return true; } + public synchronized void setSessionRefresher(@Nullable SessionRefresher refresher) { + sessionRefresher = refresher; + } + + /** + * Of the session the requests are made with now: a request answered with an ask for a new one tells which it was made with (see + * requestSessionRefresh) + */ + public synchronized int getSessionId() { + return sessionId; + } + + /** + * The server asked for the player response again (see ReloadPlayerResponse): it sends no media with this session. A new one is + * asked for (see SessionRefresher), and swapped in while the player plays what it buffered. Before, the player was failed and + * the app reloaded the video with it: the playback stopped for about 3 s, and the audio output was closed and opened again + * (SmartTube #6478, about 6 h into a long video). + * + * @param requestSessionId of the session the request was made with (see getSessionId) + * @return whether the requests wait for the new session, or are made with one already in: false when there's no new one to + * have here (no refresher, or one failed or didn't help), and the stream fails as before + */ + public boolean requestSessionRefresh(int requestSessionId, @Nullable String reloadPlaybackToken) { + SessionRefresher refresher; + int refreshedSessionId; + + synchronized (this) { + if (requestSessionId != sessionId) { + // Made with the session before: the next request has the new one + return true; + } + + if (isSessionRefreshPending()) { + return true; // the other track asked for it + } + + if (sessionRefresher == null || isSessionRefreshFailed) { + return false; + } + + long nowMs = SystemClock.elapsedRealtime(); + + if (sessionStartMs != -1 && nowMs - sessionStartMs < MIN_SESSION_LIFETIME_MS) { + Log.e(TAG, "Asked for a new session %s ms after the last one: it didn't help", nowMs - sessionStartMs); + isSessionRefreshFailed = true; + return false; + } + + Log.d(TAG, "Asking for a new session of %s", videoId); + sessionRefreshStartMs = nowMs; + pendingSessionOrigin = reloadPlaybackToken != null && !reloadPlaybackToken.isEmpty() ? SESSION_ASKED_WITH_TOKEN : SESSION_ASKED; + refresher = sessionRefresher; + refreshedSessionId = sessionId; + } + + // Not holding the lock: the callback may come at once + try { + refresher.refresh(reloadPlaybackToken, session -> onSessionRefreshed(refreshedSessionId, session)); + } catch (RuntimeException e) { + Log.e(TAG, "Session refresh failed to start: %s", e.getMessage()); + onSessionRefreshed(refreshedSessionId, null); + } + + synchronized (this) { + return !isSessionRefreshFailed; + } + } + + /** + * A new session is asked for and not given yet (see requestSessionRefresh): the requests wait for it. One not given in + * SESSION_REFRESH_TIMEOUT_MS failed. + */ + public synchronized boolean isSessionRefreshPending() { + if (sessionRefreshStartMs == -1) { + return false; + } + + if (SystemClock.elapsedRealtime() - sessionRefreshStartMs >= SESSION_REFRESH_TIMEOUT_MS) { + Log.e(TAG, "No new session in %s ms", SESSION_REFRESH_TIMEOUT_MS); + sessionRefreshStartMs = -1; + isSessionRefreshFailed = true; + return false; + } + + return true; + } + + /** + * @param refreshedSessionId of the session in use when the new one was asked for + * @return whether the session was swapped in + */ + private synchronized boolean onSessionRefreshed(int refreshedSessionId, @Nullable SabrSession session) { + if (refreshedSessionId != sessionId || sessionRefreshStartMs == -1) { + Log.w(TAG, "A new session came after the ask for it timed out, or after another one was swapped in"); + return false; + } + + sessionRefreshStartMs = -1; + String rejection = session != null ? getRejection(session) : "none came"; + + if (rejection != null) { + Log.e(TAG, "No new session: %s", rejection); + isSessionRefreshFailed = true; + return false; + } + + refreshSession(session.serverAbrStreamingUrl, session.videoPlaybackUstreamerConfig, session.poToken); + sessionOrigin = pendingSessionOrigin != null ? pendingSessionOrigin : SESSION_ASKED; + + return true; + } + + /** + * @return why the streams can't go on with the session, null when they can + */ + @Nullable + private String getRejection(SabrSession session) { + if (session.clientInfo.getClientName() != clientInfo.getClientName()) { + return String.format("of the client %s, not %s", session.clientInfo.getClientName(), clientInfo.getClientName()); + } + + for (SabrStream sabrStream : sabrStreams.values()) { + if (!sabrStream.acceptsUrl(session.serverAbrStreamingUrl)) { + return "of another broadcast"; + } + + for (FormatId formatId : sabrStream.getFormatSelector().formatIds) { + if (!session.itags.contains(formatId.getItag())) { + return String.format("without the format %s", formatId.getItag()); + } + } + } + + return null; + } + + /** + * The streams fetched again: before they expire (see SabrManifestParser#refresh), or as the server asked (see + * requestSessionRefresh). The next request of each track goes to their URL with their config and poToken, while the media buffered + * plays on. A request under way keeps the old ones, and one answered with an ask for a new session is made again with this one. + * What the server said of the streams so far (e.g. the playback cookie, the formats initialized) stays. + */ + public synchronized void refreshSession(String serverAbrStreamingUrl, String videoPlaybackUstreamerConfig, @Nullable String poToken) { + cdnSelector = new SabrCdnSelector(serverAbrStreamingUrl); + this.videoPlaybackUstreamerConfig = videoPlaybackUstreamerConfig; + this.poToken = poToken; + String url = cdnSelector.getCurrentUrl(); + + for (SabrStream sabrStream : sabrStreams.values()) { + sabrStream.setServerAbrStreamingUrl(url); + sabrStream.setPoToken(poToken); + } + + sessionId++; + sessionStartMs = SystemClock.elapsedRealtime(); + // Asked for by the server, it's set after this (see onSessionRefreshed) + sessionOrigin = SESSION_REFETCHED; + // The requests waiting for a new session (see requestSessionRefresh) go on with this one: the one asked for is dropped when it + // comes (see onSessionRefreshed) + sessionRefreshStartMs = -1; + isSessionRefreshFailed = false; + Log.d(TAG, "New session swapped in: %s", url); + } + + public ClientInfo getClientInfo() { + return clientInfo; + } + + public int getSabrRequestNumber() { + return sabrRequestNumber; + } + + public synchronized String getRequestUrl(int trackType) { + SabrStream activeStream = sabrStreams.get(trackType); + + if (activeStream == null) { + throw new IllegalStateException("Active SabrStream not found for track type " + trackType); + } + + return Utils.updateQuery(activeStream.getUrl(), "rn", ++sabrRequestNumber); + } + /** * @return target length of a live segment or -1 if unknown yet (no streams created) */ @@ -277,20 +585,6 @@ public synchronized long getLiveWindowStartMs() { return result; } - public int getSabrRequestNumber() { - return sabrRequestNumber; - } - - public synchronized String getRequestUrl(int trackType) { - SabrStream activeStream = sabrStreams.get(trackType); - - if (activeStream == null) { - throw new IllegalStateException("Active SabrStream not found for track type " + trackType); - } - - return Utils.updateQuery(activeStream.getUrl(), "rn", ++sabrRequestNumber); - } - public SabrStreamError getUnthrownError() { for (SabrStream sabrStream : sabrStreams.values()) { return sabrStream.getUnthrownError(); @@ -304,6 +598,22 @@ public VideoPlaybackAbrRequest createVideoPlaybackAbrRequest(int trackType, bool } public VideoPlaybackAbrRequest createVideoPlaybackAbrRequest(int trackType, boolean isInit, long seekTimeUs) { + return createVideoPlaybackAbrRequest(trackType, isInit, seekTimeUs, null); + } + + /** + * A live stream's request for the segment after the given one, as if it were the newest received: the player asks for one segment + * of a track at a time, and an edge answers each in about a second however old it is (see DefaultSabrChunkSource's prefetch) + * + * @param lastSegment the format's segment taken as the newest one buffered: its sequence number, start and duration + */ + public VideoPlaybackAbrRequest createLiveRequestAfter(int trackType, MediaHeader lastSegment) { + return createVideoPlaybackAbrRequest(trackType, false, + (lastSegment.getStartMs() + lastSegment.getDurationMs()) * 1_000L, lastSegment); + } + + private VideoPlaybackAbrRequest createVideoPlaybackAbrRequest(int trackType, boolean isInit, long seekTimeUs, + @Nullable MediaHeader lastSegment) { SabrStream activeStream = sabrStreams.get(trackType); if (activeStream == null) { @@ -353,7 +663,7 @@ public VideoPlaybackAbrRequest createVideoPlaybackAbrRequest(int trackType, bool ClientAbrState clientAbrState = clientAbrStateBuilder.build(); - Pair, FormatId> bufferRanges = addBufferingInfoToAbrRequest(trackType); + Pair, FormatId> bufferRanges = addBufferingInfoToAbrRequest(trackType, lastSegment); List selectedFormats = createSelectedFormatIds(trackType); @@ -365,7 +675,7 @@ public VideoPlaybackAbrRequest createVideoPlaybackAbrRequest(int trackType, bool selectedFormats.add(0, bufferRanges.second); } - return VideoPlaybackAbrRequest.newBuilder() + VideoPlaybackAbrRequest request = VideoPlaybackAbrRequest.newBuilder() .setClientAbrState(clientAbrState) .addAllPreferredVideoFormatIds(getFormatSelector(C.TRACK_TYPE_VIDEO).formatIds) .addAllPreferredAudioFormatIds(getFormatSelector(C.TRACK_TYPE_AUDIO).formatIds) @@ -379,6 +689,65 @@ public VideoPlaybackAbrRequest createVideoPlaybackAbrRequest(int trackType, bool ) .setStreamerContext(createStreamerContext(trackType)) .build(); + + lastRequests.put(trackType, describeRequest(request, isInit, getSessionId(), sessionOrigin)); + + return request; + } + + /** + * The track's last request (see describeRequest), null for none yet + */ + @Nullable + public String getLastRequest(int trackType) { + return lastRequests.get(trackType); + } + + /** + * How long ago the session in use was swapped in (see refreshSession), -1 for the stream's first one + */ + public synchronized long getSessionAgeMs() { + return sessionStartMs == -1 ? -1 : SystemClock.elapsedRealtime() - sessionStartMs; + } + + /** + * The formats a request names, for a refusal's diagnostics: e.g. "init, video 248, audio 251:drc, selected none, session 1 (server-asked)" + */ + static String describeRequest(VideoPlaybackAbrRequest request, boolean isInit, int sessionId, String sessionOrigin) { + return (isInit ? "init" : "media") + + ", video " + describeFormats(request.getPreferredVideoFormatIdsList()) + + ", audio " + describeFormats(request.getPreferredAudioFormatIdsList()) + + ", selected " + describeFormats(request.getSelectedFormatIdsList()) + + ", session " + sessionId + " (" + sessionOrigin + ")"; + } + + /** + * How the session in use came: first, server-asked (with a token or not), or refetched (see describeRequest) + */ + public String getSessionOrigin() { + return sessionOrigin; + } + + private static String describeFormats(List formats) { + if (formats.isEmpty()) { + return "none"; + } + + StringBuilder result = new StringBuilder(); + + for (FormatId format : formats) { + if (result.length() > 0) { + result.append(' '); + } + + result.append(format.getItag()); + + if (format.hasXtags() && !format.getXtags().isEmpty()) { + result.append(':').append(format.getXtags()); + } + } + + return result.toString(); } /** @@ -396,7 +765,7 @@ public VideoPlaybackAbrRequest createVideoPlaybackAbrRequest(int trackType, bool * * @return The format to discard (if any) - typically formats that are active but not currently requested. */ - private Pair, FormatId> addBufferingInfoToAbrRequest(int trackType) { + private Pair, FormatId> addBufferingInfoToAbrRequest(int trackType, @Nullable MediaHeader lastSegment) { SabrStream activeStream = sabrStreams.get(trackType); if (activeStream == null) { @@ -419,7 +788,7 @@ private Pair, FormatId> addBufferingInfoToAbrRequest(int tra int activeFormatKey = activeFormat.getItag(); boolean shouldDiscard = currentFormatKey != activeFormatKey; - MediaHeader initializedFormat = getInitializedFormat(activeFormatKey); + MediaHeader initializedFormat = !shouldDiscard && lastSegment != null ? lastSegment : getInitializedFormat(activeFormatKey); BufferedRange bufferedRange = shouldDiscard ? createFullBufferRange(activeFormat) : createPartialBufferRange(initializedFormat); @@ -467,11 +836,15 @@ private Pair, FormatId> addBufferingInfoToAbrRequest(int tra * @return A BufferedRange object indicating the entire format is buffered. */ private BufferedRange createFullBufferRange(@NonNull FormatId format) { + // FIX: of a live stream, every segment from the first. [MAX, MAX] covered none: its server goes by the segment numbers and + // sent the other track's segment to each request, which threw it away and never got its own (see yt-dlp's consumed range of a + // discarded format: sequence numbers 0 to max). A video's keeps [MAX, MAX]: with [0, MAX] its server sent the other + // track's media headers with no format metadata before them, and the init chunk failed (Initialized format not found). return BufferedRange.newBuilder() .setFormatId(format) .setDurationMs(Integer.MAX_VALUE) .setStartTimeMs(0) - .setStartSegmentIndex(Integer.MAX_VALUE) + .setStartSegmentIndex(isLive() ? 0 : Integer.MAX_VALUE) .setEndSegmentIndex(Integer.MAX_VALUE) .setTimeRange(TimeRange.newBuilder() .setDurationTicks(Integer.MAX_VALUE) @@ -492,6 +865,27 @@ private BufferedRange createPartialBufferRange(MediaHeader initializedFormat) { } int sequenceNumber = initializedFormat.hasSequenceNumber() ? initializedFormat.getSequenceNumber() : 1; + + // A live stream's server goes by the times: the segment's own, in ms. With a start at 0 and the duration's ms as ticks of the + // media's timescale (44100 for audio), the time asked for wasn't buffered, and each request was answered with a seek back to + // the segment's start and no media (see yt-dlp's buffered ranges) + if (isLive() && initializedFormat.hasStartMs() && initializedFormat.getStartMs() >= 0) { + long segmentStartMs = initializedFormat.getStartMs(); + long segmentDurationMs = initializedFormat.hasDurationMs() ? initializedFormat.getDurationMs() : 0; + return BufferedRange.newBuilder() + .setFormatId(initializedFormat.getFormatId()) + .setStartSegmentIndex(sequenceNumber) + .setEndSegmentIndex(sequenceNumber) + .setStartTimeMs(segmentStartMs) + .setDurationMs(segmentDurationMs) + .setTimeRange(TimeRange.newBuilder() + .setTimescale(1_000) + .setStartTicks(segmentStartMs) + .setDurationTicks(segmentDurationMs) + .build()) + .build(); + } + TimeRange timeRange = initializedFormat.hasTimeRange() ? initializedFormat.getTimeRange() : null; int timeScale = timeRange != null && timeRange.hasTimescale() ? timeRange.getTimescale() : 1_000; long startMs = initializedFormat.hasStartMs() ? initializedFormat.getStartMs() : 0; diff --git a/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/manifest/SabrManifestParser.java b/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/manifest/SabrManifestParser.java index 84f51194f15..31192c52029 100644 --- a/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/manifest/SabrManifestParser.java +++ b/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/manifest/SabrManifestParser.java @@ -4,6 +4,7 @@ import android.util.Pair; import androidx.annotation.NonNull; +import androidx.annotation.Nullable; import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.Format; @@ -29,8 +30,8 @@ import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; +import java.util.HashSet; import java.util.List; -import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.TreeSet; @@ -41,6 +42,7 @@ public class SabrManifestParser { private static final String NULL_INDEX_RANGE = "0-0"; private static final String NULL_CONTENT_LENGTH = "0"; private static final int MAX_DURATION_SEC = 48 * 60 * 60; + private static final int DEFAULT_LIVE_SEGMENT_DURATION_SEC = 5; private MediaItemFormatInfo mFormatInfo; private Set mMP4Videos; private Set mWEBMVideos; @@ -48,6 +50,81 @@ public class SabrManifestParser { private Map> mWEBMAudios; private List mSubs; + /** + * The streams of the video the manifest plays, fetched again before they expire (see SabrManifest#refreshSession): put in use when + * they're of the same client and have each of its formats as it was. Its tracks and what they buffered stay. + * + * @return whether they were put in use + */ + public static boolean refresh(SabrManifest manifest, MediaItemFormatInfo formatInfo) { + String url = formatInfo.getServerAbrStreamingUrl(); + String config = formatInfo.getVideoPlaybackUstreamerConfig(); + + if (url == null || config == null || formatInfo.isLive() || manifest.isLive() || formatInfo.getClientInfo() == null + || !Helpers.equals(manifest.getVideoId(), formatInfo.getVideoId()) + || !createClientInfo(formatInfo).equals(manifest.getClientInfo()) + || !hasFormats(manifest, formatInfo.getAdaptiveFormats())) { + return false; + } + + manifest.refreshSession(url, config, formatInfo.getPoToken()); + + return true; + } + + /** + * Each audio and video format of the manifest is one of them: the same itag, last modified time and tags. The requests name the + * formats they're for by these. + */ + private static boolean hasFormats(SabrManifest manifest, @Nullable List formats) { + if (formats == null) { + return false; + } + + Set keys = new HashSet<>(); + + for (MediaFormat format : formats) { + keys.add(getFormatKey(format.getITag(), Helpers.parseLong(format.getLmt()), format.getXtags())); + } + + for (int i = 0; i < manifest.getPeriodCount(); i++) { + for (AdaptationSet adaptationSet : manifest.getPeriod(i).adaptationSets) { + if (adaptationSet.type != C.TRACK_TYPE_AUDIO && adaptationSet.type != C.TRACK_TYPE_VIDEO) { + continue; + } + + for (Representation representation : adaptationSet.representations) { + Format format = representation.format; + + if (!keys.contains(getFormatKey(format.id, format.lastModified, getXtags(format)))) { + return false; + } + } + } + } + + return true; + } + + private static String getFormatKey(@Nullable String itag, long lastModified, @Nullable String xtags) { + return itag + "/" + lastModified + "/" + (xtags != null ? xtags : ""); + } + + @Nullable + private static String getXtags(Format format) { + if (format.metadata == null) { + return null; + } + + for (int i = 0; i < format.metadata.length(); i++) { + if (format.metadata.get(i) instanceof SabrFormatMetadata) { + return ((SabrFormatMetadata) format.metadata.get(i)).xTags; + } + } + + return null; + } + public SabrManifest parse(@NonNull MediaItemFormatInfo formatInfo) { mFormatInfo = formatInfo; MediaFormatComparator comp = new MediaFormatComparator(); @@ -92,12 +169,46 @@ private SabrManifest parseSabrManifest(MediaItemFormatInfo formatInfo) { formatInfo.getPoToken(), formatInfo.getVideoId(), createClientInfo(formatInfo), - formatInfo.getVisitorCookie()); + formatInfo.getVisitorCookie(), + formatInfo.isLive() ? getLiveSegmentTargetDurationSec(formatInfo) : SabrManifest.NOT_LIVE); + } + + /** + * A live segment's length the server's media headers don't give (see SabrProcessor#processMediaHeader): the formats' target (1 s, + * 2 s or 5 s by the stream's latency), else the average the dash info took from the head (see MediaItemFormatInfo#getSegmentDurationUs), + * else a normal latency stream's + */ + private static int getLiveSegmentTargetDurationSec(MediaItemFormatInfo formatInfo) { + if (formatInfo.getAdaptiveFormats() != null) { + for (MediaFormat format : formatInfo.getAdaptiveFormats()) { + if (format.getTargetDurationSec() > 0) { + return format.getTargetDurationSec(); + } + } + } + + int segmentDurationUs = formatInfo.getSegmentDurationUs(); + + return segmentDurationUs > 0 ? Math.max(1, Math.round(segmentDurationUs / 1_000_000f)) : DEFAULT_LIVE_SEGMENT_DURATION_SEC; } + /** + * A video's: its length in whole seconds. A live stream's: the 48 hours its timeline spans from the start segment, as the DASH + * live manifest's segments do (see parseSegmentTemplate). Unset, the player had no duration: SABR representations have no index + * to take it from (see SabrMediaSource.PeriodSeekInfo), and the app's live position is the player's duration less a buffer. + */ private static long getDurationMs(MediaItemFormatInfo formatInfo) { + if (formatInfo.isLive()) { + return MAX_DURATION_SEC * 1_000L; + } + long lenSeconds = Helpers.parseLong(formatInfo.getLengthSeconds()); - return lenSeconds > 0 ? lenSeconds * 1_000 : C.TIME_UNSET; + + if (lenSeconds <= 0) { + return C.TIME_UNSET; + } + + return lenSeconds * 1_000; } private Pair parsePeriod(MediaItemFormatInfo formatInfo) { @@ -222,18 +333,13 @@ private SegmentTemplate parseSegmentTemplate(MediaFormat format) { //long segmentCount = (long) lengthSeconds / targetDurationSec * 10000 / 9999; //int segmentCount = (int)(lengthSeconds * (long) unitsPerSecond / segmentDurationUnits); int segmentCount = (int) Math.ceil(lengthSeconds * (double) unitsPerSecond / segmentDurationUnits); - // Increase offset a bit to compensate previous tweaks - // Streams to check: - // https://www.youtube.com/watch?v=drdemkJpgao - // Live segments: the chunk time from the server is absolute (since the stream start), but YouTube limits the viewing range. - // So don't shift the time and don't build the segment list: count the segments from the fixed segment duration. - long startSegmentNum = mFormatInfo.isLive() ? 0 : mFormatInfo.getStartSegmentNum(); - long offsetUnits = (long) segmentDurationUnits * startSegmentNum; + // The start segment's media time: the number x the average duration + long offsetUnits = (long) segmentDurationUnits * mFormatInfo.getStartSegmentNum(); long timescale = unitsPerSecond; long presentationTimeOffset = offsetUnits; long duration = segmentDurationUnits; - long startNumber = startSegmentNum; + long startNumber = mFormatInfo.getStartSegmentNum(); long endNumber = C.INDEX_UNSET; String url = mFormatInfo.getServerAbrStreamingUrl(); UrlTemplate mediaTemplate = UrlTemplate.compile(url + "&sq=$Number$"); @@ -242,7 +348,7 @@ private SegmentTemplate parseSegmentTemplate(MediaFormat format) { RangedUri initialization = parseRangedUrl(format.getSourceUrl(), format.getInit()); - List timeline = mFormatInfo.isLive() ? null : parseSegmentTimeline(offsetUnits, segmentDurationUnits, segmentCount); + List timeline = parseSegmentTimeline(offsetUnits, segmentDurationUnits, segmentCount); return new SegmentTemplate( initialization, @@ -404,7 +510,8 @@ private RepresentationInfo parseRepresentation(MediaFormat mediaFormat) { SegmentBase segmentBase = null; - if (MediaFormatUtils.isLiveMedia(baseUrl)) { + // Of the stream, not its URL: the SABR URL of a live stream doesn't say it (no live=1), and a finished one's may + if (mFormatInfo.isLive()) { segmentBase = parseSegmentTemplate(mediaFormat); } else if (mediaFormat.getSegmentUrlList() != null) { segmentBase = parseSegmentList(mediaFormat); @@ -717,11 +824,48 @@ protected int getContentType(Format format) { return C.TRACK_TYPE_UNKNOWN; } - private ClientInfo createClientInfo(MediaItemFormatInfo formatInfo) { - MediaItemFormatInfo.ClientInfo clientInfo = formatInfo.getClientInfo(); + private static ClientInfo createClientInfo(MediaItemFormatInfo formatInfo) { + return createClientInfo(formatInfo.getClientInfo()); + } + + /** + * Of the formats fetched again for a new session (see SabrManifest#requestSessionRefresh): null when they have no SABR stream + */ + @Nullable + public static SabrSession parseSession(@Nullable MediaItemFormatInfo formatInfo) { + if (formatInfo == null || formatInfo.getServerAbrStreamingUrl() == null || formatInfo.getVideoPlaybackUstreamerConfig() == null + || formatInfo.getClientInfo() == null || formatInfo.getAdaptiveFormats() == null) { + return null; + } + + ClientInfo clientInfo; + + try { + clientInfo = createClientInfo(formatInfo.getClientInfo()); + } catch (RuntimeException e) { + return null; // not a client the requests know (see ClientName) + } + + Set itags = new HashSet<>(); + for (MediaFormat format : formatInfo.getAdaptiveFormats()) { + int itag = Helpers.parseInt(format.getITag()); + + if (itag > 0) { + itags.add(itag); + } + } + + return new SabrSession(formatInfo.getServerAbrStreamingUrl(), formatInfo.getVideoPlaybackUstreamerConfig(), + formatInfo.getPoToken(), clientInfo, itags); + } + + /** + * Of the SABR requests (see StreamerContext) + */ + public static ClientInfo createClientInfo(MediaItemFormatInfo.ClientInfo clientInfo) { return ClientInfo.newBuilder() - .setClientName(ClientName.valueOf(clientInfo.getClientName().toUpperCase(Locale.ROOT))) + .setClientName(ClientName.valueOf(clientInfo.getClientName().toUpperCase())) .setClientVersion(clientInfo.getClientVersion()) .setOsName(clientInfo.getOsName()) .setOsVersion(clientInfo.getOsVersion()) diff --git a/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/manifest/SabrSession.java b/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/manifest/SabrSession.java new file mode 100644 index 00000000000..060140c3864 --- /dev/null +++ b/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/manifest/SabrSession.java @@ -0,0 +1,37 @@ +package com.google.android.exoplayer2.source.sabr.manifest; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; + +import com.google.android.exoplayer2.source.sabr.protos.videostreaming.StreamerContext.ClientInfo; + +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; + +/** + * What a player response gives a SABR stream to be streamed with: its URL, its ustreamer config and its poToken. The server asks for + * another one when they expire, about 6 h in (see SabrManifest#requestSessionRefresh). + */ +public final class SabrSession { + public final String serverAbrStreamingUrl; + public final String videoPlaybackUstreamerConfig; + @Nullable public final String poToken; + /** + * Of the client the player response was asked of: another client's session doesn't go with the stream's requests + */ + public final ClientInfo clientInfo; + /** + * Of the player response's formats: the stream's are to be among them + */ + public final Set itags; + + public SabrSession(@NonNull String serverAbrStreamingUrl, @NonNull String videoPlaybackUstreamerConfig, @Nullable String poToken, + @NonNull ClientInfo clientInfo, @NonNull Set itags) { + this.serverAbrStreamingUrl = serverAbrStreamingUrl; + this.videoPlaybackUstreamerConfig = videoPlaybackUstreamerConfig; + this.poToken = poToken; + this.clientInfo = clientInfo; + this.itags = Collections.unmodifiableSet(new HashSet<>(itags)); + } +} diff --git a/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/parser/SabrProcessor.java b/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/parser/SabrProcessor.java index f6bd752a9d0..3d1e48cda43 100644 --- a/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/parser/SabrProcessor.java +++ b/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/parser/SabrProcessor.java @@ -3,6 +3,7 @@ import android.util.Base64; import androidx.annotation.NonNull; +import androidx.annotation.Nullable; import com.google.android.exoplayer2.extractor.ExtractorInput; import com.google.android.exoplayer2.source.sabr.parser.exceptions.SabrPoTokenError; @@ -61,7 +62,10 @@ public class SabrProcessor { private final int liveSegmentTargetDurationToleranceMs; private final int liveSegmentTargetDurationSec; private long playerTimeMs; - private final String poToken; + /** + * Replaced when the streams are fetched again (see SabrManifest#refreshSession, #requestSessionRefresh). Read on the loader's thread. + */ + private volatile String poToken; private final boolean postLive; private final String videoId; private final long durationMs; @@ -69,12 +73,17 @@ public class SabrProcessor { private final Map selectedFormats; private Status streamProtectionStatus; private boolean isLive; - private LiveMetadata liveMetadata; + private volatile LiveMetadata liveMetadata; // read on the playback thread too (see getLiveHeadSequenceNumber) private long totalDurationMs; private NextRequestPolicy nextRequestPolicy; private final Map sabrContextUpdates; private final Set sabrContextsToSend; private final Map initializedFormats; + /** + * Of a live stream, the newest media segment's header of each format as soon as it's read, its media still to come, with its + * start and duration (estimated when the header has none). Cleared by a reset (a seek). See getNewestLiveHeader. + */ + private final Map newestLiveHeaders = new java.util.concurrent.ConcurrentHashMap<>(); private final FormatSelector emptySelector; private SabrStreamError unthrownError; @@ -223,6 +232,16 @@ public ProcessMediaHeaderResult processMediaHeader(MediaHeader mediaHeader) { String.format("Cannot determine duration of segment %s (media_header=%s)", sequenceNumber, mediaHeader)); } + // Known before its media: a live seek's prefetch goes on from it at once (initializedFormats has it only at its MEDIA_END) + boolean hasStart = mediaHeader.hasStartMs() || timeRange != null && timeRange.hasStartTicks() && timeRange.hasTimescale(); + + if (isLive() && !isInitSegment && hasStart) { + newestLiveHeaders.put(mediaHeader.getItag(), mediaHeader.toBuilder() + .setStartMs(startMs) + .setDurationMs(durationMs) + .build()); + } + long estimatedContentLength = NO_VALUE; if (isLive() && !mediaHeader.hasContentLength() && mediaHeader.hasBitrateBps()) { estimatedContentLength = (long) Math.ceil(mediaHeader.getBitrateBps() * ((double) durationMs / 1_000)); @@ -268,9 +287,6 @@ public ProcessMediaHeaderResult processMediaHeader(MediaHeader mediaHeader) { Log.d(TAG, "Initialized Media Header %s for sequence %s. Segment: %s", Utils.toLong(mediaHeader.getHeaderId()), sequenceNumber, segment); -// Log.d(TAG, "Header times: seq=%s, hasStartMs=%s, startMs=%s, hasTimeRange=%s, actualDurationMs=%s, grid=%s", -// sequenceNumber, mediaHeader.hasStartMs(), startMs, timeRange != null, actualDurationMs, -// (long) sequenceNumber * getLiveSegmentTargetDurationSec() * 1_000L); return result; } @@ -318,18 +334,10 @@ public ProcessMediaEndResult processMediaEnd(long headerId) { if (!segment.mediaHeader.getIsInitSeg()) { MediaHeader mediaHeader = segment.mediaHeader; - // Live headers have neither start_ms nor duration_ms (the start is in time_range). Without them the next - // request is made from 0 and the chunk times stay unset. The real start is NOT on the target duration grid - // (start = number * target + offset), so use it as is. Aim the next request - // just inside the next segment: the exact boundary still belongs to the previous one and the server would resend it forever. - if (isLive()) { - long targetMs = getLiveSegmentTargetDurationSec() * 1_000L; - long toNextSegmentMs = targetMs + getLiveSegmentTargetDurationToleranceMs(); - - mediaHeader = mediaHeader.toBuilder() - .setStartMs(segment.startMs) - .setDurationMs(toNextSegmentMs) - .build(); + // A live segment's header has no duration: the estimate is kept (see processMediaHeader), or the next request asks for the + // time this segment starts at (see getSegmentStartTimeMs) + if (isLive() && !mediaHeader.hasDurationMs() && segment.durationMs > 0) { + mediaHeader = mediaHeader.toBuilder().setDurationMs(segment.durationMs).build(); } initializedFormats.put(mediaHeader.getItag(), mediaHeader); @@ -570,7 +578,8 @@ public ProcessLiveMetadataResult processLiveMetadata(LiveMetadata liveMetadata) // If the current player time is less than the min dvr time, simulate a server seek to the min dvr time. // The server SHOULD send us a SABR_SEEK part in this case, but it does not always happen (e.g. ANDROID_VR) // The server SHOULD NOT send us segments before the min dvr time, so we should assume that the player time is correct. - long minSeekableTimeMs = getMinSeekableTimeMs(); + long minSeekableTimeMs = Utils.ticksToMs(liveMetadata.hasMinSeekableTimeTicks() ? liveMetadata.getMinSeekableTimeTicks() : -1, + liveMetadata.hasMinSeekableTimescale() ? liveMetadata.getMinSeekableTimescale() : -1); if (minSeekableTimeMs != -1 && playerTimeMs > 0 && playerTimeMs < minSeekableTimeMs) { Log.d(TAG, "Player time %s is less than min seekable time %s, simulating server seek", playerTimeMs, minSeekableTimeMs); @@ -661,6 +670,10 @@ public void processSabrContextSendingPolicy(SabrContextSendingPolicy sabrCtxSend } } + public boolean isLive() { + return liveMetadata != null || isLive; + } + /** * @return position to start a live stream from (near the live edge) or -1 if unknown. * Without it the first request is made at 0 and the server answers with the head segment out of order. @@ -680,25 +693,37 @@ public long getLiveEdgeMs() { } public long getMinSeekableTimeMs() { - return liveMetadata == null ? -1 : Utils.ticksToMs( - liveMetadata.hasMinSeekableTimeTicks() ? liveMetadata.getMinSeekableTimeTicks() : -1, - liveMetadata.hasMinSeekableTimescale() ? liveMetadata.getMinSeekableTimescale() : -1); + LiveMetadata metadata = liveMetadata; + + return metadata == null ? -1 : Utils.ticksToMs( + metadata.hasMinSeekableTimeTicks() ? metadata.getMinSeekableTimeTicks() : -1, + metadata.hasMinSeekableTimescale() ? metadata.getMinSeekableTimescale() : -1); } public long getMaxSeekableTimeMs() { - return liveMetadata == null ? -1 : Utils.ticksToMs( - liveMetadata.hasMaxSeekableTimeTicks() ? liveMetadata.getMaxSeekableTimeTicks() : -1, - liveMetadata.hasMaxSeekableTimescale() ? liveMetadata.getMaxSeekableTimescale() : -1); + LiveMetadata metadata = liveMetadata; + + return metadata == null ? -1 : Utils.ticksToMs( + metadata.hasMaxSeekableTimeTicks() ? metadata.getMaxSeekableTimeTicks() : -1, + metadata.hasMaxSeekableTimescale() ? metadata.getMaxSeekableTimescale() : -1); } - public boolean isLive() { - return liveMetadata != null || isLive; + public long getLiveHeadSequenceNumber() { + LiveMetadata metadata = liveMetadata; + return metadata != null && metadata.hasHeadSequenceNumber() ? metadata.getHeadSequenceNumber() : -1; } public void setLive(boolean isLive) { this.isLive = isLive; } + /** + * Of the streams fetched again (see SabrManifest#refreshSession, #requestSessionRefresh): the requests from now on send it + */ + public void setPoToken(@Nullable String poToken) { + this.poToken = poToken; + } + public int getLiveSegmentTargetDurationToleranceMs() { return liveSegmentTargetDurationToleranceMs; } @@ -829,7 +854,17 @@ public void setFormatSelector(FormatSelector formatSelector) { return initializedFormats; } + /** + * Of a live stream, the newest media segment's header read for the format since the last reset, its media maybe still to come; + * null for none + */ + @Nullable + public MediaHeader getNewestLiveHeader(int iTag) { + return newestLiveHeaders.get(iTag); + } + public void reset(int iTag) { + newestLiveHeaders.remove(iTag); MediaHeader mediaHeader = initializedFormats.get(iTag); if (mediaHeader != null) { diff --git a/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/parser/SabrStream.java b/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/parser/SabrStream.java index 96ece8fbe03..1c85f126c61 100644 --- a/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/parser/SabrStream.java +++ b/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/parser/SabrStream.java @@ -1,17 +1,24 @@ package com.google.android.exoplayer2.source.sabr.parser; import androidx.annotation.NonNull; +import androidx.annotation.Nullable; import com.google.android.exoplayer2.extractor.ExtractorInput; -import com.google.android.exoplayer2.source.sabr.parser.exceptions.SabrSegmentMismatchError; +import com.google.android.exoplayer2.source.sabr.parser.exceptions.BrokenPartError; +import com.google.android.exoplayer2.source.sabr.parser.exceptions.BrokenResponseError; +import com.google.android.exoplayer2.source.sabr.parser.exceptions.MediaSegmentMismatchError; +import com.google.android.exoplayer2.source.sabr.parser.exceptions.SabrProtocolError; import com.google.android.exoplayer2.source.sabr.parser.exceptions.SabrStreamError; +import com.google.android.exoplayer2.source.sabr.parser.exceptions.UnknownPartError; import com.google.android.exoplayer2.source.sabr.parser.models.FormatSelector; import com.google.android.exoplayer2.source.sabr.parser.parts.FormatInitializedSabrPart; import com.google.android.exoplayer2.source.sabr.parser.parts.MediaSeekSabrPart; import com.google.android.exoplayer2.source.sabr.parser.parts.MediaSegmentDataSabrPart; import com.google.android.exoplayer2.source.sabr.parser.parts.MediaSegmentEndSabrPart; import com.google.android.exoplayer2.source.sabr.parser.parts.MediaSegmentInitSabrPart; +import com.google.android.exoplayer2.source.sabr.parser.exceptions.SabrPoTokenError; import com.google.android.exoplayer2.source.sabr.parser.parts.PoTokenStatusSabrPart; +import com.google.android.exoplayer2.source.sabr.parser.parts.PoTokenStatusSabrPart.PoTokenStatus; import com.google.android.exoplayer2.source.sabr.parser.parts.RefreshPlayerResponseSabrPart; import com.google.android.exoplayer2.source.sabr.parser.parts.SabrPart; import com.google.android.exoplayer2.source.sabr.parser.results.ProcessFormatInitializationMetadataResult; @@ -35,18 +42,35 @@ import com.google.android.exoplayer2.source.sabr.protos.videostreaming.StreamProtectionStatus; import com.google.android.exoplayer2.source.sabr.protos.videostreaming.StreamerContext; import com.google.android.exoplayer2.source.sabr.protos.videostreaming.StreamerContext.ClientInfo; +import com.google.android.exoplayer2.upstream.HttpDataSource.HttpDataSourceException; +import com.google.protobuf.InvalidProtocolBufferException; import com.liskovsoft.sharedutils.helpers.Helpers; import com.liskovsoft.sharedutils.mylogger.Log; import com.liskovsoft.sharedutils.querystringparser.UrlQueryString; import com.liskovsoft.sharedutils.querystringparser.UrlQueryStringFactory; import java.io.IOException; +import java.io.InterruptedIOException; +import java.net.SocketTimeoutException; import java.util.HashSet; import java.util.List; import java.util.Set; public class SabrStream { private static final String TAG = SabrStream.class.getSimpleName(); + /** + * Media responses in a row with no media while the poToken's attestation was pending: the server is withholding it (see + * #onResponseEnd). Fewer is a response with none for another reason, e.g. a redirect. + */ + private static final int MAX_PENDING_RESPONSES_WITHOUT_MEDIA = 3; + /** + * Of an unknown part, the bytes after its header told (see #peekHex) + */ + private static final int PEEKED_BYTES = 16; + /** + * How many of the parts read last a broken response tells (see #getPartTrail) + */ + private static final int PART_TRAIL_LENGTH = 8; private final int[] KNOWN_PARTS = { UMPPartId.MEDIA_HEADER, UMPPartId.MEDIA, @@ -55,8 +79,8 @@ public class SabrStream { UMPPartId.SABR_REDIRECT, UMPPartId.FORMAT_INITIALIZATION_METADATA, UMPPartId.NEXT_REQUEST_POLICY, - UMPPartId.LIVE_METADATA, - //UMPPartId.SABR_SEEK, + UMPPartId.LIVE_METADATA, // a live stream's head and seekable range, in each response + UMPPartId.SABR_SEEK, // e.g. to a live stream's head, when the time asked for is out of its range UMPPartId.SABR_ERROR, UMPPartId.SABR_CONTEXT_UPDATE, UMPPartId.SABR_CONTEXT_SENDING_POLICY, @@ -83,6 +107,82 @@ public class SabrStream { private boolean receivedNewSegments; private String url; private List multiResult = null; + private int segmentItag = -1; + private long segmentSequenceNumber = -1; + /** + * The request being read is the init chunk's (see DefaultSabrChunkSource#newInitializationChunk): its response ends with the + * init segment (see SabrExtractorInput) + */ + private volatile boolean isInitRequest; + @Nullable private volatile IOException responseError; + @Nullable private static volatile BackoffListener backoffListener; + @Nullable private static volatile ProtectionStatusListener protectionStatusListener; + @Nullable private static volatile RedirectListener redirectListener; + @Nullable private final String videoId; + /** + * The server's last word on the poToken, which each response has (see ProtectionStatusListener), null before the first + */ + @Nullable private volatile PoTokenStatus protectionStatus; + /** + * Media responses in a row that came with no media while the attestation was pending (see #onResponseEnd) + */ + private int pendingResponsesWithoutMedia; + /** + * The NextRequestPolicy parts read so far: one read since a request was made came in its answer (see #getBackoffTimeMs, which is + * the last one's) + */ + private volatile int nextRequestPolicyCount; + /** + * The parts the response being read gave, the last PART_TRAIL_LENGTH of them (see #getPartTrail). On the loader's thread, as the + * parts are read. + */ + private final int[] partTrailIds = new int[PART_TRAIL_LENGTH]; + private final int[] partTrailSizes = new int[PART_TRAIL_LENGTH]; + private int partTrailCount; + /** + * Where the last part's header ended in its response, -1 before the first + */ + private long partTrailPosition = -1; + + /** + * Told each wait the server asks for (see NextRequestPolicy#getBackoffTimeMs), e.g. for the app's timing of video starts: one + * under SabrExtractorInput's MIN_SWALLOW_BACKOFF_MS isn't waited, unless an init request's answer had no init segment (see + * DefaultSabrChunkSource#maybeWaitForInit). On the loader's thread. + */ + public interface BackoffListener { + void onBackoff(int backoffMs); + } + + public static void setBackoffListener(@Nullable BackoffListener listener) { + backoffListener = listener; + } + + /** + * Told what the server makes of the poToken (see SabrProcessor#processStreamProtectionStatus), e.g. for the app's diagnostics: + * a stream's first status, then each change. On the loader's thread. + */ + public interface ProtectionStatusListener { + void onProtectionStatus(@Nullable String videoId, PoTokenStatus status); + } + + public static void setProtectionStatusListener(@Nullable ProtectionStatusListener listener) { + protectionStatusListener = listener; + } + + /** + * Told the URL the server sends the stream to from now on (see SabrRedirect), e.g. for the app to connect to its host ahead of the + * next request, which otherwise opens a connection of its own. On the loader's thread, while the response that said so is read. + */ + public interface RedirectListener { + /** + * @param fromUrl the stream's URL before, null for none + */ + void onRedirect(@Nullable String fromUrl, String toUrl); + } + + public static void setRedirectListener(@Nullable RedirectListener listener) { + redirectListener = listener; + } private static class NoSegmentsTracker { public int consecutiveRequests = 0; @@ -128,6 +228,7 @@ public SabrStream( durationMs ); url = serverAbrStreamingUrl; + this.videoId = videoId; // Whether we got any new (not consumed) segments in the request noNewSegmentsTracker = new NoSegmentsTracker(); @@ -141,60 +242,119 @@ public SabrStream( public SabrPart parse(@NonNull ExtractorInput extractorInput) { SabrPart result = null; - while (result == null && (multiResult == null || multiResult.isEmpty())) { - UMPPart part = nextKnownUMPPart(extractorInput); + try { + while (result == null && (multiResult == null || multiResult.isEmpty())) { + UMPPart part = nextKnownUMPPart(extractorInput); - if (part == null) { - break; - } + if (part == null) { + break; + } - result = parsePart(part); + result = parsePart(part); - if (result == null) { - multiResult = parseMultiPart(part); + if (result == null) { + multiResult = parseMultiPart(part); + } } + } catch (BrokenResponseError e) { + // Where in the response it went wrong, told with the error: a first part is a response that isn't UMP, a later one a read + // that went out of step + e.setPartTrail(getPartTrail()); + + throw e; + } + + if (result instanceof MediaSegmentDataSabrPart) { + MediaSegmentDataSabrPart data = (MediaSegmentDataSabrPart) result; + segmentItag = data.formatId.getItag(); + segmentSequenceNumber = data.sequenceNumber; } return result != null ? result : multiResult != null && !multiResult.isEmpty() ? multiResult.remove(0) : null; } - public void reset() { - noNewSegmentsTracker.reset(); + /** + * Itag of the segment whose media is being read, -1 before the first one. + */ + public int getSegmentItag() { + return segmentItag; } - public void reset(int iTag) { - processor.reset(iTag); + /** + * Sequence number of the segment whose media is being read, -1 before the first one or for an init segment. + */ + public long getSegmentSequenceNumber() { + return segmentSequenceNumber; } - public FormatSelector getFormatSelector() { - return processor.getFormatSelector(); + /** + * The connection broke in the middle of a response, which ended early with the media it had. + */ + public void setResponseError(IOException error) { + responseError = error; } - public void setFormatSelector(FormatSelector formatSelector) { - processor.setFormatSelector(formatSelector); + /** + * The connection error that ended a response early since the last call, null if none did. + */ + @Nullable + public IOException pollResponseError() { + IOException error = responseError; + responseError = null; + return error; } - public long getSegmentStartTimeMs(int iTag) { - return processor.getSegmentStartTimeMs(iTag); + /** + * The data source failed on the connection: an I/O error under it. An answer of the server (a response code, a content type) + * has none, and an interrupted read is a canceled load. SABR wraps it in an IllegalStateException (see UMPDecoder). + */ + @Nullable + public static IOException getConnectionError(Throwable error) { + for (Throwable cause = error; cause != null; cause = cause.getCause()) { + if (cause instanceof HttpDataSourceException) { + Throwable ioError = cause.getCause(); + boolean canceled = ioError instanceof InterruptedIOException && !(ioError instanceof SocketTimeoutException); + return ioError instanceof IOException && !canceled ? (IOException) cause : null; + } + } + + return null; + } + + public void reset() { + noNewSegmentsTracker.reset(); } /** - * How far below the video's total duration (in ms) a seek target should be clamped when it - * would otherwise land at/past the end (see DefaultSabrChunkSource.getAdjustedSeekPositionUs()). - * Based on the same live-segment-target-duration estimate SabrProcessor uses for a segment's own duration. - *

- * Currently unused - the fixed constant in DefaultSabrChunkSource was consistently smaller - * (safer) on tested content. Kept for future use. + * Another response is read before the last one was read to its end (a seek cancelled its chunk, see SabrExtractorInput#init): the + * parts parsed from the last one and not taken yet aren't this one's */ - public long getEndOfStreamSeekToleranceMs() { - return processor.getLiveSegmentTargetDurationSec() * 1_000L - - processor.getLiveSegmentTargetDurationToleranceMs(); + public void onNewResponse() { + multiResult = null; + } + + /** + * A live stream's media headers have no duration: it's estimated from the target duration (see SabrProcessor#processMediaHeader). + * Known from the format info before the first response, whose live metadata says it too. + */ + public void setLive(boolean isLive) { + processor.setLive(isLive); + } + + /** + * Of the streams fetched again (see SabrManifest#refreshSession, #requestSessionRefresh): the requests from now on send it + */ + public void setPoToken(@Nullable String poToken) { + processor.setPoToken(poToken); } public boolean isLive() { return processor.isLive(); } + /** + * Of a live stream, the newest segment the server has (see LiveMetadata), -1 before it says + */ public long getLiveSegmentDurationMs() { return processor.getLiveSegmentTargetDurationSec() * 1_000L; } @@ -211,6 +371,39 @@ public long getMinSeekableTimeMs() { return processor.getMinSeekableTimeMs(); } + public long getLiveHeadSequenceNumber() { + return processor.getLiveHeadSequenceNumber(); + } + + public void reset(int iTag) { + processor.reset(iTag); + } + + public FormatSelector getFormatSelector() { + return processor.getFormatSelector(); + } + + public void setFormatSelector(FormatSelector formatSelector) { + processor.setFormatSelector(formatSelector); + } + + public long getSegmentStartTimeMs(int iTag) { + return processor.getSegmentStartTimeMs(iTag); + } + + /** + * How far below the video's total duration (in ms) a seek target should be clamped when it + * would otherwise land at/past the end (see DefaultSabrChunkSource.getAdjustedSeekPositionUs()). + * Based on the same live-segment-target-duration estimate SabrProcessor uses for a segment's own duration. + *

+ * Currently unused - the fixed constant in DefaultSabrChunkSource was consistently smaller + * (safer) on tested content. Kept for future use. + */ + public long getEndOfStreamSeekToleranceMs() { + return processor.getLiveSegmentTargetDurationSec() * 1_000L + - processor.getLiveSegmentTargetDurationToleranceMs(); + } + public boolean hasSegmentStartTime(int iTag) { return processor.hasSegmentStartTime(iTag); } @@ -219,6 +412,14 @@ public long getSegmentDurationMs(int iTag) { return processor.getSegmentDurationMs(iTag); } + public void setInitRequest(boolean isInitRequest) { + this.isInitRequest = isInitRequest; + } + + public boolean isInitRequest() { + return isInitRequest; + } + public int getBackoffTimeMs() { return processor.getBackoffTimeMs(); } @@ -227,10 +428,25 @@ public SabrStreamError getUnthrownError() { return processor.getUnthrownError(); } + /** + * The NextRequestPolicy parts read so far: compared with the count when a request was made, one came in its answer + */ + public int getNextRequestPolicyCount() { + return nextRequestPolicyCount; + } + public MediaHeader getInitializedFormat(int iTag) { return processor.getInitializedFormats().get(iTag); } + /** + * See SabrProcessor#getNewestLiveHeader + */ + @Nullable + public MediaHeader getNewestLiveHeader(int iTag) { + return processor.getNewestLiveHeader(iTag); + } + public StreamerContext createStreamerContext() { return processor.createStreamerContext(); } @@ -264,6 +480,9 @@ private SabrPart parsePart(UMPPart part) { return null; case UMPPartId.RELOAD_PLAYER_RESPONSE: return processReloadPlayerResponse(part); + case UMPPartId.LIVE_METADATA: + case UMPPartId.SABR_SEEK: + return null; // parts of their own (see parseMultiPart) } if (!contains(IGNORED_PARTS, part.partId)) { @@ -292,14 +511,14 @@ private MediaSegmentInitSabrPart processMediaHeader(UMPPart part) { try { mediaHeader = MediaHeader.parseFrom(part.toStream()); } catch (IOException e) { - throw new IllegalStateException(e); + throw partError(e); } try { ProcessMediaHeaderResult result = processor.processMediaHeader(mediaHeader); return result.sabrPart; - } catch (SabrSegmentMismatchError e) { + } catch (MediaSegmentMismatchError e) { // For livestreams, the server may not know the exact segment for a given player time. // For segments near stream head, it estimates using segment duration, which can cause off-by-one segment mismatches. // If a segment is much longer or shorter than expected, the server may return a segment ahead or behind. @@ -360,13 +579,49 @@ private PoTokenStatusSabrPart processStreamProtectionStatus(UMPPart part) { try { sps = StreamProtectionStatus.parseFrom(part.toStream()); } catch (IOException e) { - throw new IllegalStateException(e); + throw partError(e); } Log.d(TAG, "Process StreamProtectionStatus: %s", sps); ProcessStreamProtectionStatusResult result = processor.processStreamProtectionStatus(sps); + PoTokenStatusSabrPart sabrPart = result.sabrPart; + ProtectionStatusListener listener = protectionStatusListener; - return result.sabrPart; + // Each response has it: told once, then when it changes + if (sabrPart != null && sabrPart.status != protectionStatus) { + protectionStatus = sabrPart.status; + + if (listener != null) { + listener.onProtectionStatus(videoId, sabrPart.status); + } + } + + return sabrPart; + } + + /** + * A media request's response was read to its end (see SabrExtractorInput). With the poToken's attestation pending, the server + * sends a minute of the video (its grace period), then answers each request at once with no media: the player stalled at + * 0:59 and the same client's reload froze there (51AQC7FS, BQ0MY38T). A live stream's response has none while the + * segment asked for doesn't exist yet (see DefaultSabrChunkSource#maybeWaitForLiveSegment). + * + * @param hasMedia a media segment came in it + * @return the poToken's status when the server withholds the media for it: pending, with no media in the last + * MAX_PENDING_RESPONSES_WITHOUT_MEDIA responses. Null otherwise. + */ + @Nullable + public PoTokenStatus onResponseEnd(boolean hasMedia) { + PoTokenStatus status = protectionStatus; + boolean isPending = status == PoTokenStatus.PENDING || status == PoTokenStatus.PENDING_MISSING; + + if (hasMedia || !isPending || isLive()) { + pendingResponsesWithoutMedia = 0; + return null; + } + + pendingResponsesWithoutMedia++; + + return pendingResponsesWithoutMedia >= MAX_PENDING_RESPONSES_WITHOUT_MEDIA ? status : null; } private void processSabrRedirect(UMPPart part) { @@ -375,7 +630,7 @@ private void processSabrRedirect(UMPPart part) { try { sabrRedirect = SabrRedirect.parseFrom(part.toStream()); } catch (IOException e) { - throw new IllegalStateException(e); + throw partError(e); } Log.d(TAG, "Process SabrRedirect: %s", sabrRedirect); @@ -385,7 +640,18 @@ private void processSabrRedirect(UMPPart part) { return; } + String fromUrl = this.url; setUrl(sabrRedirect.getRedirectUrl()); + RedirectListener listener = redirectListener; + + if (listener != null) { + try { + listener.onRedirect(fromUrl, this.url); + } catch (RuntimeException e) { + // The stream goes on without it + Log.e(TAG, "Redirect listener failed: %s", e.getMessage()); + } + } } private FormatInitializedSabrPart processFormatInitializationMetadata(UMPPart part) { @@ -394,7 +660,7 @@ private FormatInitializedSabrPart processFormatInitializationMetadata(UMPPart pa try { fmtInitMetadata = FormatInitializationMetadata.parseFrom(part.toStream()); } catch (IOException e) { - throw new IllegalStateException(e); + throw partError(e); } Log.d(TAG, "Process FormatInitializationMetadata: %s", fmtInitMetadata); @@ -409,11 +675,17 @@ private void processNextRequestPolicy(UMPPart part) { try { nextRequestPolicy = NextRequestPolicy.parseFrom(part.toStream()); } catch (IOException e) { - throw new IllegalStateException(e); + throw partError(e); } Log.d(TAG, "Process NextRequestPolicy: %s", nextRequestPolicy); processor.processNextRequestPolicy(nextRequestPolicy); + nextRequestPolicyCount++; + BackoffListener listener = backoffListener; + + if (listener != null && nextRequestPolicy.getBackoffTimeMs() > 0) { + listener.onBackoff(nextRequestPolicy.getBackoffTimeMs()); + } } private void processSabrError(UMPPart part) { @@ -422,11 +694,11 @@ private void processSabrError(UMPPart part) { try { sabrError = SabrError.parseFrom(part.toStream()); } catch (IOException e) { - throw new IllegalStateException(e); + throw partError(e); } Log.d(TAG, "Process SabrError: %s", sabrError); - throw new SabrStreamError(String.format("SABR Protocol Error: %s", sabrError)); + throw new SabrProtocolError(sabrError); } private void processSabrContextUpdate(UMPPart part) { @@ -435,7 +707,7 @@ private void processSabrContextUpdate(UMPPart part) { try { sabrCtxUpdate = SabrContextUpdate.parseFrom(part.toStream()); } catch (IOException e) { - throw new IllegalStateException(e); + throw partError(e); } Log.d(TAG, "Process SabrContextUpdate: %s", sabrCtxUpdate); @@ -448,7 +720,7 @@ private void processSabrContextSendingPolicy(UMPPart part) { try { sabrCtxSendingPolicy = SabrContextSendingPolicy.parseFrom(part.toStream()); } catch (IOException e) { - throw new IllegalStateException(e); + throw partError(e); } Log.d(TAG, "Process SabrContextSendingPolicy: %s", sabrCtxSendingPolicy); @@ -474,7 +746,7 @@ private RefreshPlayerResponseSabrPart processReloadPlayerResponse(UMPPart part) try { reloadPlayerResponse = ReloadPlayerResponse.parseFrom(part.toStream()); } catch (IOException e) { - throw new IllegalStateException(e); + throw partError(e); } Log.d(TAG, "Process ReloadPlayerResponse: %s", reloadPlayerResponse); @@ -491,7 +763,7 @@ private List processLiveMetadata(UMPPart part) { try { liveMetadata = LiveMetadata.parseFrom(part.toStream()); } catch (IOException e) { - throw new IllegalStateException(e); + throw partError(e); } Log.d(TAG, "Process LiveMetadata: %s", liveMetadata); @@ -504,7 +776,7 @@ private List processSabrSeek(UMPPart part) { try { sabrSeek = SabrSeek.parseFrom(part.toStream()); } catch (IOException e) { - throw new IllegalStateException(e); + throw partError(e); } Log.d(TAG, "Process SabrSeek: %s", sabrSeek); @@ -531,6 +803,8 @@ private UMPPart nextKnownUMPPart(@NonNull ExtractorInput extractorInput) { break; } + rememberPart(part); + // Normal reading: 47, 58. 52, 53, 42, 35, 20, 21, 22, 20... if (contains(KNOWN_PARTS, part.partId)) { Log.d(TAG, "Found known part: id=%s, size=%s, position=%s", part.partId, part.size, part.data.getPosition()); @@ -538,7 +812,8 @@ private UMPPart nextKnownUMPPart(@NonNull ExtractorInput extractorInput) { } else { String msg = String.format("Unknown part encountered: id=%s, size=%s, position=%s", part.partId, part.size, part.data.getPosition()); if (part.partId > 100) { - throw new IllegalStateException(msg); + // With what came after its header: a UMP part's, or another kind of response's (e.g. a page) + throw new UnknownPartError(msg + ", then " + peekHex(part)); } Log.e(TAG, msg); @@ -553,6 +828,80 @@ private UMPPart nextKnownUMPPart(@NonNull ExtractorInput extractorInput) { return part; } + private void rememberPart(UMPPart part) { + long position = part.data.getPosition(); + + // Where the response is read to, past the last part's within a response (its header and payload come between): not past it is + // another response's first part + if (position <= partTrailPosition) { + partTrailCount = 0; + } + + partTrailPosition = position; + partTrailIds[partTrailCount % PART_TRAIL_LENGTH] = part.partId; + partTrailSizes[partTrailCount % PART_TRAIL_LENGTH] = part.size; + partTrailCount++; + } + + /** + * The parts of the response being read, the last PART_TRAIL_LENGTH of them oldest first, as "id:size", e.g. "35:12 20:1500": the + * broken part is the last. Only itself for a response whose first part it was. + */ + /* package */ String getPartTrail() { + StringBuilder trail = new StringBuilder(); + + for (int i = Math.max(0, partTrailCount - PART_TRAIL_LENGTH); i < partTrailCount; i++) { + if (trail.length() > 0) { + trail.append(' '); + } + + trail.append(partTrailIds[i % PART_TRAIL_LENGTH]).append(':').append(partTrailSizes[i % PART_TRAIL_LENGTH]); + } + + return trail.toString(); + } + + /** + * A part's payload that doesn't read as the protobuf its id says is a broken response (see BrokenPartError). Any other failure of + * the read is the connection's, under the same wrapper as before. + */ + private static IllegalStateException partError(IOException e) { + return e instanceof InvalidProtocolBufferException ? new BrokenPartError(e.toString(), e) : new IllegalStateException(e); + } + + /** + * The first bytes after the part's header, in hex, e.g. "3c 21 44 4f": not read past (peeked, then put back) + */ + private static String peekHex(UMPPart part) { + byte[] bytes = new byte[Math.max(0, Math.min(part.size, PEEKED_BYTES))]; + + try { + if (bytes.length == 0 || !part.data.peekFully(bytes, 0, bytes.length, true)) { + return "no bytes"; + } + } catch (IOException e) { + return "no bytes (" + e.getClass().getSimpleName() + ")"; + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return "no bytes (interrupted)"; + } finally { + part.data.resetPeekPosition(); + } + + StringBuilder result = new StringBuilder(); + + for (byte value : bytes) { + if (result.length() > 0) { + result.append(' '); + } + + int unsigned = value & 0xFF; + result.append(unsigned < 0x10 ? "0" : "").append(Integer.toHexString(unsigned)); + } + + return result.toString(); + } + public String getUrl() { return this.url; } @@ -561,14 +910,23 @@ public void setServerAbrStreamingUrl(String url) { setUrl(url); } + /** + * Whether the stream can go on at the URL: not a live stream's of another broadcast, which it would have to start again at + */ + public boolean acceptsUrl(@Nullable String url) { + if (!processor.isLive() || this.url == null) { + return true; + } + + return url != null && Helpers.equals(UrlQueryStringFactory.parse(url).get("id"), UrlQueryStringFactory.parse(this.url).get("id")); + } + private void setUrl(String url) { Log.d(TAG, "New URL: %s", url); UrlQueryString newQueryString = UrlQueryStringFactory.parse(url); - UrlQueryString oldQueryString = UrlQueryStringFactory.parse(this.url); - String bn = newQueryString.get("id"); - String bc = oldQueryString.get("id"); - if (processor.isLive() && this.url != null && !Helpers.equals(bn, bc)) { - throw new SabrStreamError(String.format("Broadcast ID changed from %s to %s. The download will need to be restarted.", bc, bn)); + if (!acceptsUrl(url)) { + String bc = UrlQueryStringFactory.parse(this.url).get("id"); + throw new SabrStreamError(String.format("Broadcast ID changed from %s to %s. The download will need to be restarted.", bc, newQueryString.get("id"))); } this.url = url; if (Helpers.equals(newQueryString.get("source"), "yt_live_broadcast")) { diff --git a/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/parser/adapter/SabrFragmentedMp4Adapter.java b/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/parser/adapter/SabrFragmentedMp4Adapter.java index 7d7199eeea8..8746e71a21b 100644 --- a/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/parser/adapter/SabrFragmentedMp4Adapter.java +++ b/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/parser/adapter/SabrFragmentedMp4Adapter.java @@ -19,14 +19,17 @@ public class SabrFragmentedMp4Adapter extends FragmentedMp4Extractor { private static final String TAG = SabrFragmentedMp4Adapter.class.getSimpleName(); + private final SabrStream sabrStream; private final SabrExtractorInput extractorInput; public SabrFragmentedMp4Adapter(SabrStream sabrStream) { + this.sabrStream = sabrStream; this.extractorInput = new SabrExtractorInput(sabrStream); } public SabrFragmentedMp4Adapter(int flags, SabrStream sabrStream) { super(flags); + this.sabrStream = sabrStream; this.extractorInput = new SabrExtractorInput(sabrStream); } @@ -35,6 +38,7 @@ public SabrFragmentedMp4Adapter( @Nullable TimestampAdjuster timestampAdjuster, SabrStream sabrStream) { super(flags, timestampAdjuster); + this.sabrStream = sabrStream; this.extractorInput = new SabrExtractorInput(sabrStream); } @@ -45,6 +49,7 @@ public SabrFragmentedMp4Adapter( @Nullable DrmInitData sideloadedDrmInitData, SabrStream sabrStream) { super(flags, timestampAdjuster, sideloadedTrack, sideloadedDrmInitData); + this.sabrStream = sabrStream; this.extractorInput = new SabrExtractorInput(sabrStream); } @@ -56,6 +61,7 @@ public SabrFragmentedMp4Adapter( List closedCaptionFormats, SabrStream sabrStream) { super(flags, timestampAdjuster, sideloadedTrack, sideloadedDrmInitData, closedCaptionFormats); + this.sabrStream = sabrStream; this.extractorInput = new SabrExtractorInput(sabrStream); } @@ -68,6 +74,7 @@ public SabrFragmentedMp4Adapter( @Nullable TrackOutput additionalEmsgTrackOutput, SabrStream sabrStream) { super(flags, timestampAdjuster, sideloadedTrack, sideloadedDrmInitData, closedCaptionFormats, additionalEmsgTrackOutput); + this.sabrStream = sabrStream; this.extractorInput = new SabrExtractorInput(sabrStream); } @@ -79,6 +86,18 @@ public int read(ExtractorInput input, PositionHolder seekPosition) try { extractorInput.init(input); result = super.read(extractorInput, seekPosition); + } catch (IOException | IllegalStateException e) { + IOException connectionError = SabrStream.getConnectionError(e); + + if (connectionError == null) { + throw e; + } + + // FIX: a retry would resume the response at a byte offset, which a SABR request can't do ("Unknown part + // encountered"), and fail the playback. The chunk ends with the media it has instead: the next request + // gets the segment again, and SabrSampleDeduplicator drops what is already queued. + Log.e(TAG, "Mp4Adapter: the response broke off: %s", e.getMessage()); + sabrStream.setResponseError(connectionError); } finally { if (result != RESULT_CONTINUE) { Log.e(TAG, "Mp4Adapter: disposing, result=%s", result); diff --git a/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/parser/adapter/SabrMatroskaAdapter.java b/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/parser/adapter/SabrMatroskaAdapter.java index 5fb453bbedc..cf5c3f87b02 100644 --- a/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/parser/adapter/SabrMatroskaAdapter.java +++ b/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/parser/adapter/SabrMatroskaAdapter.java @@ -4,7 +4,10 @@ import com.google.android.exoplayer2.extractor.PositionHolder; import com.google.android.exoplayer2.extractor.mkv.MatroskaExtractor; import com.google.android.exoplayer2.source.sabr.parser.SabrStream; -import com.google.android.exoplayer2.source.sabr.parser.exceptions.SabrPropagationError; +import com.google.android.exoplayer2.source.sabr.parser.exceptions.SabrReloadPlayerError; +import com.google.android.exoplayer2.source.sabr.parser.exceptions.PoTokenError; +import com.google.android.exoplayer2.source.sabr.parser.exceptions.SabrBackoffError; +import com.google.android.exoplayer2.source.sabr.parser.exceptions.SabrProtocolError; import com.google.android.exoplayer2.source.sabr.parser.misc.SabrExtractorInput; import com.liskovsoft.sharedutils.mylogger.Log; @@ -12,15 +15,18 @@ public class SabrMatroskaAdapter extends MatroskaExtractor { private static final String TAG = SabrMatroskaAdapter.class.getSimpleName(); + private final SabrStream sabrStream; private final SabrExtractorInput extractorInput; public SabrMatroskaAdapter(SabrStream sabrStream) { - this.extractorInput = new SabrExtractorInput(sabrStream); + this.sabrStream = sabrStream; + this.extractorInput = new SabrExtractorInput(sabrStream, true); // a live WebM segment is a whole WebM file } public SabrMatroskaAdapter(int flags, SabrStream sabrStream) { super(flags); - this.extractorInput = new SabrExtractorInput(sabrStream); + this.sabrStream = sabrStream; + this.extractorInput = new SabrExtractorInput(sabrStream, true); // a live WebM segment is a whole WebM file } @Override @@ -31,12 +37,21 @@ public int read(ExtractorInput input, PositionHolder seekPosition) try { extractorInput.init(input); result = super.read(extractorInput, seekPosition); - } catch (SabrPropagationError e) { + } catch (SabrReloadPlayerError | SabrBackoffError | PoTokenError | SabrProtocolError e) { + // Swallowed below, a SabrProtocolError ended the chunk as if it had loaded, empty, and the app never heard of it Log.e(TAG, "Propagating SABR control signal: %s", e.getMessage()); throw e; } catch (Exception e) { Log.e(TAG, "User doing seek? %s: %s", e.getClass().getSimpleName(), e.getMessage()); e.printStackTrace(); + + IOException connectionError = SabrStream.getConnectionError(e); + + if (connectionError != null) { + // FIX: the connection broke in the middle of the response. A media network that stalls is left as after a + // failed load (see DefaultSabrChunkSource.onChunkLoadCompleted). + sabrStream.setResponseError(connectionError); + } } finally { if (result != RESULT_CONTINUE) { Log.e(TAG, "MatroskaAdapter: disposing, result=%s", result); diff --git a/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/parser/exceptions/BrokenPartError.java b/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/parser/exceptions/BrokenPartError.java new file mode 100644 index 00000000000..66a7b0c3712 --- /dev/null +++ b/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/parser/exceptions/BrokenPartError.java @@ -0,0 +1,17 @@ +package com.google.android.exoplayer2.source.sabr.parser.exceptions; + +/** + * A UMP part whose header was read but whose bytes can't be: a size that can't be skipped (negative, from a header read out of step: + * FVNAAYZD #15, size -1721324469), or a payload that isn't the protobuf its id says (DMQEWB9B #1: "Protocol message tag had invalid + * wire type" in a NextRequestPolicy). Not a connection that broke while reading it: that is the data source's own exception, which the + * loader's wrapper keeps as a cause. + */ +public class BrokenPartError extends BrokenResponseError { + public BrokenPartError(String msg) { + super(msg); + } + + public BrokenPartError(String msg, Throwable cause) { + super(msg, cause); + } +} diff --git a/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/parser/exceptions/BrokenResponseError.java b/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/parser/exceptions/BrokenResponseError.java new file mode 100644 index 00000000000..9c548cd82de --- /dev/null +++ b/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/parser/exceptions/BrokenResponseError.java @@ -0,0 +1,76 @@ +package com.google.android.exoplayer2.source.sabr.parser.exceptions; + +import androidx.annotation.Nullable; + +/** + * The bytes of a SABR response don't read as what they should: a part whose id or size no part has, or one that isn't the protobuf + * its id says. The response is broken or was read out of step, not a connection that failed (that is the data source's own exception + * under the loader's) or a server that said no. An IllegalStateException, as these were thrown before.
+ * Its message tells what the response was (see #setResponse) and the parts read before it (see #setPartTrail), so a response that + * isn't UMP at all (e.g. a page, or bytes the connection should have decoded) is told from one that went out of step in the middle, + * and an engine's from another's. + */ +public class BrokenResponseError extends IllegalStateException { + @Nullable + private volatile String response; + @Nullable + private volatile String partTrail; + + public BrokenResponseError(String msg) { + super(msg); + } + + public BrokenResponseError(String msg, Throwable cause) { + super(msg, cause); + } + + /** + * Of the response the part was read from (see DefaultSabrChunkSource#onChunkLoadError), before the error goes to the player + * + * @param contentType e.g. "application/vnd.yt-ump", null when the response had none + * @param contentEncoding e.g. "gzip", null when it had none + * @param contentLength -1 when not known + * @param bytesLoaded what the data source delivered of the response, against what the parts read of it (their position) + */ + public void setResponse(@Nullable String contentType, @Nullable String contentEncoding, long contentLength, long bytesLoaded) { + StringBuilder text = new StringBuilder(); + + if (contentType != null) { + text.append(", content type: ").append(contentType); + } + + if (contentEncoding != null) { + text.append(", content encoding: ").append(contentEncoding); + } + + if (contentLength >= 0) { + text.append(", content length: ").append(contentLength); + } + + if (bytesLoaded >= 0) { + text.append(", loaded: ").append(bytesLoaded); + } + + response = text.toString(); + } + + /** + * The parts read before it, oldest first, as "id:size", e.g. "35:12 20:1500 21:13": see SabrStream#getPartTrail + */ + public void setPartTrail(@Nullable String partTrail) { + this.partTrail = partTrail; + } + + @Override + public String getMessage() { + String message = super.getMessage(); + String partTrail = this.partTrail; + String response = this.response; + + if (partTrail != null && !partTrail.isEmpty()) { + message += ", after parts " + partTrail; + } + + return response != null ? message + response : message; + } +} diff --git a/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/parser/exceptions/MediaSegmentMismatchError.java b/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/parser/exceptions/MediaSegmentMismatchError.java new file mode 100644 index 00000000000..97960ead4bd --- /dev/null +++ b/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/parser/exceptions/MediaSegmentMismatchError.java @@ -0,0 +1,19 @@ +package com.google.android.exoplayer2.source.sabr.parser.exceptions; + +import com.google.android.exoplayer2.source.sabr.protos.misc.FormatId; + +public class MediaSegmentMismatchError extends SabrStreamError { + public final long expectedSequenceNumber; + public final long receivedSequenceNumber; + + public MediaSegmentMismatchError(FormatId formatId, long expectedSequenceNumber, long receivedSequenceNumber) { + super(String.format( + "Segment sequence number mismatch for format %s: expected %s, received %s", + formatId, + expectedSequenceNumber, + receivedSequenceNumber + )); + this.receivedSequenceNumber = receivedSequenceNumber; + this.expectedSequenceNumber = expectedSequenceNumber; + } +} diff --git a/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/parser/exceptions/PoTokenError.java b/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/parser/exceptions/PoTokenError.java new file mode 100644 index 00000000000..8eeb75485a6 --- /dev/null +++ b/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/parser/exceptions/PoTokenError.java @@ -0,0 +1,30 @@ +package com.google.android.exoplayer2.source.sabr.parser.exceptions; + +import com.google.android.exoplayer2.source.sabr.parser.parts.PoTokenStatusSabrPart.PoTokenStatus; + +/** + * The server won't send media past its grace period (about a minute) with this poToken. It requires attestation + * (StreamProtectionStatus ATTESTATION_REQUIRED): the one sent is invalid, or none was sent. Or the attestation is still pending + * (ATTESTATION_PENDING) and it stopped sending media (see SabrStream#onResponseEnd). + */ +public class PoTokenError extends SabrPoTokenError { + /** + * INVALID when a poToken was sent, MISSING when none was. PENDING and PENDING_MISSING likewise, its attestation pending. + */ + public final PoTokenStatus status; + + public PoTokenError(PoTokenStatus status) { + super(getMessage(status)); + this.status = status; + } + + private static String getMessage(PoTokenStatus status) { + if (status == PoTokenStatus.INVALID) { + return "SABR server rejected the poToken"; + } else if (status == PoTokenStatus.PENDING || status == PoTokenStatus.PENDING_MISSING) { + return "SABR server stopped sending media pending the poToken's attestation"; + } + + return "SABR server requires a poToken"; + } +} diff --git a/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/parser/exceptions/SabrBackoffError.java b/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/parser/exceptions/SabrBackoffError.java index 69b9e13b5df..880060e4902 100644 --- a/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/parser/exceptions/SabrBackoffError.java +++ b/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/parser/exceptions/SabrBackoffError.java @@ -4,7 +4,7 @@ * The server told us to back off, honor it instead of re-requesting * immediately - otherwise we burn exactly the waiting period the server asked for. */ -public class SabrBackoffError extends SabrPropagationError { +public class SabrBackoffError extends SabrStreamError { public final int backoffMs; public SabrBackoffError(int backoffMs) { diff --git a/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/parser/exceptions/SabrProtocolError.java b/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/parser/exceptions/SabrProtocolError.java new file mode 100644 index 00000000000..197455f8c85 --- /dev/null +++ b/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/parser/exceptions/SabrProtocolError.java @@ -0,0 +1,95 @@ +package com.google.android.exoplayer2.source.sabr.parser.exceptions; + +import androidx.annotation.Nullable; + +import com.google.android.exoplayer2.source.sabr.protos.videostreaming.SabrError; + +/** + * The server answered the request with a SabrError part instead of media, e.g. sabr.malformed_config (the ustreamer config of the + * player response no longer applies, and every request after it is refused) or sabr.no_available_formats. The same request gets + * the same answer: the player response is fetched again, or another client's. + */ +public class SabrProtocolError extends SabrStreamError { + public static final int UNSET = -1; + /** + * E.g. sabr.malformed_config, null when the server sent none + */ + @Nullable + public final String type; + /** + * The action the server asks for (2 in every report so far, of sabr.malformed_config and sabr.no_available_formats). No client + * documents its values. UNSET when the server sent none. + */ + public final int action; + /** + * The HTTP status the server gives the error, UNSET when it gave none + */ + public final int statusCode; + /** + * What the refused request asked for (see SabrManifest#describeRequest), null when not known + */ + @Nullable + private volatile String request; + /** + * How long before the refusal the session it was made with was swapped in (see SabrManifest#requestSessionRefresh), UNSET for the + * stream's first one + */ + private volatile long sessionAgeMs = UNSET; + + public SabrProtocolError(SabrError sabrError) { + this(sabrError.hasType() ? sabrError.getType() : null, + sabrError.hasAction() ? sabrError.getAction() : UNSET, + sabrError.hasError() && sabrError.getError().hasStatusCode() ? sabrError.getError().getStatusCode() : UNSET); + } + + public SabrProtocolError(@Nullable String type, int action, int statusCode) { + super(getMessage(type, action, statusCode)); + this.type = type; + this.action = action; + this.statusCode = statusCode; + } + + /** + * Told by the chunk source that made the request (see DefaultSabrChunkSource#onChunkLoadError): the error is parsed from the + * response alone + * + * @param sessionAgeMs see {@link #getSessionAgeMs()} + */ + public void setRequest(@Nullable String request, long sessionAgeMs) { + this.request = request; + this.sessionAgeMs = sessionAgeMs; + } + + /** + * E.g. "init, video 248:xtags, audio 251, selected none, session 2", null when not known + */ + @Nullable + public String getRequest() { + return request; + } + + /** + * How long before it the stream's session was refreshed (the player response fetched again, see SabrManifest#refreshSession), + * UNSET for the session the stream started with. A refused fresh one says the client is refused, not a stale player response. + */ + public long getSessionAgeMs() { + return sessionAgeMs; + } + + /** + * One line, for the player's message and the diagnostics, e.g. "SABR Protocol Error: sabr.malformed_config, action 2" + */ + private static String getMessage(@Nullable String type, int action, int statusCode) { + StringBuilder message = new StringBuilder("SABR Protocol Error: ").append(type != null ? type : "unknown"); + + if (action != UNSET) { + message.append(", action ").append(action); + } + + if (statusCode != UNSET) { + message.append(", status ").append(statusCode); + } + + return message.toString(); + } +} diff --git a/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/parser/exceptions/SabrReloadPlayerError.java b/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/parser/exceptions/SabrReloadPlayerError.java index 83995f753c9..c9b43266494 100644 --- a/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/parser/exceptions/SabrReloadPlayerError.java +++ b/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/parser/exceptions/SabrReloadPlayerError.java @@ -6,7 +6,7 @@ * The server sent ReloadPlayerResponse. No media will be sent until the player response is re-fetched * with the token (playbackContext.reloadPlaybackContext.reloadPlaybackParams.token). */ -public class SabrReloadPlayerError extends SabrPropagationError { +public class SabrReloadPlayerError extends SabrStreamError { @Nullable public final String reloadPlaybackToken; diff --git a/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/parser/exceptions/SabrStreamConsumedError.java b/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/parser/exceptions/SabrStreamConsumedError.java index c523dd549f9..009d71d5917 100644 --- a/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/parser/exceptions/SabrStreamConsumedError.java +++ b/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/parser/exceptions/SabrStreamConsumedError.java @@ -1,7 +1,4 @@ package com.google.android.exoplayer2.source.sabr.parser.exceptions; -public class SabrStreamConsumedError extends SabrStreamError { - public SabrStreamConsumedError(String msg) { - super(msg); - } +public class SabrStreamConsumedError extends Exception { } diff --git a/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/parser/exceptions/UnknownPartError.java b/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/parser/exceptions/UnknownPartError.java new file mode 100644 index 00000000000..60e056d0609 --- /dev/null +++ b/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/parser/exceptions/UnknownPartError.java @@ -0,0 +1,13 @@ +package com.google.android.exoplayer2.source.sabr.parser.exceptions; + +/** + * Where a UMP part's header should be, the response has bytes no part starts with (an id far past the known ones): the response is + * broken or was read out of step, not one the stream can go on with.
+ * Its message has the part's first bytes, and what the response was (see BrokenResponseError#setResponse): a response that isn't UMP + * at all (e.g. a page) is told from a new part type (T33S5T0B: id 109 at byte 3, its first part). + */ +public class UnknownPartError extends BrokenResponseError { + public UnknownPartError(String msg) { + super(msg); + } +} diff --git a/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/parser/misc/SabrExtractorInput.java b/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/parser/misc/SabrExtractorInput.java index d1405ba0d67..15f6e23bfcd 100644 --- a/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/parser/misc/SabrExtractorInput.java +++ b/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/parser/misc/SabrExtractorInput.java @@ -3,9 +3,13 @@ import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.extractor.ExtractorInput; import com.google.android.exoplayer2.source.sabr.parser.SabrStream; +import com.google.android.exoplayer2.source.sabr.parser.exceptions.PoTokenError; import com.google.android.exoplayer2.source.sabr.parser.exceptions.SabrReloadPlayerError; import com.google.android.exoplayer2.source.sabr.parser.exceptions.SabrBackoffError; import com.google.android.exoplayer2.source.sabr.parser.parts.MediaSegmentDataSabrPart; +import com.google.android.exoplayer2.source.sabr.parser.parts.MediaSegmentEndSabrPart; +import com.google.android.exoplayer2.source.sabr.parser.parts.PoTokenStatusSabrPart; +import com.google.android.exoplayer2.source.sabr.parser.parts.PoTokenStatusSabrPart.PoTokenStatus; import com.google.android.exoplayer2.source.sabr.parser.parts.RefreshPlayerResponseSabrPart; import com.google.android.exoplayer2.source.sabr.parser.parts.SabrPart; import com.liskovsoft.sharedutils.mylogger.Log; @@ -17,17 +21,47 @@ public final class SabrExtractorInput implements ExtractorInput { private static final String TAG = SabrExtractorInput.class.getSimpleName(); private static final boolean ALLOW_END_OF_INPUT = true; private static final int MIN_SWALLOW_BACKOFF_MS = 15_000; // 15 sec - private static final int LIVE_EMPTY_RESPONSE_WAIT_MS = 1_000; private final SabrStream sabrStream; private ExtractorInput input; private long position; private long startPosition; private int remaining; - private boolean receivedData; private MediaSegmentDataSabrPart data; + /** + * The init chunk's response was read up to the end of its init segment: the rest isn't + */ + private boolean isInitEnded; + /** + * Each live segment is read from the response's start position (see startsNextFile) + */ + private final boolean isLiveSegmentAFile; + /** + * Where the response's reading started: the position each live segment is read from + */ + private long basePosition; + /** + * Of the response's last segment read, -1 for none yet + */ + private long lastSequenceNumber = -1; + /** + * A media segment (not an init segment) came in the response + */ + private boolean hasMedia; + /** + * The response was read to its end: told the stream once (see SabrStream#onResponseEnd), not at each read past it + */ + private boolean isResponseEnded; public SabrExtractorInput(SabrStream sabrStream) { + this(sabrStream, false); + } + + /** + * @param isLiveSegmentAFile a live segment of the format is a whole file (its own header), as a live WebM segment is + */ + public SabrExtractorInput(SabrStream sabrStream, boolean isLiveSegmentAFile) { this.sabrStream = sabrStream; + this.isLiveSegmentAFile = isLiveSegmentAFile; } /** Should be called before passing the extractor to a handler */ @@ -37,15 +71,24 @@ public void init(ExtractorInput input) { } if (this.input != null) { - //throw new IllegalStateException("The input should be disposed before initializing"); - Log.e(TAG, "User doing seek? The input should be disposed before initializing"); + // A seek cancelled the chunk before: its load ended without the input disposed (see ContainerMediaChunk#load). Its segment + // reads the response it came from, through the chunk source's one data source, which now reads this one: read on, it + // swallowed this response's first bytes, and its next part was read out of step ("Unknown part encountered" 95-786 ms after + // a seek, V9H5DRS0, AYTTSQJK, FVNAAYZD). This response is read from its own start. + Log.w(TAG, "A new response before the last was disposed (a seek?): the last one's segment is dropped"); + data = null; + sabrStream.onNewResponse(); } this.input = input; position = input.getPosition(); startPosition = position; + basePosition = position; + lastSequenceNumber = -1; remaining = C.LENGTH_UNSET; - receivedData = false; + isInitEnded = false; + hasMedia = false; + isResponseEnded = false; } public void dispose() { @@ -59,8 +102,12 @@ public void dispose() { startPosition = 0; input = null; data = null; + isInitEnded = false; position = C.POSITION_UNSET; + lastSequenceNumber = -1; remaining = C.LENGTH_UNSET; + hasMedia = false; + isResponseEnded = false; } @Override @@ -159,7 +206,7 @@ public long getPeekPosition() { return -1; } - private void fetchData() throws IOException, InterruptedException { + private void fetchData() { while (true) { if (data != null) { long advance = getAdvance(); @@ -173,35 +220,26 @@ private void fetchData() throws IOException, InterruptedException { } } - SabrPart sabrPart; + if (isInitEnded) { + break; + } - try { - sabrPart = sabrStream.parse(input); - } catch (IllegalStateException e) { - // Network failures (e.g. read timeout) are retryable. - if (e.getCause() instanceof IOException) { - throw (IOException) e.getCause(); - } + SabrPart sabrPart = sabrStream.parse(input); - throw e; + // FIX: the init chunk's request is answered with the init segment, then a whole media segment (several MB in 4K). + // Read to the end, it was thrown away and only then asked for again by the first media chunk: the video started + // seconds later. Everything the next request needs (the cookie, the formats) comes before the init segment. + if (sabrPart instanceof MediaSegmentEndSabrPart && ((MediaSegmentEndSabrPart) sabrPart).isInitSegment + && sabrStream.isInitRequest()) { + Log.d(TAG, "Init segment read: the rest of the init chunk's response is skipped"); + isInitEnded = true; + maybeThrowBackoffRequested(); // its policy came before the init segment + break; } if (sabrPart == null) { - // The stream ended. If the server told us to back off, honor it instead of - // re-requesting immediately - otherwise we burn exactly the waiting period the server asked for. - int backoffMs = sabrStream.getBackoffTimeMs(); - - if (backoffMs > MIN_SWALLOW_BACKOFF_MS) { - // Server backoff is too long: reload the format rather than wait. - throwBackoffRequested(backoffMs); - } else if (backoffMs > 0) { - Thread.sleep(backoffMs); - } else if (!receivedData && sabrStream.isLive()) { - // Live head: the server has nothing new yet. It's not the end of the stream. - // Wait a bit, otherwise the empty responses are requested in a tight loop. - Thread.sleep(LIVE_EMPTY_RESPONSE_WAIT_MS); - } - + maybeThrowBackoffRequested(); + maybeThrowAttestationPending(); break; } @@ -215,8 +253,14 @@ private void fetchData() throws IOException, InterruptedException { if (sabrPart instanceof MediaSegmentDataSabrPart) { data = (MediaSegmentDataSabrPart) sabrPart; - receivedData = true; + + if (startsNextFile(data)) { + position = basePosition; + } + + lastSequenceNumber = data.sequenceNumber; startPosition = position; + hasMedia |= !data.isInitSegment; break; } @@ -225,9 +269,26 @@ private void fetchData() throws IOException, InterruptedException { if (sabrPart instanceof RefreshPlayerResponseSabrPart) { throwPlayerResponseReloadRequested((RefreshPlayerResponseSabrPart) sabrPart); } + + // The server won't send media past its grace period (about a minute) with this poToken. + // Ignoring this part stalls the playback there, at the same position after every reload. + if (sabrPart instanceof PoTokenStatusSabrPart) { + throwIfAttestationRequired((PoTokenStatusSabrPart) sabrPart); + } } } + /** + * A live segment after the response's first: read from the response's start position, as DASH reads each from its own file's. + * A live WebM segment has its own EBML header and Segment: read on from the first's end, the extractor refused the second Segment + * (Multiple Segment elements not supported), the chunk ended with its first segment and the rest of the response was thrown away, + * then asked for again. On 2026-11-15, 5 of a 4K stream's responses after each start or seek: ~3 MB thrown away each. + */ + private boolean startsNextFile(MediaSegmentDataSabrPart part) { + return isLiveSegmentAFile && sabrStream.isLive() && !part.isInitSegment + && lastSequenceNumber != -1 && part.sequenceNumber != lastSequenceNumber; + } + private interface ForwardCallback { int forward(int newLength) throws IOException, InterruptedException; } @@ -363,7 +424,43 @@ private static void throwPlayerResponseReloadRequested(RefreshPlayerResponseSabr throw new SabrReloadPlayerError(sabrPart.reloadPlaybackToken); } + /** + * The stream ended. If the server told us to back off, honor it instead of re-requesting immediately - otherwise we burn exactly + * the waiting period the server asked for. + */ + private void maybeThrowBackoffRequested() { + int backoffMs = sabrStream.getBackoffTimeMs(); + + if (backoffMs > MIN_SWALLOW_BACKOFF_MS) { + throwBackoffRequested(backoffMs); + } + } + private static void throwBackoffRequested(int backoffMs) { throw new SabrBackoffError(backoffMs); } + + /** + * The response ended. Past its grace period with the poToken's attestation pending, the server answers each request with no + * media, and the player stalled there for good (see SabrStream#onResponseEnd). The init chunk's response, cut at its init + * segment, isn't one: it's ended before it ends. + */ + private void maybeThrowAttestationPending() { + if (isResponseEnded || sabrStream.isInitRequest()) { + return; + } + + isResponseEnded = true; + PoTokenStatus status = sabrStream.onResponseEnd(hasMedia); + + if (status != null) { + throw new PoTokenError(status); + } + } + + private static void throwIfAttestationRequired(PoTokenStatusSabrPart sabrPart) { + if (sabrPart.status == PoTokenStatus.INVALID || sabrPart.status == PoTokenStatus.MISSING) { + throw new PoTokenError(sabrPart.status); + } + } } diff --git a/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/parser/ump/UMPPart.java b/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/parser/ump/UMPPart.java index d18c0e5668e..bc5e8906f75 100644 --- a/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/parser/ump/UMPPart.java +++ b/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/parser/ump/UMPPart.java @@ -1,6 +1,7 @@ package com.google.android.exoplayer2.source.sabr.parser.ump; import com.google.android.exoplayer2.extractor.ExtractorInput; +import com.google.android.exoplayer2.source.sabr.parser.exceptions.BrokenPartError; public class UMPPart { public final int partId; @@ -18,6 +19,12 @@ public UMPInputStream toStream() { } public void skip() { + // A header read out of step: its size is past what an int holds (FVNAAYZD #15: -1721324469). Not a read that failed, which is + // the connection's (below). + if (size < 0) { + throw new BrokenPartError("Cannot skip part with the id: " + partId + ", and size: " + size); + } + try { data.skipFully(size); } catch (Exception e) { diff --git a/exoplayer-amzn-2.10.6/library/sabr/src/test/java/com/google/android/exoplayer2/source/sabr/DefaultSabrChunkSourceLiveTest.java b/exoplayer-amzn-2.10.6/library/sabr/src/test/java/com/google/android/exoplayer2/source/sabr/DefaultSabrChunkSourceLiveTest.java new file mode 100644 index 00000000000..87548763383 --- /dev/null +++ b/exoplayer-amzn-2.10.6/library/sabr/src/test/java/com/google/android/exoplayer2/source/sabr/DefaultSabrChunkSourceLiveTest.java @@ -0,0 +1,289 @@ +package com.google.android.exoplayer2.source.sabr; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import android.net.Uri; +import android.os.SystemClock; + +import androidx.annotation.Nullable; +import androidx.test.ext.junit.runners.AndroidJUnit4; + +import com.google.android.exoplayer2.C; +import com.google.android.exoplayer2.Format; +import com.google.android.exoplayer2.source.TrackGroup; +import com.google.android.exoplayer2.source.chunk.ChunkHolder; +import com.google.android.exoplayer2.source.chunk.ContainerMediaChunk; +import com.google.android.exoplayer2.source.chunk.MediaChunk; +import com.google.android.exoplayer2.source.sabr.manifest.AdaptationSet; +import com.google.android.exoplayer2.source.sabr.manifest.Period; +import com.google.android.exoplayer2.source.sabr.manifest.Representation; +import com.google.android.exoplayer2.source.sabr.manifest.SabrManifest; +import com.google.android.exoplayer2.source.sabr.manifest.SegmentBase; +import com.google.android.exoplayer2.source.sabr.manifest.SegmentBase.SegmentTemplate; +import com.google.android.exoplayer2.source.sabr.protos.videostreaming.BufferedRange; +import com.google.android.exoplayer2.source.sabr.protos.videostreaming.StreamerContext.ClientInfo; +import com.google.android.exoplayer2.source.sabr.protos.videostreaming.VideoPlaybackAbrRequest; +import com.google.android.exoplayer2.trackselection.FixedTrackSelection; +import com.google.android.exoplayer2.upstream.DataSource; +import com.google.android.exoplayer2.upstream.DataSpec; +import com.google.android.exoplayer2.upstream.LoaderErrorThrower; +import com.google.android.exoplayer2.upstream.TransferListener; +import com.google.android.exoplayer2.util.MimeTypes; + +import java.io.IOException; +import java.io.InterruptedIOException; +import java.util.Arrays; +import java.util.Collections; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.annotation.Config; + +/** + * A live stream over SABR: its timeline starts at its start segment's media time (as the DASH live manifest's), and at its head the + * next request waits instead of looping + */ +@RunWith(AndroidJUnit4.class) +@Config(sdk = 28) +public class DefaultSabrChunkSourceLiveTest { + private static final String SABR_URL = "https://rr1---sn-primary.googlevideo.com/videoplayback?source=yt_live_broadcast"; + /** + * The start segment's media time of a 23-day stream (ROboUHfPUrU, 2026-11-15): 24 h before its head + */ + private static final long START_SEGMENT_TIME_US = 1_957_547_035_080L; + private static final long LIVE_POSITION_US = 86_400_000_000L; + private static final long WINDOW_MS = 48 * 60 * 60 * 1_000L; + + @Test + public void aLiveSeekAsksTheServerForTheMediaTime() throws Exception { + SabrManifest manifest = liveManifest(5, audio()); + ChunkHolder out = new ChunkHolder(); + + source(manifest, 0, new FailingDataSource()).getNextChunk(LIVE_POSITION_US, LIVE_POSITION_US, Collections.emptyList(), out); + + assertTrue(out.chunk instanceof ContainerMediaChunk); + VideoPlaybackAbrRequest request = VideoPlaybackAbrRequest.parseFrom(out.chunk.dataSpec.httpBody); + assertEquals((LIVE_POSITION_US + START_SEGMENT_TIME_US) / 1_000, request.getClientAbrState().getPlayerTimeMs()); + // On the timeline, not the media's: the player's buffered duration is computed from it + assertEquals(LIVE_POSITION_US, ((MediaChunk) out.chunk).startTimeUs); + } + + @Test + public void aVideoSeekAsksTheServerForTheTimelinesTime() throws Exception { + SabrManifest manifest = manifest(SabrManifest.NOT_LIVE, 0, audio()); + ChunkHolder out = new ChunkHolder(); + + source(manifest, 0, new FailingDataSource()).getNextChunk(30_000_000, 30_000_000, Collections.emptyList(), out); + + assertEquals(30_000, VideoPlaybackAbrRequest.parseFrom(out.chunk.dataSpec.httpBody).getClientAbrState().getPlayerTimeMs()); + } + + /** + * Answered with no media (the segment after the head's doesn't exist yet), the request asked again at once got the same answer, tens + * a second, until the app reloaded the stream (seen 2026-11-15). It waits a quarter of a segment. + */ + @Test + public void aLiveRequestAnsweredWithNoSegmentIsRetriedLater() throws Exception { + FailingDataSource upstream = new FailingDataSource(); + DefaultSabrChunkSource source = source(liveManifest(1, audio()), 0, upstream); + ChunkHolder out = new ChunkHolder(); + source.getNextChunk(LIVE_POSITION_US, LIVE_POSITION_US, Collections.emptyList(), out); + MediaChunk seek = (MediaChunk) out.chunk; + + source.onChunkLoadCompleted(seek); // no segment came + out.clear(); + source.getNextChunk(LIVE_POSITION_US, LIVE_POSITION_US, Collections.singletonList(seek), out); + + long waitedMs = msUntilOpened(out.chunk, upstream); + assertTrue("waited " + waitedMs + " ms", waitedMs >= 200); + } + + /** + * The wait is told, with its track: a start at the head that waited for the stream had no row for it (AFQQ49Z4 RJFwMQBXPUQ) + */ + @Test + public void aLiveRequestAnsweredWithNoSegmentTellsItsWait() throws Exception { + long[] told = {-1, -1}; + DefaultSabrChunkSource.setLiveHeadWaitListener((trackType, waitMs) -> { + told[0] = trackType; + told[1] = waitMs; + }); + + try { + DefaultSabrChunkSource source = source(liveManifest(4, audio()), 0, new FailingDataSource()); + ChunkHolder out = new ChunkHolder(); + source.getNextChunk(LIVE_POSITION_US, LIVE_POSITION_US, Collections.emptyList(), out); + + source.onChunkLoadCompleted(out.chunk); // no segment came + + assertEquals(C.TRACK_TYPE_AUDIO, told[0]); + assertEquals(1_000, told[1]); // a quarter of the 4 s segments + } finally { + DefaultSabrChunkSource.setLiveHeadWaitListener(null); + } + } + + @Test + public void aSeekAfterAnAnswerWithNoSegmentAsksAtOnce() throws Exception { + FailingDataSource upstream = new FailingDataSource(); + DefaultSabrChunkSource source = source(liveManifest(1, audio()), 0, upstream); + ChunkHolder out = new ChunkHolder(); + source.getNextChunk(LIVE_POSITION_US, LIVE_POSITION_US, Collections.emptyList(), out); + source.onChunkLoadCompleted(out.chunk); + out.clear(); + + source.getNextChunk(LIVE_POSITION_US - 10_000_000, LIVE_POSITION_US - 10_000_000, Collections.emptyList(), out); + + long waitedMs = msUntilOpened(out.chunk, upstream); + assertTrue("waited " + waitedMs + " ms", waitedMs < 150); + } + + @Test + public void aVideoRequestAnsweredWithNoSegmentIsntDelayed() throws Exception { + FailingDataSource upstream = new FailingDataSource(); + DefaultSabrChunkSource source = source(manifest(SabrManifest.NOT_LIVE, 0, audio()), 0, upstream); + ChunkHolder out = new ChunkHolder(); + source.getNextChunk(0, 0, Collections.emptyList(), out); + MediaChunk first = (MediaChunk) out.chunk; + source.onChunkLoadCompleted(first); + out.clear(); + + source.getNextChunk(0, 0, Collections.singletonList(first), out); + + long waitedMs = msUntilOpened(out.chunk, upstream); + assertTrue("waited " + waitedMs + " ms", waitedMs < 150); + } + + @Test + public void theWaitEndsWhenTheLoadIsCanceled() throws Exception { + DefaultSabrChunkSource.DelayedOpenDataSource dataSource = + new DefaultSabrChunkSource.DelayedOpenDataSource(new FailingDataSource(), SystemClock.elapsedRealtime() + 60_000); + Thread.currentThread().interrupt(); // as the loader does when it cancels + + try { + dataSource.open(new DataSpec(Uri.parse(SABR_URL))); + fail(); + } catch (InterruptedIOException expected) { + assertTrue(Thread.interrupted()); + } + } + + /** + * The other track's format, marked buffered for good so that the server sends none of it: a live stream's server goes by the segment + * numbers, so from the first one; a video's server sent media headers with no format metadata for [0, MAX], so it keeps [MAX, MAX] + */ + @Test + public void theOtherTracksFormatIsBufferedFromTheFirstSegmentOfALiveStream() throws Exception { + assertEquals(0, otherTracksRange(liveManifest(5, video(), audio())).getStartSegmentIndex()); + assertEquals(Integer.MAX_VALUE, otherTracksRange(manifest(SabrManifest.NOT_LIVE, 0, video(), audio())).getStartSegmentIndex()); + } + + private static BufferedRange otherTracksRange(SabrManifest manifest) throws Exception { + source(manifest, 0, new FailingDataSource()); + source(manifest, 1, new FailingDataSource()); + + VideoPlaybackAbrRequest request = manifest.createVideoPlaybackAbrRequest(C.TRACK_TYPE_VIDEO, false); + + assertEquals(1, request.getBufferedRangesCount()); + assertEquals(140, request.getBufferedRanges(0).getFormatId().getItag()); + return request.getBufferedRanges(0); + } + + /** + * Loads the chunk until its data source opens (the upstream fails there) + */ + private static long msUntilOpened(@Nullable Object chunk, FailingDataSource upstream) throws Exception { + assertTrue(chunk instanceof ContainerMediaChunk); + long startNs = System.nanoTime(); + + try { + ((ContainerMediaChunk) chunk).load(); + fail(); + } catch (IOException expected) { + // the upstream's + } + + return (upstream.openedNs - startNs) / 1_000_000; + } + + private static Format audio() { + return Format.createAudioContainerFormat( + "140", null, MimeTypes.AUDIO_MP4, MimeTypes.AUDIO_AAC, null, null, + 144_000, 2, 44_100, null, 0, 0, "en"); + } + + private static Format video() { + return Format.createVideoContainerFormat( + "248", null, MimeTypes.VIDEO_WEBM, MimeTypes.VIDEO_VP9, null, null, + 2_900_000, 1920, 1080, 30, null, 0, 0); + } + + private static SabrManifest liveManifest(int targetDurationSec, Format... formats) { + return manifest(targetDurationSec, START_SEGMENT_TIME_US, formats); + } + + private static SabrManifest manifest(int liveTargetDurationSec, long presentationTimeOffsetUs, Format... formats) { + boolean isLive = liveTargetDurationSec != SabrManifest.NOT_LIVE; + AdaptationSet[] adaptationSets = new AdaptationSet[formats.length]; + + for (int i = 0; i < formats.length; i++) { + SegmentBase segmentBase = isLive + ? new SegmentTemplate(null, 1_000_000, presentationTimeOffsetUs, 0, C.INDEX_UNSET, + liveTargetDurationSec * 1_000_000L, null, null, null) + : new SegmentBase.SingleSegmentBase(); + int type = MimeTypes.isVideo(formats[i].sampleMimeType) ? C.TRACK_TYPE_VIDEO : C.TRACK_TYPE_AUDIO; + adaptationSets[i] = new AdaptationSet(i, type, + Collections.singletonList(Representation.newInstance(formats[i], SABR_URL, segmentBase))); + } + + Period period = new Period("test", 0, Arrays.asList(adaptationSets)); + return new SabrManifest( + C.TIME_UNSET, isLive ? WINDOW_MS : 60_000, 1_500, false, + C.TIME_UNSET, C.TIME_UNSET, C.TIME_UNSET, C.TIME_UNSET, + Collections.singletonList(period), SABR_URL, "", null, "test", + ClientInfo.getDefaultInstance(), null, liveTargetDurationSec); + } + + private static DefaultSabrChunkSource source(SabrManifest manifest, int adaptationSetIndex, DataSource dataSource) { + AdaptationSet adaptationSet = manifest.getPeriod(0).adaptationSets.get(adaptationSetIndex); + Format format = adaptationSet.representations.get(0).format; + return new DefaultSabrChunkSource( + new LoaderErrorThrower.Dummy(), manifest, 0, new int[] {adaptationSetIndex}, + new FixedTrackSelection(new TrackGroup(format), 0), adaptationSet.type, + dataSource, 0, 1, false, Collections.emptyList(), null); + } + + /** + * Fails when opened, and tells when + */ + private static final class FailingDataSource implements DataSource { + private volatile long openedNs; + + @Override + public void addTransferListener(TransferListener transferListener) { + } + + @Override + public long open(DataSpec dataSpec) throws IOException { + openedNs = System.nanoTime(); + throw new IOException("test"); + } + + @Override + public int read(byte[] buffer, int offset, int readLength) { + return C.RESULT_END_OF_INPUT; + } + + @Nullable + @Override + public Uri getUri() { + return null; + } + + @Override + public void close() { + } + } +} diff --git a/exoplayer-amzn-2.10.6/library/sabr/src/test/java/com/google/android/exoplayer2/source/sabr/GoogleVideoHostsTest.java b/exoplayer-amzn-2.10.6/library/sabr/src/test/java/com/google/android/exoplayer2/source/sabr/GoogleVideoHostsTest.java new file mode 100644 index 00000000000..27a0e5c0e48 --- /dev/null +++ b/exoplayer-amzn-2.10.6/library/sabr/src/test/java/com/google/android/exoplayer2/source/sabr/GoogleVideoHostsTest.java @@ -0,0 +1,117 @@ +package com.google.android.exoplayer2.source.sabr; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import org.junit.Before; +import org.junit.Test; + +public class GoogleVideoHostsTest { + /** + * As in the player response fixtures: the host's prefix (rr1, the mvi) differs from the fvip + */ + private static final String URL = "https://rr1---sn-4gxb5u-qo3l.googlevideo.com/videoplayback?expire=1762756396&itag=18" + + "&mh=iw&mm=31%2C29&mn=sn-4gxb5u-qo3l%2Csn-3c27sn7y&ms=au%2Crdu&mv=m&mvi=1&pl=25&fvip=8&c=WEB&sig=AOq0QJ8"; + + @Before + public void setUp() { + GoogleVideoHosts.clearFailedNetworks(); + } + + @Test + public void fallbackUrlIsOnTheFvipHostOfTheSecondNetwork() { + assertEquals(URL.replace("rr1---sn-4gxb5u-qo3l", "r8---sn-3c27sn7y") + "&fallback_count=1", + GoogleVideoHosts.toFallbackUrl(URL)); + } + + @Test + public void fallbackUrlKeepsThePortAndTheFragment() { + String url = "https://rr1---sn-a.googlevideo.com:8443/videoplayback?mn=sn-a,sn-b&fvip=3#frag"; + + assertEquals("https://r3---sn-b.googlevideo.com:8443/videoplayback?mn=sn-a,sn-b&fvip=3&fallback_count=1#frag", + GoogleVideoHosts.toFallbackUrl(url)); + } + + @Test + public void noFallbackUrlWithoutFvipOrASecondNetwork() { + assertNull(GoogleVideoHosts.toFallbackUrl("https://rr1---sn-a.googlevideo.com/videoplayback?mn=sn-a%2Csn-b")); + assertNull(GoogleVideoHosts.toFallbackUrl("https://rr1---sn-a.googlevideo.com/videoplayback?mn=sn-a&fvip=3")); + assertNull(GoogleVideoHosts.toFallbackUrl("https://rr1---sn-a.googlevideo.com/videoplayback?mn=sn-a%2C&fvip=3")); + assertNull(GoogleVideoHosts.toFallbackUrl("https://rr1---sn-a.googlevideo.com/videoplayback?fvip=3")); + assertNull(GoogleVideoHosts.toFallbackUrl("https://rr1---sn-a.googlevideo.com/videoplayback?mn=sn-a%2Csn-b&fvip=")); + } + + @Test + public void noFallbackUrlForAnotherDomainOrABadHostLabel() { + assertNull(GoogleVideoHosts.toFallbackUrl("https://example.com/videoplayback?mn=sn-a%2Csn-b&fvip=3")); + assertNull(GoogleVideoHosts.toFallbackUrl("https://rr1---sn-a.googlevideo.com/videoplayback?mn=sn-a%2Csn-b.evil.com%2F&fvip=3")); + assertNull(GoogleVideoHosts.toFallbackUrl("https://rr1---sn-a.googlevideo.com/videoplayback?mn=sn-a%2Csn-b&fvip=3.x")); + assertNull(GoogleVideoHosts.toFallbackUrl(null)); + assertNull(GoogleVideoHosts.toFallbackUrl("https://rr1---sn-a.googlevideo.com/%")); + } + + @Test + public void noFallbackUrlWhenAlreadyOnIt() { + assertNull(GoogleVideoHosts.toFallbackUrl("https://R3---sn-b.googlevideo.com/videoplayback?mn=sn-a%2Csn-b&fvip=3")); + } + + @Test + public void redirectorUrlAsksForAWorkingHost() { + assertEquals(URL.replace("rr1---sn-4gxb5u-qo3l", "redirector") + "&cmo=pf%3D1", GoogleVideoHosts.toRedirectorUrl(URL)); + } + + @Test + public void redirectorUrlOfAnA1HostNamesItsDomain() { + assertEquals("https://redirector.googlevideo.com/videoplayback?id=1&cmo=pf%3D1&cmo=td%3Da1.googlevideo.com", + GoogleVideoHosts.toRedirectorUrl("https://r1---sn-a.c.a1.googlevideo.com/videoplayback?id=1")); + } + + @Test + public void noRedirectorUrlForAnotherDomainOrTheRedirectorItself() { + assertNull(GoogleVideoHosts.toRedirectorUrl("https://rr1---sn-a.example.com/videoplayback?id=1")); + assertNull(GoogleVideoHosts.toRedirectorUrl("https://redirector.googlevideo.com/videoplayback?id=1&cmo=pf%3D1")); + assertNull(GoogleVideoHosts.toRedirectorUrl(null)); + } + + @Test + public void noRedirectorUrlForAManifestOrAPathStyleUrl() { + assertNull(GoogleVideoHosts.toRedirectorUrl("https://manifest.googlevideo.com/api/manifest/hls_playlist/expire/1/id/x")); + assertNull(GoogleVideoHosts.toRedirectorUrl("https://rr1---sn-a.googlevideo.com/videoplayback/expire/1/itag/134/sq/5")); + } + + @Test + public void sameMediaIgnoresTheRequestsOwnParameters() { + assertTrue(GoogleVideoHosts.isSameMedia(URL + "&range=0-1000", URL + "&rn=4&sq=7")); + } + + @Test + public void sameMediaComparesHostPathAndSignatures() { + assertFalse(GoogleVideoHosts.isSameMedia(URL, URL.replace("rr1---", "rr2---"))); + assertFalse(GoogleVideoHosts.isSameMedia(URL, URL.replace("/videoplayback", "/videoplayback2"))); + assertFalse(GoogleVideoHosts.isSameMedia(URL, URL.replace("sig=AOq0QJ8", "sig=other"))); + assertFalse(GoogleVideoHosts.isSameMedia(URL, URL + "&lsig=x")); + assertFalse(GoogleVideoHosts.isSameMedia(URL + "&signature=a", URL + "&signature=b")); + assertFalse(GoogleVideoHosts.isSameMedia(URL, null)); + assertTrue(GoogleVideoHosts.isSameMedia(URL, URL.replace("rr1---sn-4gxb5u-qo3l", "RR1---sn-4gxb5u-qo3l"))); + } + + @Test + public void failedNetworkCoversEveryHostOfIt() { + GoogleVideoHosts.markNetworkFailed(URL); + + assertTrue(GoogleVideoHosts.isNetworkFailed("https://rr7---sn-4gxb5u-qo3l.googlevideo.com/videoplayback?itag=1")); + assertFalse(GoogleVideoHosts.isNetworkFailed(GoogleVideoHosts.toFallbackUrl(URL))); + assertFalse(GoogleVideoHosts.isNetworkFailed("https://redirector.googlevideo.com/videoplayback")); + } + + @Test + public void hostsWithoutANetworkAreNeverMarked() { + GoogleVideoHosts.markNetworkFailed("https://redirector.googlevideo.com/videoplayback"); + GoogleVideoHosts.markNetworkFailed("https://example.com/videoplayback"); + + assertFalse(GoogleVideoHosts.isNetworkFailed("https://redirector.googlevideo.com/videoplayback")); + assertFalse(GoogleVideoHosts.isNetworkFailed("https://example.com/videoplayback")); + } +} diff --git a/exoplayer-amzn-2.10.6/library/sabr/src/test/java/com/google/android/exoplayer2/source/sabr/SabrLivePrefetcherTest.java b/exoplayer-amzn-2.10.6/library/sabr/src/test/java/com/google/android/exoplayer2/source/sabr/SabrLivePrefetcherTest.java new file mode 100644 index 00000000000..873d9ae823d --- /dev/null +++ b/exoplayer-amzn-2.10.6/library/sabr/src/test/java/com/google/android/exoplayer2/source/sabr/SabrLivePrefetcherTest.java @@ -0,0 +1,422 @@ +package com.google.android.exoplayer2.source.sabr; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; + +import android.net.Uri; + +import androidx.annotation.Nullable; +import androidx.test.ext.junit.runners.AndroidJUnit4; + +import com.google.android.exoplayer2.C; +import com.google.android.exoplayer2.Format; +import com.google.android.exoplayer2.source.TrackGroup; +import com.google.android.exoplayer2.source.chunk.Chunk; +import com.google.android.exoplayer2.source.chunk.ChunkHolder; +import com.google.android.exoplayer2.source.chunk.MediaChunk; +import com.google.android.exoplayer2.source.sabr.manifest.AdaptationSet; +import com.google.android.exoplayer2.source.sabr.manifest.Period; +import com.google.android.exoplayer2.source.sabr.manifest.Representation; +import com.google.android.exoplayer2.source.sabr.manifest.SabrManifest; +import com.google.android.exoplayer2.source.sabr.manifest.SegmentBase.SegmentTemplate; +import com.google.android.exoplayer2.source.sabr.parser.SabrStream; +import com.google.android.exoplayer2.source.sabr.parser.misc.SabrExtractorInput; +import com.google.android.exoplayer2.source.sabr.parser.ump.UMPPartId; +import com.google.android.exoplayer2.source.sabr.protos.misc.FormatId; +import com.google.android.exoplayer2.source.sabr.protos.videostreaming.FormatInitializationMetadata; +import com.google.android.exoplayer2.source.sabr.protos.videostreaming.LiveMetadata; +import com.google.android.exoplayer2.source.sabr.protos.videostreaming.MediaHeader; +import com.google.android.exoplayer2.source.sabr.protos.videostreaming.StreamerContext.ClientInfo; +import com.google.android.exoplayer2.source.sabr.protos.videostreaming.VideoPlaybackAbrRequest; +import com.google.android.exoplayer2.testutil.FakeExtractorInput; +import com.google.android.exoplayer2.trackselection.FixedTrackSelection; +import com.google.android.exoplayer2.upstream.DataSource; +import com.google.android.exoplayer2.upstream.DataSpec; +import com.google.android.exoplayer2.upstream.LoaderErrorThrower; +import com.google.android.exoplayer2.upstream.TransferListener; +import com.google.android.exoplayer2.util.MimeTypes; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.annotation.Config; + +/** + * A live stream with 1 s segments: an edge answers a request for a segment it hasn't cached in about a second, so the next segments are + * asked for while the player loads one, and their responses are what the player's requests get + */ +@RunWith(AndroidJUnit4.class) +@Config(sdk = 28) +public class SabrLivePrefetcherTest { + private static final String SABR_URL = "https://rr1---sn-primary.googlevideo.com/videoplayback?source=yt_live_broadcast"; + private static final int ITAG = 140; + private static final int SEQUENCE = 423_104; + private static final long START_MS = 423_098_967; + private static final byte[] RESPONSE = {1, 2, 3, 4, 5}; + + @Test + public void thePlayersRequestGetsTheResponseFetchedAhead() throws Exception { + RecordingFactory factory = new RecordingFactory(RESPONSE); + SabrLivePrefetcher prefetcher = new SabrLivePrefetcher(factory, null); + RecordingDataSource upstream = new RecordingDataSource(new byte[] {9}); + + prefetcher.prefetch(ITAG, SEQUENCE, spec(), 1_000); + DataSource dataSource = prefetcher.dataSourceFor(ITAG, SEQUENCE, upstream); + + assertArrayEquals(RESPONSE, readAll(dataSource)); + assertEquals(0, upstream.opened); + assertEquals(1, factory.sources.size()); + } + + @Test + public void aFailedFetchIsAskedAgain() throws Exception { + SabrLivePrefetcher prefetcher = new SabrLivePrefetcher(new RecordingFactory(null), null); + RecordingDataSource upstream = new RecordingDataSource(new byte[] {9}); + + prefetcher.prefetch(ITAG, SEQUENCE, spec(), 1_000); + + assertArrayEquals(new byte[] {9}, readAll(prefetcher.dataSourceFor(ITAG, SEQUENCE, upstream))); + assertEquals(1, upstream.opened); + } + + /** + * At the start of a stream the server may answer with a burst toward its 15 s readahead (over 8 MB for a 2 s segment of 1440p): it + * isn't kept, the player asks itself, and nothing more is asked for ahead for a while + */ + @Test + public void aBurstIsntKeptAndPausesThePrefetch() throws Exception { + RecordingFactory factory = new RecordingFactory(new byte[2_000]); + SabrLivePrefetcher prefetcher = new SabrLivePrefetcher(factory, null); + RecordingDataSource upstream = new RecordingDataSource(new byte[] {9}); + + prefetcher.prefetch(ITAG, SEQUENCE, spec(), 1_000); + assertArrayEquals(new byte[] {9}, readAll(prefetcher.dataSourceFor(ITAG, SEQUENCE, upstream))); + prefetcher.prefetch(ITAG, SEQUENCE + 1, spec(), 1_000); + + assertEquals(1, upstream.opened); + assertEquals(1, factory.sources.size()); + } + + @Test + public void aResponseIsKeptUpToAFewSegmentsOfTheFormat() { + assertEquals(1024 * 1024, SabrLivePrefetcher.getMaxResponseBytes(144_000, 1_000, 1)); // audio: at least 1 MB + assertEquals(5_625_000, SabrLivePrefetcher.getMaxResponseBytes(9_000_000, 2_000, 1)); // 1440p: 2.5 segments + assertEquals(12 * 1024 * 1024, SabrLivePrefetcher.getMaxResponseBytes(25_000_000, 2_000, 1)); // 4K: at most 12 MB + assertEquals(2_531_250, SabrLivePrefetcher.getMaxResponseBytes(4_500_000, 1_000, 3)); // 3 segments of 1080p: 4.5 segments + } + + /** + * A response that brought several segments (audio's do): the ones asked for ahead before the next one asked for won't be read + */ + @Test + public void earlierSegmentsAreDroppedAndAnotherFormatIsntServed() throws Exception { + RecordingFactory factory = new RecordingFactory(RESPONSE); + SabrLivePrefetcher prefetcher = new SabrLivePrefetcher(factory, null); + RecordingDataSource upstream = new RecordingDataSource(new byte[] {9}); + prefetcher.prefetch(ITAG, SEQUENCE, spec(), 1_000); + prefetcher.prefetch(ITAG, SEQUENCE + 1, spec(), 1_000); + prefetcher.prefetch(ITAG, SEQUENCE + 2, spec(), 1_000); + + assertSame(upstream, prefetcher.dataSourceFor(251, SEQUENCE + 2, upstream)); + assertTrue(prefetcher.dataSourceFor(ITAG, SEQUENCE + 2, upstream) instanceof SabrLivePrefetcher.PrefetchedDataSource); + assertSame(upstream, prefetcher.dataSourceFor(ITAG, SEQUENCE + 1, upstream)); + assertSame(upstream, prefetcher.dataSourceFor(ITAG, SEQUENCE, upstream)); + } + + /** + * After a segment arrived: the player's next request is its own, the three after it are asked for ahead, as if each one before them + * were the newest received (by number); none past the head, which the server would hold until it exists + */ + @Test + public void theNextSegmentsUpToTheHeadAreAskedForAhead() throws Exception { + RecordingFactory factory = new RecordingFactory(RESPONSE); + SabrManifest manifest = liveManifest(1); + DefaultSabrChunkSource source = source(manifest); + source.enableLivePrefetch(factory, null); + MediaChunk previous = firstChunk(source); // a seek: the stream is reset + receive(manifest.getSabrStream(C.TRACK_TYPE_AUDIO), SEQUENCE + 3); + ChunkHolder out = new ChunkHolder(); + + source.getNextChunk(0, 0, Collections.singletonList(previous), out); + + assertEquals(2, factory.sources.size()); // SEQUENCE + 2 and + 3: + 4 is past the head + VideoPlaybackAbrRequest first = VideoPlaybackAbrRequest.parseFrom(opened(factory.sources.get(0)).httpBody); + assertEquals(SEQUENCE + 1, first.getBufferedRanges(0).getStartSegmentIndex()); + assertEquals(START_MS + 1_000, first.getBufferedRanges(0).getStartTimeMs()); + VideoPlaybackAbrRequest second = VideoPlaybackAbrRequest.parseFrom(opened(factory.sources.get(1)).httpBody); + assertEquals(SEQUENCE + 2, second.getBufferedRanges(0).getStartSegmentIndex()); + } + + /** + * Behind the head, a response holds the segments after the one asked for too (3 of a 1 s stream): the ones asked for ahead are as + * far apart. One by one, each segment came in 3 responses, and 2 of them weren't read: 3x the bytes for as long as the player + * stayed behind the head (2026-11-15). + */ + @Test + public void theSegmentsAskedForAheadAreAsFarApartAsAResponseHolds() throws Exception { + RecordingFactory factory = new RecordingFactory(RESPONSE); + SabrManifest manifest = liveManifest(1); + DefaultSabrChunkSource source = source(manifest); + source.enableLivePrefetch(factory, null); + SabrStream sabrStream = manifest.getSabrStream(C.TRACK_TYPE_AUDIO); + MediaChunk seek = firstChunk(source); // its response: 3 segments + receive(sabrStream, SEQUENCE + 100, SEQUENCE, 3); + ChunkHolder out = new ChunkHolder(); + source.getNextChunk(0, 0, Collections.singletonList(seek), out); // a seek's response says nothing: one by one + assertEquals(3, factory.sources.size()); + receive(sabrStream, SEQUENCE + 100, SEQUENCE + 3, 3); + + source.getNextChunk(0, 0, Arrays.asList(seek, (MediaChunk) out.chunk), new ChunkHolder()); + + assertEquals(6, factory.sources.size()); + for (int i = 0; i < 3; i++) { // the newest received is SEQUENCE + 5: SEQUENCE + 9, + 12 and + 15, each as if after the one before it + VideoPlaybackAbrRequest request = VideoPlaybackAbrRequest.parseFrom(opened(factory.sources.get(3 + i)).httpBody); + assertEquals(SEQUENCE + 8 + 3 * i, request.getBufferedRanges(0).getStartSegmentIndex()); + } + } + + @Test + public void aStreamWithLongerSegmentsIsntPrefetched() throws Exception { + RecordingFactory factory = new RecordingFactory(RESPONSE); + SabrManifest manifest = liveManifest(5); + DefaultSabrChunkSource source = source(manifest); + source.enableLivePrefetch(factory, null); + MediaChunk previous = firstChunk(source); + receive(manifest.getSabrStream(C.TRACK_TYPE_AUDIO), SEQUENCE + 10); + + source.getNextChunk(0, 0, Collections.singletonList(previous), new ChunkHolder()); + + assertTrue(factory.sources.isEmpty()); + } + + @Test + public void aSeekDropsWhatsAskedForAhead() throws Exception { + RecordingFactory factory = new RecordingFactory(RESPONSE); + SabrManifest manifest = liveManifest(1); + DefaultSabrChunkSource source = source(manifest); + source.enableLivePrefetch(factory, null); + MediaChunk previous = firstChunk(source); + receive(manifest.getSabrStream(C.TRACK_TYPE_AUDIO), SEQUENCE + 10); + source.getNextChunk(0, 0, Collections.singletonList(previous), new ChunkHolder()); + assertEquals(3, factory.sources.size()); + + ChunkHolder out = new ChunkHolder(); + source.getNextChunk(0, 0, Collections.emptyList(), out); + + assertFalse(out.chunk == null); + assertEquals(3, factory.sources.size()); // no more asked for: the stream is reset by the seek + } + + /** + * Which segment a live seek brings first isn't known before it comes: the three after it, the player's next one first, are asked + * for as soon as its header is read, while its media still loads, not once the chunk is loaded (CQHM6BGP hMzTblhfTvc: a start + * fetched the 2 s segments it needed one after another, at about a second each) + */ + @Test + public void theSegmentsAfterASeeksFirstAreAskedForAsItComes() throws Exception { + RecordingFactory factory = new RecordingFactory(RESPONSE); + SabrManifest manifest = liveManifest(2); + DefaultSabrChunkSource source = source(manifest); + source.enableLivePrefetch(factory, null); + MediaChunk seek = firstChunk(source); + DataSource loading = loadingDataSource(seek); + loading.open(seek.dataSpec); + loading.read(new byte[16], 0, 16); + assertTrue(factory.sources.isEmpty()); // nothing came yet + + receive(manifest.getSabrStream(C.TRACK_TYPE_AUDIO), SEQUENCE + 10); // its first segment's header: SEQUENCE + loading.read(new byte[16], 0, 16); + loading.read(new byte[16], 0, 16); + + assertEquals(3, factory.sources.size()); // once + for (int i = 0; i < 3; i++) { // SEQUENCE + 1, + 2 and + 3, each as if after the one before it + VideoPlaybackAbrRequest request = VideoPlaybackAbrRequest.parseFrom(opened(factory.sources.get(i)).httpBody); + assertEquals(SEQUENCE + i, request.getBufferedRanges(0).getStartSegmentIndex()); + } + + // The player's next request gets the one asked for ahead, and one more is asked for + source.getNextChunk(0, 0, Collections.singletonList(seek), new ChunkHolder()); + assertEquals(4, factory.sources.size()); + } + + /** + * What the chunk loads from + */ + private static DataSource loadingDataSource(Chunk chunk) throws Exception { + Field field = Chunk.class.getDeclaredField("dataSource"); + field.setAccessible(true); + return (DataSource) field.get(chunk); + } + + /** + * Its request, once the prefetch's thread opened it + */ + private static DataSpec opened(RecordingDataSource source) throws InterruptedException { + for (int i = 0; i < 200 && source.dataSpec == null; i++) { + Thread.sleep(10); + } + return source.dataSpec; + } + + private static MediaChunk firstChunk(DefaultSabrChunkSource source) { + ChunkHolder out = new ChunkHolder(); + source.getNextChunk(0, 0, Collections.emptyList(), out); + return (MediaChunk) out.chunk; + } + + /** + * The stream receives a live response: the format's metadata, the live metadata (its head), a segment + */ + private static void receive(SabrStream sabrStream, int headSequenceNumber) throws Exception { + receive(sabrStream, headSequenceNumber, SEQUENCE, 1); + } + + /** + * The stream receives a live response of several segments, a second each + */ + private static void receive(SabrStream sabrStream, int headSequenceNumber, int firstSequence, int segments) throws Exception { + FormatId formatId = FormatId.newBuilder().setItag(ITAG).build(); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + part(out, UMPPartId.FORMAT_INITIALIZATION_METADATA, FormatInitializationMetadata.newBuilder() + .setFormatId(formatId).setMimeType("audio/mp4; codecs=\"mp4a.40.2\"").build().toByteArray()); + part(out, UMPPartId.LIVE_METADATA, LiveMetadata.newBuilder() + .setHeadSequenceNumber(headSequenceNumber).setHeadSequenceTimeMs(START_MS + 30_000).build().toByteArray()); + for (int i = 0; i < segments; i++) { + int sequence = firstSequence + i; + part(out, UMPPartId.MEDIA_HEADER, MediaHeader.newBuilder().setHeaderId(i).setItag(ITAG).setFormatId(formatId) + .setSequenceNumber(sequence).setStartMs(START_MS + (sequence - SEQUENCE) * 1_000L).build().toByteArray()); + part(out, UMPPartId.MEDIA, new byte[] {(byte) i, 7, 7}); + part(out, UMPPartId.MEDIA_END, new byte[] {(byte) i}); + } + + SabrExtractorInput input = new SabrExtractorInput(sabrStream); + input.init(new FakeExtractorInput.Builder().setData(out.toByteArray()).build()); + byte[] buffer = new byte[16]; + while (input.read(buffer, 0, buffer.length) != C.RESULT_END_OF_INPUT) { + // the segment's media + } + } + + private static void part(ByteArrayOutputStream out, int partId, byte[] payload) throws Exception { + out.write(partId); + out.write(payload.length); + out.write(payload); + } + + private static SabrManifest liveManifest(int targetDurationSec) { + Format audio = Format.createAudioContainerFormat( + String.valueOf(ITAG), null, MimeTypes.AUDIO_MP4, MimeTypes.AUDIO_AAC, null, null, + 144_000, 2, 44_100, null, 0, 0, "en"); + Representation representation = Representation.newInstance(audio, SABR_URL, + new SegmentTemplate(null, 1_000_000, 0, 0, C.INDEX_UNSET, targetDurationSec * 1_000_000L, null, null, null)); + Period period = new Period("test", 0, + Collections.singletonList(new AdaptationSet(0, C.TRACK_TYPE_AUDIO, Collections.singletonList(representation)))); + return new SabrManifest( + C.TIME_UNSET, 48 * 60 * 60 * 1_000L, 1_500, false, + C.TIME_UNSET, C.TIME_UNSET, C.TIME_UNSET, C.TIME_UNSET, + Collections.singletonList(period), SABR_URL, "", null, "test", + ClientInfo.getDefaultInstance(), null, targetDurationSec); + } + + private static DefaultSabrChunkSource source(SabrManifest manifest) { + AdaptationSet adaptationSet = manifest.getPeriod(0).adaptationSets.get(0); + return new DefaultSabrChunkSource( + new LoaderErrorThrower.Dummy(), manifest, 0, new int[] {0}, + new FixedTrackSelection(new TrackGroup(adaptationSet.representations.get(0).format), 0), C.TRACK_TYPE_AUDIO, + new RecordingDataSource(new byte[0]), 0, 1, false, Collections.emptyList(), null); + } + + private static DataSpec spec() { + return new DataSpec(Uri.parse(SABR_URL)); + } + + private static byte[] readAll(DataSource dataSource) throws IOException { + dataSource.open(spec()); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + byte[] buffer = new byte[2]; + int read; + while ((read = dataSource.read(buffer, 0, buffer.length)) != C.RESULT_END_OF_INPUT) { + out.write(buffer, 0, read); + } + dataSource.close(); + return out.toByteArray(); + } + + /** + * Its sources answer with the response, or fail for none + */ + private static final class RecordingFactory implements DataSource.Factory { + @Nullable private final byte[] response; + final List sources = Collections.synchronizedList(new ArrayList<>()); + + RecordingFactory(@Nullable byte[] response) { + this.response = response; + } + + @Override + public DataSource createDataSource() { + RecordingDataSource source = new RecordingDataSource(response); + sources.add(source); + return source; + } + } + + private static final class RecordingDataSource implements DataSource { + @Nullable private final byte[] response; + volatile int opened; + @Nullable volatile DataSpec dataSpec; + private int position; + + RecordingDataSource(@Nullable byte[] response) { + this.response = response; + } + + @Override + public void addTransferListener(TransferListener transferListener) { + } + + @Override + public long open(DataSpec dataSpec) throws IOException { + this.dataSpec = dataSpec; + opened++; + if (response == null) { + throw new IOException("test"); + } + position = 0; + return response.length; + } + + @Override + public int read(byte[] buffer, int offset, int readLength) { + if (response == null || position >= response.length) { + return C.RESULT_END_OF_INPUT; + } + int length = Math.min(readLength, response.length - position); + System.arraycopy(response, position, buffer, offset, length); + position += length; + return length; + } + + @Nullable + @Override + public Uri getUri() { + // As a real one's once open: a chunk's StatsDataSource asks for it + DataSpec dataSpec = this.dataSpec; + return dataSpec != null ? dataSpec.uri : null; + } + + @Override + public void close() { + } + } +} diff --git a/exoplayer-amzn-2.10.6/library/sabr/src/test/java/com/google/android/exoplayer2/source/sabr/SabrRefusedRequestTest.java b/exoplayer-amzn-2.10.6/library/sabr/src/test/java/com/google/android/exoplayer2/source/sabr/SabrRefusedRequestTest.java new file mode 100644 index 00000000000..948d0e9f8ce --- /dev/null +++ b/exoplayer-amzn-2.10.6/library/sabr/src/test/java/com/google/android/exoplayer2/source/sabr/SabrRefusedRequestTest.java @@ -0,0 +1,70 @@ +package com.google.android.exoplayer2.source.sabr; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; + +import android.net.Uri; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import com.google.android.exoplayer2.upstream.DataSpec; +import com.google.android.exoplayer2.upstream.HttpDataSource.InvalidResponseCodeException; +import com.google.android.exoplayer2.upstream.Loader.UnexpectedLoaderException; +import java.util.Collections; +import org.junit.After; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.annotation.Config; + +/** + * A 401 or 403 says what it refused, as a SabrProtocolError does (WVE7ZKDD #1, #2: a 403 on a rewind, with neither the request nor its + * session's age) + */ +@RunWith(AndroidJUnit4.class) +@Config(sdk = 28) +public class SabrRefusedRequestTest { + @After + public void tearDown() { + SabrRefusedRequest.resetForTesting(); + } + + @Test + public void aRefusalIsFoundByTheErrorItCameAs() { + InvalidResponseCodeException refusal = refusal(403); + + SabrRefusedRequest.onLoadError(refusal, "media, video 313, audio 251, selected 313, session 0 (first)", 87_000); + SabrRefusedRequest refused = SabrRefusedRequest.of(new UnexpectedLoaderException(refusal)); + + assertEquals("media, video 313, audio 251, selected 313, session 0 (first)", refused.request); + assertEquals(87_000, refused.sessionAgeMs); + assertSame(refused, SabrRefusedRequest.of(refusal)); + } + + /** + * Another error, or another refusal than the last one kept: none + */ + @Test + public void anotherErrorHasNone() { + SabrRefusedRequest.onLoadError(refusal(401), "init, video 136, audio 251, selected 251, session 1 (refetched)", 40); + + assertNull(SabrRefusedRequest.of(refusal(401))); + assertNull(SabrRefusedRequest.of(new IllegalStateException("offline"))); + assertNull(SabrRefusedRequest.of(null)); + } + + /** + * Not a refusal (e.g. a 503 of the server): not kept + */ + @Test + public void anotherResponseCodeIsntKept() { + InvalidResponseCodeException serverError = refusal(503); + + SabrRefusedRequest.onLoadError(serverError, "media, video 313, audio 251, selected 313, session 0 (first)", 1_000); + + assertNull(SabrRefusedRequest.of(serverError)); + } + + private static InvalidResponseCodeException refusal(int code) { + return new InvalidResponseCodeException(code, null, Collections.emptyMap(), + new DataSpec(Uri.parse("https://rr1---sn-test.googlevideo.com/videoplayback"))); + } +} diff --git a/exoplayer-amzn-2.10.6/library/sabr/src/test/java/com/google/android/exoplayer2/source/sabr/SabrSampleDeduplicatorTest.java b/exoplayer-amzn-2.10.6/library/sabr/src/test/java/com/google/android/exoplayer2/source/sabr/SabrSampleDeduplicatorTest.java new file mode 100644 index 00000000000..90d63875099 --- /dev/null +++ b/exoplayer-amzn-2.10.6/library/sabr/src/test/java/com/google/android/exoplayer2/source/sabr/SabrSampleDeduplicatorTest.java @@ -0,0 +1,161 @@ +package com.google.android.exoplayer2.source.sabr; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; + +import androidx.test.ext.junit.runners.AndroidJUnit4; + +import com.google.android.exoplayer2.C; +import com.google.android.exoplayer2.Format; +import com.google.android.exoplayer2.FormatHolder; +import com.google.android.exoplayer2.decoder.DecoderInputBuffer; +import com.google.android.exoplayer2.extractor.TrackOutput; +import com.google.android.exoplayer2.source.SampleQueue; +import com.google.android.exoplayer2.source.chunk.Chunk; +import com.google.android.exoplayer2.source.sabr.parser.SabrStream; +import com.google.android.exoplayer2.source.sabr.protos.videostreaming.StreamerContext.ClientInfo; +import com.google.android.exoplayer2.upstream.DefaultAllocator; +import com.google.android.exoplayer2.util.MimeTypes; +import com.google.android.exoplayer2.util.ParsableByteArray; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.annotation.Config; + +@RunWith(AndroidJUnit4.class) +@Config(sdk = 28) +public class SabrSampleDeduplicatorTest { + private static final int TRACK_ID = 1; + private static final int ITAG = 248; + + private final SabrSampleDeduplicator deduplicator = new SabrSampleDeduplicator(createStream()); + private final Chunk firstChunk = mock(Chunk.class); + private final Chunk secondChunk = mock(Chunk.class); + private final Chunk thirdChunk = mock(Chunk.class); + + @Test + public void queuesEverySampleOfOneResponse() { + assertTrue(queue(firstChunk, 7, 0)); + assertTrue(queue(firstChunk, 7, 100_000)); + assertTrue(queue(firstChunk, 7, 33_000)); + } + + @Test + public void dropsTheSamplesOfAResentSegmentThatAreAlreadyQueued() { + // Decode order with B-frames: the queued samples are not a prefix of the times + queue(firstChunk, 7, 0); + queue(firstChunk, 7, 100_000); + queue(firstChunk, 7, 33_000); + + assertFalse(queue(secondChunk, 7, 0)); + assertFalse(queue(secondChunk, 7, 100_000)); + assertFalse(queue(secondChunk, 7, 33_000)); + assertTrue(queue(secondChunk, 7, 66_000)); + assertTrue(queue(secondChunk, 7, 200_000)); + } + + @Test + public void dropsTheSamplesQueuedByEveryEarlierResponse() { + queue(firstChunk, 7, 0); + queue(secondChunk, 7, 0); + queue(secondChunk, 7, 33_000); + + assertFalse(queue(thirdChunk, 7, 0)); + assertFalse(queue(thirdChunk, 7, 33_000)); + assertTrue(queue(thirdChunk, 7, 66_000)); + } + + @Test + public void queuesTheNextSegment() { + queue(firstChunk, 7, 0); + + assertTrue(queue(secondChunk, 8, 5_000_000)); + } + + @Test + public void queuesTheSameSegmentOfAnotherFormat() { + deduplicator.shouldQueue(TRACK_ID, firstChunk, ITAG, 7, 0); + + assertTrue(deduplicator.shouldQueue(TRACK_ID, secondChunk, 247, 7, 0)); + } + + @Test + public void tracksAreIndependent() { + deduplicator.shouldQueue(TRACK_ID, firstChunk, ITAG, 7, 0); + + assertTrue(deduplicator.shouldQueue(TRACK_ID + 1, secondChunk, ITAG, 7, 0)); + } + + @Test + public void queuesASegmentAgainAfterAReset() { + queue(firstChunk, 7, 0); + deduplicator.reset(); + + assertTrue(queue(secondChunk, 7, 0)); + } + + @Test + public void droppedSampleDataIsSkippedInTheQueue() { + // The stream has not read any segment, so every sample belongs to the same one + SampleQueue sampleQueue = new SampleQueue(new DefaultAllocator(true, 16)); + TrackOutput first = deduplicator.wrap(firstChunk, (id, type) -> sampleQueue).track(TRACK_ID, C.TRACK_TYPE_VIDEO); + first.format(Format.createSampleFormat(null, MimeTypes.VIDEO_VP9, 0)); + writeSample(first, 0, 1, C.BUFFER_FLAG_KEY_FRAME); + writeSample(first, 33_000, 2, 0); + // A response that ended in the middle of the segment leaves part of a sample + first.sampleData(new ParsableByteArray(new byte[] {9, 9, 9}), 3); + + TrackOutput second = deduplicator.wrap(secondChunk, (id, type) -> sampleQueue).track(TRACK_ID, C.TRACK_TYPE_VIDEO); + writeSample(second, 0, 1, C.BUFFER_FLAG_KEY_FRAME); + writeSample(second, 33_000, 2, 0); + writeSample(second, 66_000, 3, 0); + + assertEquals(Arrays.asList("0:1", "33000:2", "66000:3"), readSamples(sampleQueue)); + } + + private boolean queue(Chunk chunk, long sequenceNumber, long timeUs) { + return deduplicator.shouldQueue(TRACK_ID, chunk, ITAG, sequenceNumber, timeUs); + } + + private static void writeSample(TrackOutput output, long timeUs, int value, int flags) { + byte[] data = new byte[] {(byte) value, (byte) value}; + output.sampleData(new ParsableByteArray(data), data.length); + output.sampleMetadata(timeUs, flags, data.length, 0, null); + } + + private static List readSamples(SampleQueue sampleQueue) { + List samples = new ArrayList<>(); + FormatHolder formatHolder = new FormatHolder(); + DecoderInputBuffer buffer = new DecoderInputBuffer(DecoderInputBuffer.BUFFER_REPLACEMENT_MODE_NORMAL); + + while (true) { + buffer.clear(); + int result = sampleQueue.read(formatHolder, buffer, false, false, 0); + + if (result == C.RESULT_NOTHING_READ) { + return samples; + } + + if (result == C.RESULT_BUFFER_READ) { + buffer.flip(); + byte[] data = new byte[buffer.data.remaining()]; + buffer.data.get(data); + assertEquals(2, data.length); + assertEquals(data[0], data[1]); + samples.add(buffer.timeUs + ":" + data[0]); + } + } + } + + private static SabrStream createStream() { + return new SabrStream( + "https://rr1---sn-primary.googlevideo.com/videoplayback", "", ClientInfo.getDefaultInstance(), + -1, -1, -1, null, false, "test", 60_000); + } +} diff --git a/exoplayer-amzn-2.10.6/library/sabr/src/test/java/com/google/android/exoplayer2/source/sabr/manifest/SabrCdnSelectorTest.java b/exoplayer-amzn-2.10.6/library/sabr/src/test/java/com/google/android/exoplayer2/source/sabr/manifest/SabrCdnSelectorTest.java index 406f3c99a86..2471c7cbf1e 100644 --- a/exoplayer-amzn-2.10.6/library/sabr/src/test/java/com/google/android/exoplayer2/source/sabr/manifest/SabrCdnSelectorTest.java +++ b/exoplayer-amzn-2.10.6/library/sabr/src/test/java/com/google/android/exoplayer2/source/sabr/manifest/SabrCdnSelectorTest.java @@ -4,30 +4,41 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; +import com.google.android.exoplayer2.source.sabr.GoogleVideoHosts; + import org.junit.Before; import org.junit.Test; public class SabrCdnSelectorTest { private static final String PRIMARY_URL = "https://rr1---sn-primary.googlevideo.com/videoplayback?" - + "mn=sn-primary%2Csn-secondary&sig=signed"; - private static final String SECONDARY_URL = - "https://rr2---sn-secondary.googlevideo.com/videoplayback?" - + "mn=sn-primary%2Csn-secondary&sig=signed"; + + "mn=sn-primary%2Csn-secondary&fvip=4&sig=signed"; + private static final String FALLBACK_URL = + "https://r4---sn-secondary.googlevideo.com/videoplayback?" + + "mn=sn-primary%2Csn-secondary&fvip=4&sig=signed&fallback_count=1"; @Before public void setUp() { - SabrCdnSelector.clearFailedNetworks(); + GoogleVideoHosts.clearFailedNetworks(); } @Test - public void startsWithOriginalUrlAndAdvancesOnce() { + public void startsWithOriginalUrlAndAdvancesOnceToTheFvipHost() { SabrCdnSelector selector = new SabrCdnSelector(PRIMARY_URL); assertEquals(PRIMARY_URL, selector.getCurrentUrl()); assertTrue(selector.maybeAdvance(PRIMARY_URL)); - assertEquals(SECONDARY_URL, selector.getCurrentUrl()); - assertFalse(selector.maybeAdvance(SECONDARY_URL)); + assertEquals(FALLBACK_URL, selector.getCurrentUrl()); + assertFalse(selector.maybeAdvance(FALLBACK_URL)); + assertEquals(FALLBACK_URL, selector.getCurrentUrl()); + } + + @Test + public void failureOfARequestWithItsOwnParametersIsMatchedByHost() { + SabrCdnSelector selector = new SabrCdnSelector(PRIMARY_URL); + + assertTrue(selector.maybeAdvance(PRIMARY_URL + "&rn=7")); + assertEquals(FALLBACK_URL, selector.getCurrentUrl()); } @Test @@ -36,25 +47,50 @@ public void staleFailureRemainsRetryableAfterAnotherTrackAdvances() { assertTrue(selector.maybeAdvance(PRIMARY_URL)); assertTrue(selector.maybeAdvance(PRIMARY_URL)); - assertEquals(SECONDARY_URL, selector.getCurrentUrl()); + assertEquals(FALLBACK_URL, selector.getCurrentUrl()); } @Test - public void advancesThroughAllAdvertisedNetworksWithoutWrapping() { + public void onlyTheSecondNetworkIsUsedWhateverTheirCount() { String primary = "https://rr1---sn-primary.googlevideo.com/videoplayback?" - + "mn=sn-primary%2Csn-secondary%2Csn-tertiary&sig=signed"; - String secondary = "https://rr2---sn-secondary.googlevideo.com/videoplayback?" - + "mn=sn-primary%2Csn-secondary%2Csn-tertiary&sig=signed"; - String tertiary = "https://rr3---sn-tertiary.googlevideo.com/videoplayback?" - + "mn=sn-primary%2Csn-secondary%2Csn-tertiary&sig=signed"; + + "mn=sn-primary%2Csn-secondary%2Csn-tertiary&fvip=2&sig=signed"; + String fallback = "https://r2---sn-secondary.googlevideo.com/videoplayback?" + + "mn=sn-primary%2Csn-secondary%2Csn-tertiary&fvip=2&sig=signed&fallback_count=1"; SabrCdnSelector selector = new SabrCdnSelector(primary); assertTrue(selector.maybeAdvance(primary)); - assertEquals(secondary, selector.getCurrentUrl()); - assertTrue(selector.maybeAdvance(secondary)); - assertEquals(tertiary, selector.getCurrentUrl()); - assertFalse(selector.maybeAdvance(tertiary)); - assertEquals(tertiary, selector.getCurrentUrl()); + assertEquals(fallback, selector.getCurrentUrl()); + assertFalse(selector.maybeAdvance(fallback)); + assertEquals(fallback, selector.getCurrentUrl()); + } + + @Test + public void urlWithoutFvipHasNoFallback() { + String url = "https://rr1---sn-primary.googlevideo.com/videoplayback?" + + "mn=sn-primary%2Csn-secondary&sig=signed"; + SabrCdnSelector selector = new SabrCdnSelector(url); + + assertFalse(selector.maybeAdvance(url)); + assertEquals(url, selector.getCurrentUrl()); + } + + @Test + public void urlWithASingleNetworkHasNoFallback() { + String url = "https://rr1---sn-primary.googlevideo.com/videoplayback?mn=sn-primary&fvip=4"; + SabrCdnSelector selector = new SabrCdnSelector(url); + + assertFalse(selector.maybeAdvance(url)); + assertEquals(url, selector.getCurrentUrl()); + } + + @Test + public void urlAlreadyOnTheFallbackHostHasNoFallback() { + String url = "https://r4---sn-secondary.googlevideo.com/videoplayback?" + + "mn=sn-primary%2Csn-secondary&fvip=4"; + SabrCdnSelector selector = new SabrCdnSelector(url); + + assertFalse(selector.maybeAdvance(url)); + assertEquals(url, selector.getCurrentUrl()); } @Test @@ -75,35 +111,63 @@ public void malformedCandidateIsIgnoredDuringFailureHandling() { } @Test - public void urlWithoutMatchingNetworkHasNoFallback() { - String url = "https://rr1---sn-other.googlevideo.com/videoplayback?" - + "mn=sn-primary%2Csn-secondary"; - SabrCdnSelector selector = new SabrCdnSelector(url); + public void newSelectorSkipsRecentlyFailedNetwork() { + SabrCdnSelector first = new SabrCdnSelector(PRIMARY_URL); + assertTrue(first.maybeAdvance(PRIMARY_URL)); - assertFalse(selector.maybeAdvance(url)); - assertEquals(url, selector.getCurrentUrl()); + // e.g. the engine was restarted: a new manifest is built from the same player response + SabrCdnSelector second = new SabrCdnSelector(PRIMARY_URL); + + assertEquals(FALLBACK_URL, second.getCurrentUrl()); } @Test - public void newSelectorSkipsRecentlyFailedNetwork() { + public void newSelectorSkipsANetworkTheDashRequestsMarkedFailed() { + GoogleVideoHosts.markNetworkFailed("https://rr5---sn-primary.googlevideo.com/videoplayback?itag=137"); + + assertEquals(FALLBACK_URL, new SabrCdnSelector(PRIMARY_URL).getCurrentUrl()); + } + + /** + * AWHPECZK: the fallback host failed too, while the first stayed skipped for half an hour. Every host failed: the first again. + */ + @Test + public void everyNetworkFailedStartsAgainFromTheFirst() { SabrCdnSelector first = new SabrCdnSelector(PRIMARY_URL); assertTrue(first.maybeAdvance(PRIMARY_URL)); + GoogleVideoHosts.markNetworkFailed(FALLBACK_URL); // e.g. by the DASH requests - // e.g. the engine was restarted: a new manifest is built from the same player response SabrCdnSelector second = new SabrCdnSelector(PRIMARY_URL); - assertEquals(SECONDARY_URL, second.getCurrentUrl()); + assertEquals(PRIMARY_URL, second.getCurrentUrl()); + assertFalse(GoogleVideoHosts.isNetworkFailed(PRIMARY_URL)); } @Test - public void lastNetworkIsKeptEvenIfAllFailed() { + public void theLastNetworkFailingTooMakesTheNextSelectionStartFromTheFirst() { SabrCdnSelector first = new SabrCdnSelector(PRIMARY_URL); assertTrue(first.maybeAdvance(PRIMARY_URL)); - assertFalse(first.maybeAdvance(SECONDARY_URL)); - SabrCdnSelector second = new SabrCdnSelector(PRIMARY_URL); + assertFalse(first.maybeAdvance(FALLBACK_URL)); // nothing left: the player's error handling goes on + + assertFalse(GoogleVideoHosts.isNetworkFailed(PRIMARY_URL)); + assertFalse(GoogleVideoHosts.isNetworkFailed(FALLBACK_URL)); + assertEquals(PRIMARY_URL, new SabrCdnSelector(PRIMARY_URL).getCurrentUrl()); + } + + /** + * The first one's skip ran out while the fallback host played: the fallback failing now leaves only itself skipped + */ + @Test + public void theLastNetworkFailingIsSkippedWhileTheFirstWorks() { + SabrCdnSelector first = new SabrCdnSelector(PRIMARY_URL); + assertTrue(first.maybeAdvance(PRIMARY_URL)); + GoogleVideoHosts.clearNetworkFailed(PRIMARY_URL); + + assertFalse(first.maybeAdvance(FALLBACK_URL)); - assertEquals(SECONDARY_URL, second.getCurrentUrl()); + assertTrue(GoogleVideoHosts.isNetworkFailed(FALLBACK_URL)); + assertEquals(PRIMARY_URL, new SabrCdnSelector(PRIMARY_URL).getCurrentUrl()); } @Test @@ -112,7 +176,7 @@ public void failedNetworkDoesNotAffectUnrelatedUrls() { assertTrue(first.maybeAdvance(PRIMARY_URL)); String other = "https://rr3---sn-other.googlevideo.com/videoplayback?" - + "mn=sn-other%2Csn-secondary&sig=signed"; + + "mn=sn-other%2Csn-secondary&fvip=4&sig=signed"; assertEquals(other, new SabrCdnSelector(other).getCurrentUrl()); } diff --git a/exoplayer-amzn-2.10.6/library/sabr/src/test/java/com/google/android/exoplayer2/source/sabr/manifest/SabrManifestSessionTest.java b/exoplayer-amzn-2.10.6/library/sabr/src/test/java/com/google/android/exoplayer2/source/sabr/manifest/SabrManifestSessionTest.java new file mode 100644 index 00000000000..db9531e3ef7 --- /dev/null +++ b/exoplayer-amzn-2.10.6/library/sabr/src/test/java/com/google/android/exoplayer2/source/sabr/manifest/SabrManifestSessionTest.java @@ -0,0 +1,64 @@ +package com.google.android.exoplayer2.source.sabr.manifest; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import androidx.test.ext.junit.runners.AndroidJUnit4; +import com.google.android.exoplayer2.source.sabr.protos.videostreaming.VideoPlaybackAbrRequest; +import com.liskovsoft.mediaserviceinterfaces.data.MediaItemFormatInfo; +import java.util.Collections; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.annotation.Config; + +/** + * A refused request says how its session came (see SabrManifest#describeRequest): a refusal 38-95 ms into a new session (0CW972QK, + * H8ZP1GPV) didn't come again with sessions the app asked for, and the server's asks, with their reload token, were the difference left + */ +@RunWith(AndroidJUnit4.class) +@Config(sdk = 28) +public class SabrManifestSessionTest { + @Test + public void eachSessionSaysHowItCame() { + SabrManifest manifest = new SabrManifestParser().parse(formatInfo()); + manifest.setSessionRefresher((token, callback) -> callback.onSession(new SabrSession("https://media.example/videoplayback?n=2", + "Cg==", null, manifest.getClientInfo(), Collections.emptySet()))); + + assertEquals(SabrManifest.SESSION_FIRST, manifest.getSessionOrigin()); + + manifest.requestSessionRefresh(manifest.getSessionId(), "reload-token"); + + assertEquals(1, manifest.getSessionId()); + assertEquals(SabrManifest.SESSION_ASKED_WITH_TOKEN, manifest.getSessionOrigin()); + + // Fetched again before they expire (see SabrManifestParser#refresh) + manifest.refreshSession("https://media.example/videoplayback?n=3", "Cg==", null); + + assertEquals(SabrManifest.SESSION_REFETCHED, manifest.getSessionOrigin()); + } + + @Test + public void theRequestSaysHowItsSessionCame() { + assertEquals("init, video none, audio none, selected none, session 2 (server-asked)", + SabrManifest.describeRequest(VideoPlaybackAbrRequest.newBuilder().build(), true, 2, SabrManifest.SESSION_ASKED)); + } + + private static MediaItemFormatInfo formatInfo() { + MediaItemFormatInfo formatInfo = mock(MediaItemFormatInfo.class); + MediaItemFormatInfo.ClientInfo clientInfo = mock(MediaItemFormatInfo.ClientInfo.class); + when(clientInfo.getClientName()).thenReturn("TVHTML5"); + when(clientInfo.getClientVersion()).thenReturn("test"); + when(clientInfo.getOsName()).thenReturn(""); + when(clientInfo.getOsVersion()).thenReturn(""); + when(formatInfo.getClientInfo()).thenReturn(clientInfo); + when(formatInfo.getLengthSeconds()).thenReturn("60"); + when(formatInfo.getVideoId()).thenReturn("Hf-CqpBeDs0"); + when(formatInfo.getServerAbrStreamingUrl()).thenReturn("https://media.example/videoplayback?n=1"); + when(formatInfo.getVideoPlaybackUstreamerConfig()).thenReturn("Cg=="); + when(formatInfo.getAdaptiveFormats()).thenReturn(Collections.emptyList()); + when(formatInfo.getSubtitles()).thenReturn(Collections.emptyList()); + + return formatInfo; + } +} diff --git a/exoplayer-amzn-2.10.6/library/sabr/src/test/java/com/google/android/exoplayer2/source/sabr/parser/SabrStreamBrokenResponseTest.java b/exoplayer-amzn-2.10.6/library/sabr/src/test/java/com/google/android/exoplayer2/source/sabr/parser/SabrStreamBrokenResponseTest.java new file mode 100644 index 00000000000..f70681c5d66 --- /dev/null +++ b/exoplayer-amzn-2.10.6/library/sabr/src/test/java/com/google/android/exoplayer2/source/sabr/parser/SabrStreamBrokenResponseTest.java @@ -0,0 +1,184 @@ +package com.google.android.exoplayer2.source.sabr.parser; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import androidx.test.ext.junit.runners.AndroidJUnit4; + +import com.google.android.exoplayer2.C; +import com.google.android.exoplayer2.source.sabr.parser.exceptions.BrokenPartError; +import com.google.android.exoplayer2.source.sabr.parser.exceptions.BrokenResponseError; +import com.google.android.exoplayer2.source.sabr.parser.exceptions.UnknownPartError; +import com.google.android.exoplayer2.source.sabr.parser.misc.SabrExtractorInput; +import com.google.android.exoplayer2.source.sabr.parser.models.AudioSelector; +import com.google.android.exoplayer2.source.sabr.parser.ump.UMPPart; +import com.google.android.exoplayer2.source.sabr.parser.ump.UMPPartId; +import com.google.android.exoplayer2.source.sabr.protos.misc.FormatId; +import com.google.android.exoplayer2.source.sabr.protos.videostreaming.FormatInitializationMetadata; +import com.google.android.exoplayer2.source.sabr.protos.videostreaming.StreamerContext.ClientInfo; +import com.google.android.exoplayer2.testutil.FakeExtractorInput; + +import java.io.ByteArrayOutputStream; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.annotation.Config; + +/** + * A response whose bytes don't read as UMP parts: the errors say where in the response it went wrong (see BrokenResponseError), and a + * payload that isn't the protobuf its id says is one of them, not a failure of the connection + */ +@RunWith(AndroidJUnit4.class) +@Config(sdk = 28) +public class SabrStreamBrokenResponseTest { + private static final int ITAG = 140; + private static final int UNKNOWN_PART_ID = 120; + + /** + * The parts read before it, with their sizes, and the bytes the parts were read to: a read that went out of step in the middle + */ + @Test + public void anUnknownPartTellsThePartsBeforeIt() throws Exception { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + part(out, UMPPartId.FORMAT_INITIALIZATION_METADATA, formatMetadata()); + part(out, UNKNOWN_PART_ID, new byte[] {1, 2, 3}); + + BrokenResponseError error = readFailure(out.toByteArray()); + + assertTrue(error instanceof UnknownPartError); + assertTrue(error.getMessage(), error.getMessage().contains("Unknown part encountered: id=" + UNKNOWN_PART_ID + ", size=3")); + assertTrue(error.getMessage(), error.getMessage().contains(", after parts " + UMPPartId.FORMAT_INITIALIZATION_METADATA + ":" + + formatMetadata().length + " " + UNKNOWN_PART_ID + ":3")); + } + + /** + * A response that isn't UMP from its first byte (a page, bytes the connection should have decoded) has no part before it + */ + @Test + public void aFirstPartThatIsUnknownHasOnlyItselfInTheTrail() throws Exception { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + part(out, UNKNOWN_PART_ID, new byte[] {60, 33, 68}); + + BrokenResponseError error = readFailure(out.toByteArray()); + + assertTrue(error.getMessage(), error.getMessage().contains(", after parts " + UNKNOWN_PART_ID + ":3")); + } + + /** + * The next response's parts start the trail again: the first part of this one isn't told after the last one's + */ + @Test + public void theTrailStartsAgainWithAResponse() throws Exception { + SabrStream sabrStream = newStream(); + ByteArrayOutputStream first = new ByteArrayOutputStream(); + part(first, UMPPartId.FORMAT_INITIALIZATION_METADATA, formatMetadata()); + read(sabrStream, first.toByteArray()); + + ByteArrayOutputStream second = new ByteArrayOutputStream(); + part(second, UNKNOWN_PART_ID, new byte[] {9}); + + try { + read(sabrStream, second.toByteArray()); + fail("An unknown part is a broken response"); + } catch (BrokenResponseError error) { + assertTrue(error.getMessage(), error.getMessage().contains(", after parts " + UNKNOWN_PART_ID + ":1")); + } + } + + /** + * Its id is a known part's and its size is right: the bytes of its payload aren't the message (DMQEWB9B #1: "Protocol message tag + * had invalid wire type" in a NextRequestPolicy) + */ + @Test + public void aPayloadThatIsNotItsMessageIsABrokenPart() throws Exception { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + // Field 15, wire type 7: no such wire type + part(out, UMPPartId.NEXT_REQUEST_POLICY, new byte[] {0x7F}); + + BrokenResponseError error = readFailure(out.toByteArray()); + + assertTrue(error instanceof BrokenPartError); + assertTrue(error.getMessage(), error.getMessage().contains("InvalidProtocolBufferException")); + assertTrue(error.getMessage(), error.getMessage().contains(", after parts " + UMPPartId.NEXT_REQUEST_POLICY + ":1")); + } + + /** + * A size read out of step is past what an int holds (FVNAAYZD #15: -1721324469): it can't be skipped, which isn't a read that failed + */ + @Test + public void aNegativeSizeIsABrokenPart() { + UMPPart part = new UMPPart(87, -1_721_324_469, new FakeExtractorInput.Builder().setData(new byte[16]).build()); + + try { + part.skip(); + fail("A negative size can't be skipped"); + } catch (BrokenPartError error) { + assertEquals("Cannot skip part with the id: 87, and size: -1721324469", error.getMessage()); + } + } + + /** + * What the chunk source adds: what the response was + */ + @Test + public void theResponseIsToldAfterThePartsAndLeavesOutWhatIsNotKnown() { + BrokenResponseError error = new UnknownPartError("Unknown part encountered: id=120, size=3, position=5"); + error.setPartTrail("120:3"); + error.setResponse("application/vnd.yt-ump", "gzip", 4_096, 1_024); + + assertEquals("Unknown part encountered: id=120, size=3, position=5, after parts 120:3, content type: application/vnd.yt-ump" + + ", content encoding: gzip, content length: 4096, loaded: 1024", error.getMessage()); + + error.setResponse(null, null, -1, -1); + + assertEquals("Unknown part encountered: id=120, size=3, position=5, after parts 120:3", error.getMessage()); + } + + private static BrokenResponseError readFailure(byte[] response) throws Exception { + try { + read(newStream(), response); + } catch (BrokenResponseError error) { + return error; + } + + fail("A response that doesn't read as parts is a broken response"); + + return null; + } + + private static byte[] formatMetadata() { + return FormatInitializationMetadata.newBuilder() + .setFormatId(FormatId.newBuilder().setItag(ITAG).build()) + .setMimeType("audio/mp4; codecs=\"mp4a.40.2\"") + .build().toByteArray(); + } + + private static SabrStream newStream() { + SabrStream sabrStream = new SabrStream( + "https://rr1---sn-primary.googlevideo.com/videoplayback", "", ClientInfo.getDefaultInstance(), + 1, -1, -1, null, false, "test", C.TIME_UNSET); + sabrStream.setFormatSelector(new AudioSelector("audio", false, FormatId.newBuilder().setItag(ITAG).build())); + + return sabrStream; + } + + /** + * Ids and sizes below 128: a one-byte varint each + */ + private static void part(ByteArrayOutputStream out, int partId, byte[] payload) throws Exception { + out.write(partId); + out.write(payload.length); + out.write(payload); + } + + private static void read(SabrStream sabrStream, byte[] response) throws Exception { + SabrExtractorInput input = new SabrExtractorInput(sabrStream); + input.init(new FakeExtractorInput.Builder().setData(response).build()); + byte[] buffer = new byte[16]; + + while (input.read(buffer, 0, buffer.length) != C.RESULT_END_OF_INPUT) { + // Read to its end + } + } +} diff --git a/exoplayer-amzn-2.10.6/library/sabr/src/test/java/com/google/android/exoplayer2/source/sabr/parser/SabrStreamLiveTest.java b/exoplayer-amzn-2.10.6/library/sabr/src/test/java/com/google/android/exoplayer2/source/sabr/parser/SabrStreamLiveTest.java new file mode 100644 index 00000000000..e71608dc90c --- /dev/null +++ b/exoplayer-amzn-2.10.6/library/sabr/src/test/java/com/google/android/exoplayer2/source/sabr/parser/SabrStreamLiveTest.java @@ -0,0 +1,148 @@ +package com.google.android.exoplayer2.source.sabr.parser; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import androidx.test.ext.junit.runners.AndroidJUnit4; + +import com.google.android.exoplayer2.C; +import com.google.android.exoplayer2.source.sabr.parser.misc.SabrExtractorInput; +import com.google.android.exoplayer2.source.sabr.parser.models.AudioSelector; +import com.google.android.exoplayer2.source.sabr.parser.ump.UMPPartId; +import com.google.android.exoplayer2.source.sabr.protos.misc.FormatId; +import com.google.android.exoplayer2.source.sabr.protos.videostreaming.FormatInitializationMetadata; +import com.google.android.exoplayer2.source.sabr.protos.videostreaming.LiveMetadata; +import com.google.android.exoplayer2.source.sabr.protos.videostreaming.MediaHeader; +import com.google.android.exoplayer2.source.sabr.protos.videostreaming.SabrSeek; +import com.google.android.exoplayer2.source.sabr.protos.videostreaming.StreamerContext.ClientInfo; +import com.google.android.exoplayer2.source.sabr.protos.videostreaming.TimeRange; +import com.google.android.exoplayer2.testutil.FakeExtractorInput; + +import java.io.ByteArrayOutputStream; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.annotation.Config; + +/** + * A live stream's response: its live metadata and seek parts, and media headers with a start but no duration (seen 2026-11-15) + */ +@RunWith(AndroidJUnit4.class) +@Config(sdk = 28) +public class SabrStreamLiveTest { + private static final int ITAG = 140; + private static final int SEQUENCE = 3_621; + private static final long START_MS = 18_089_994; + private static final byte[] MEDIA_DATA = {5, 6, 7, 8, 9, 10}; + + /** + * Its estimate, a tolerance short of the target (see SabrProcessor#processMediaHeader), is kept: the next request asks for the time + * after the segment. Without it, it asked for the segment's start, and the server answered with the same segment's start again. + */ + @Test + public void aLiveSegmentWithoutDurationIsGivenTheTargets() throws Exception { + SabrStream sabrStream = newStream(2); + sabrStream.setLive(true); + + assertArrayEquals(MEDIA_DATA, readAll(sabrStream, liveResponse(true))); + + assertEquals(1_900, sabrStream.getSegmentDurationMs(ITAG)); + assertEquals(START_MS + 1_900, sabrStream.getSegmentStartTimeMs(ITAG)); + assertEquals(SEQUENCE, sabrStream.getInitializedFormat(ITAG).getSequenceNumber()); + } + + /** + * Skipped as unknown before 2026-11-15: the segment had no duration (Cannot determine duration of segment), and the stream failed + */ + @Test + public void theLiveMetadataMakesTheStreamLive() throws Exception { + SabrStream sabrStream = newStream(5); + + assertArrayEquals(MEDIA_DATA, readAll(sabrStream, liveResponse(true))); + + assertTrue(sabrStream.isLive()); + assertEquals(4_900, sabrStream.getSegmentDurationMs(ITAG)); + } + + @Test + public void aLiveStreamWithoutLiveMetadataYetIsLiveByItsFormatInfo() throws Exception { + SabrStream sabrStream = newStream(1); + sabrStream.setLive(true); + + assertArrayEquals(MEDIA_DATA, readAll(sabrStream, liveResponse(false))); + + assertEquals(900, sabrStream.getSegmentDurationMs(ITAG)); + } + + private static SabrStream newStream(int targetDurationSec) { + SabrStream sabrStream = new SabrStream( + "https://rr1---sn-primary.googlevideo.com/videoplayback", "", ClientInfo.getDefaultInstance(), + targetDurationSec, -1, -1, null, false, "test", C.TIME_UNSET); + sabrStream.setFormatSelector(new AudioSelector("audio", false, FormatId.newBuilder().setItag(ITAG).build())); + return sabrStream; + } + + /** + * As the server sends it for a live stream: the format's metadata, the live metadata, a seek to the head, then a segment whose + * header has a start (in ms and in ticks) but no duration + */ + private static byte[] liveResponse(boolean withLiveMetadata) throws Exception { + FormatId formatId = FormatId.newBuilder().setItag(ITAG).build(); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + part(out, UMPPartId.FORMAT_INITIALIZATION_METADATA, FormatInitializationMetadata.newBuilder() + .setFormatId(formatId) + .setMimeType("audio/mp4; codecs=\"mp4a.40.2\"") + .build().toByteArray()); + + if (withLiveMetadata) { + part(out, UMPPartId.LIVE_METADATA, LiveMetadata.newBuilder() + .setHeadSequenceNumber(SEQUENCE + 2) + .setHeadSequenceTimeMs(START_MS + 10_000) + .setMaxSeekableTimeTicks(START_MS * 1_000) + .setMaxSeekableTimescale(1_000_000) + .build().toByteArray()); + part(out, UMPPartId.SABR_SEEK, SabrSeek.newBuilder() + .setSeekMediaTime(START_MS * 44_100 / 1_000) + .setSeekMediaTimescale(44_100) + .build().toByteArray()); + } + + part(out, UMPPartId.MEDIA_HEADER, MediaHeader.newBuilder() + .setHeaderId(0) + .setItag(ITAG) + .setFormatId(formatId) + .setSequenceNumber(SEQUENCE) + .setStartMs(START_MS) + .setTimeRange(TimeRange.newBuilder().setStartTicks(START_MS * 44_100 / 1_000).setTimescale(44_100).build()) + .build().toByteArray()); + byte[] media = new byte[1 + MEDIA_DATA.length]; + System.arraycopy(MEDIA_DATA, 0, media, 1, MEDIA_DATA.length); + part(out, UMPPartId.MEDIA, media); + part(out, UMPPartId.MEDIA_END, new byte[] {0}); + return out.toByteArray(); + } + + /** + * Ids and sizes below 128: a one-byte varint each + */ + private static void part(ByteArrayOutputStream out, int partId, byte[] payload) throws Exception { + out.write(partId); + out.write(payload.length); + out.write(payload); + } + + private static byte[] readAll(SabrStream sabrStream, byte[] response) throws Exception { + SabrExtractorInput input = new SabrExtractorInput(sabrStream); + input.init(new FakeExtractorInput.Builder().setData(response).build()); + ByteArrayOutputStream result = new ByteArrayOutputStream(); + byte[] buffer = new byte[16]; + int read; + + while ((read = input.read(buffer, 0, buffer.length)) != C.RESULT_END_OF_INPUT) { + result.write(buffer, 0, read); + } + + return result.toByteArray(); + } +} diff --git a/exoplayer-amzn-2.10.6/library/sabr/src/test/java/com/google/android/exoplayer2/source/sabr/parser/adapter/SabrFragmentedMp4AdapterTest.java b/exoplayer-amzn-2.10.6/library/sabr/src/test/java/com/google/android/exoplayer2/source/sabr/parser/adapter/SabrFragmentedMp4AdapterTest.java new file mode 100644 index 00000000000..f1e6907271d --- /dev/null +++ b/exoplayer-amzn-2.10.6/library/sabr/src/test/java/com/google/android/exoplayer2/source/sabr/parser/adapter/SabrFragmentedMp4AdapterTest.java @@ -0,0 +1,111 @@ +package com.google.android.exoplayer2.source.sabr.parser.adapter; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.fail; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import android.net.Uri; + +import androidx.test.ext.junit.runners.AndroidJUnit4; + +import com.google.android.exoplayer2.ParserException; +import com.google.android.exoplayer2.extractor.Extractor; +import com.google.android.exoplayer2.extractor.ExtractorInput; +import com.google.android.exoplayer2.extractor.ExtractorOutput; +import com.google.android.exoplayer2.extractor.PositionHolder; +import com.google.android.exoplayer2.source.sabr.parser.SabrStream; +import com.google.android.exoplayer2.source.sabr.parser.exceptions.SabrProtocolError; +import com.google.android.exoplayer2.source.sabr.parser.misc.SabrExtractorInputTest; +import com.google.android.exoplayer2.source.sabr.protos.videostreaming.StreamerContext.ClientInfo; +import com.google.android.exoplayer2.testutil.FakeExtractorInput; +import com.google.android.exoplayer2.upstream.DataSpec; +import com.google.android.exoplayer2.upstream.HttpDataSource.HttpDataSourceException; +import com.google.android.exoplayer2.upstream.HttpDataSource.InvalidResponseCodeException; + +import java.io.IOException; +import java.io.InterruptedIOException; +import java.net.SocketTimeoutException; +import java.util.Collections; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.annotation.Config; + +@RunWith(AndroidJUnit4.class) +@Config(sdk = 28) +public class SabrFragmentedMp4AdapterTest { + private static final DataSpec DATA_SPEC = new DataSpec(Uri.parse("https://rr1---sn-primary.googlevideo.com/videoplayback")); + + private final SabrStream sabrStream = new SabrStream( + "https://rr1---sn-primary.googlevideo.com/videoplayback", "", ClientInfo.getDefaultInstance(), + -1, -1, -1, null, false, "test", 60_000); + private final SabrFragmentedMp4Adapter adapter = new SabrFragmentedMp4Adapter(sabrStream); + + @Before + public void setUp() { + adapter.init(mock(ExtractorOutput.class)); + } + + @Test + public void endsTheChunkWhenTheConnectionBreaks() throws Exception { + HttpDataSourceException error = new HttpDataSourceException( + new SocketTimeoutException("timeout"), DATA_SPEC, HttpDataSourceException.TYPE_READ); + + assertEquals(Extractor.RESULT_END_OF_INPUT, adapter.read(failingInput(error), new PositionHolder())); + assertSame(error, sabrStream.pollResponseError()); + assertNull(sabrStream.pollResponseError()); + } + + @Test + public void propagatesAnAnswerOfTheServer() throws Exception { + InvalidResponseCodeException error = new InvalidResponseCodeException( + 403, Collections.emptyMap(), DATA_SPEC); + + assertReadFails(error); + } + + @Test + public void propagatesACanceledRead() throws Exception { + HttpDataSourceException error = new HttpDataSourceException( + new InterruptedIOException("interrupted"), DATA_SPEC, HttpDataSourceException.TYPE_READ); + + assertReadFails(error); + } + + @Test + public void propagatesAParserError() throws Exception { + assertReadFails(new ParserException("broken part")); + } + + /** + * The server refused the request: the load fails with it, as in SabrMatroskaAdapter + */ + @Test(expected = SabrProtocolError.class) + public void propagatesASabrError() throws Exception { + adapter.read(new FakeExtractorInput.Builder().setData(SabrExtractorInputTest.sabrErrorResponse()).build(), new PositionHolder()); + } + + private void assertReadFails(IOException error) throws Exception { + try { + adapter.read(failingInput(error), new PositionHolder()); + fail(); + } catch (IllegalStateException e) { + assertSame(error, e.getCause()); // see UMPDecoder + } + + assertNull(sabrStream.pollResponseError()); + } + + private static ExtractorInput failingInput(IOException error) throws Exception { + ExtractorInput input = mock(ExtractorInput.class); + when(input.readFully(any(), anyInt(), anyInt(), anyBoolean())).thenThrow(error); + return input; + } +} diff --git a/exoplayer-amzn-2.10.6/library/sabr/src/test/java/com/google/android/exoplayer2/source/sabr/parser/adapter/SabrMatroskaAdapterLiveTest.java b/exoplayer-amzn-2.10.6/library/sabr/src/test/java/com/google/android/exoplayer2/source/sabr/parser/adapter/SabrMatroskaAdapterLiveTest.java new file mode 100644 index 00000000000..416c123d0d3 --- /dev/null +++ b/exoplayer-amzn-2.10.6/library/sabr/src/test/java/com/google/android/exoplayer2/source/sabr/parser/adapter/SabrMatroskaAdapterLiveTest.java @@ -0,0 +1,170 @@ +package com.google.android.exoplayer2.source.sabr.parser.adapter; + +import static org.junit.Assert.assertEquals; + +import androidx.test.ext.junit.runners.AndroidJUnit4; + +import com.google.android.exoplayer2.extractor.Extractor; +import com.google.android.exoplayer2.extractor.PositionHolder; +import com.google.android.exoplayer2.source.sabr.parser.SabrStream; +import com.google.android.exoplayer2.source.sabr.parser.models.VideoSelector; +import com.google.android.exoplayer2.source.sabr.parser.ump.UMPPartId; +import com.google.android.exoplayer2.source.sabr.protos.misc.FormatId; +import com.google.android.exoplayer2.source.sabr.protos.videostreaming.FormatInitializationMetadata; +import com.google.android.exoplayer2.source.sabr.protos.videostreaming.MediaHeader; +import com.google.android.exoplayer2.source.sabr.protos.videostreaming.StreamerContext.ClientInfo; +import com.google.android.exoplayer2.source.sabr.protos.videostreaming.TimeRange; +import com.google.android.exoplayer2.testutil.FakeExtractorInput; +import com.google.android.exoplayer2.testutil.FakeExtractorOutput; +import com.google.android.exoplayer2.testutil.FakeTrackOutput; + +import java.io.ByteArrayOutputStream; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.annotation.Config; + +/** + * A live WebM segment is a whole WebM file: its own EBML header and Segment. After a start or a seek the server answers with several: + * read on from the first's end, the second Segment was refused (Multiple Segment elements not supported), the chunk ended with the first + * segment, and the rest of the response was thrown away, then asked for again (~3 MB per response for a 4K stream, 2026-11-15). + */ +@RunWith(AndroidJUnit4.class) +@Config(sdk = 28) +public class SabrMatroskaAdapterLiveTest { + private static final int ITAG = 248; + private static final int SEQUENCE = 466_988; + private static final long START_MS = 18_089_000; + private static final int TRACK_NUMBER = 1; + + @Test + public void readsEachLiveSegmentOfAResponse() throws Exception { + SabrStream sabrStream = newStream(); + sabrStream.setLive(true); + FakeExtractorOutput output = new FakeExtractorOutput(); + SabrMatroskaAdapter adapter = new SabrMatroskaAdapter(sabrStream); + adapter.init(output); + + readAll(adapter, response(webm(1_000, new byte[] {1, 2, 3, 4}), webm(2_000, new byte[] {5, 6, 7, 8}))); + + FakeTrackOutput track = output.trackOutputs.get(TRACK_NUMBER); + assertEquals(2, track.getSampleCount()); + assertEquals(1_000_000, track.getSampleTimeUs(0)); + assertEquals(2_000_000, track.getSampleTimeUs(1)); + } + + private static SabrStream newStream() { + SabrStream sabrStream = new SabrStream( + "https://rr1---sn-primary.googlevideo.com/videoplayback", "", ClientInfo.getDefaultInstance(), + 1, -1, -1, null, false, "test", 60_000); + sabrStream.setFormatSelector(new VideoSelector("video", false, FormatId.newBuilder().setItag(ITAG).build())); + return sabrStream; + } + + private static void readAll(SabrMatroskaAdapter adapter, byte[] response) throws Exception { + FakeExtractorInput input = new FakeExtractorInput.Builder().setData(response).build(); + PositionHolder positionHolder = new PositionHolder(); + int result; + + do { + result = adapter.read(input, positionHolder); + } while (result == Extractor.RESULT_CONTINUE); + + assertEquals(Extractor.RESULT_END_OF_INPUT, result); + } + + /** + * As the server sends two live segments: the format's metadata, then a header, the data and the end of each + */ + private static byte[] response(byte[] first, byte[] second) throws Exception { + FormatId formatId = FormatId.newBuilder().setItag(ITAG).build(); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + part(out, UMPPartId.FORMAT_INITIALIZATION_METADATA, FormatInitializationMetadata.newBuilder() + .setFormatId(formatId) + .setMimeType("video/webm; codecs=\"vp9\"") + .build().toByteArray()); + segment(out, formatId, 0, SEQUENCE, START_MS, first); + segment(out, formatId, 1, SEQUENCE + 1, START_MS + 1_000, second); + return out.toByteArray(); + } + + private static void segment(ByteArrayOutputStream out, FormatId formatId, int headerId, int sequence, long startMs, byte[] data) + throws Exception { + part(out, UMPPartId.MEDIA_HEADER, MediaHeader.newBuilder() + .setHeaderId(headerId) + .setItag(ITAG) + .setFormatId(formatId) + .setSequenceNumber(sequence) + .setStartMs(startMs) + .setTimeRange(TimeRange.newBuilder().setStartTicks(startMs).setTimescale(1_000).build()) + .build().toByteArray()); + byte[] media = new byte[1 + data.length]; + media[0] = (byte) headerId; + System.arraycopy(data, 0, media, 1, data.length); + part(out, UMPPartId.MEDIA, media); + part(out, UMPPartId.MEDIA_END, new byte[] {(byte) headerId}); + } + + /** + * A whole WebM file, as a live segment is: EBML header, then a Segment with its info, a VP9 track and a cluster of one keyframe + */ + private static byte[] webm(int clusterTimecodeMs, byte[] frame) throws Exception { + byte[] ebml = element(0x1A45DFA3, element(0x4282, "webm".getBytes("US-ASCII"))); + byte[] info = element(0x1549A966, element(0x2AD7B1, new byte[] {0x0F, 0x42, 0x40})); // timecode scale: 1 ms + byte[] video = element(0xE0, concat(element(0xB0, new byte[] {0x05, 0x00}), element(0xBA, new byte[] {0x02, (byte) 0xD0}))); + byte[] trackEntry = element(0xAE, concat( + element(0xD7, new byte[] {TRACK_NUMBER}), + element(0x83, new byte[] {1}), // video + element(0x86, "V_VP9".getBytes("US-ASCII")), + video)); + byte[] tracks = element(0x1654AE6B, trackEntry); + byte[] simpleBlock = concat(new byte[] {(byte) (0x80 | TRACK_NUMBER), 0, 0, (byte) 0x80}, frame); // track, timecode 0, keyframe + byte[] cluster = element(0x1F43B675, concat( + element(0xE7, new byte[] {(byte) (clusterTimecodeMs >> 8), (byte) clusterTimecodeMs}), + element(0xA3, simpleBlock))); + return concat(ebml, element(0x18538067, concat(info, tracks, cluster))); + } + + /** + * Its id's bytes as written (the id keeps its length marker), and a one-byte size + */ + private static byte[] element(int id, byte[] content) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + int idLength = id > 0xFFFFFF ? 4 : id > 0xFFFF ? 3 : id > 0xFF ? 2 : 1; + + for (int i = idLength - 1; i >= 0; i--) { + out.write(id >> (8 * i)); + } + + if (content.length >= 0x7F) { + throw new IllegalArgumentException("One-byte sizes only: " + content.length); + } + + out.write(0x80 | content.length); + out.write(content, 0, content.length); + return out.toByteArray(); + } + + private static byte[] concat(byte[]... parts) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + + for (byte[] part : parts) { + out.write(part, 0, part.length); + } + + return out.toByteArray(); + } + + /** + * Ids and sizes below 128: a one-byte varint each + */ + private static void part(ByteArrayOutputStream out, int partId, byte[] payload) { + if (payload.length >= 128) { + throw new IllegalArgumentException("One-byte sizes only: " + payload.length); + } + + out.write(partId); + out.write(payload.length); + out.write(payload, 0, payload.length); + } +} diff --git a/exoplayer-amzn-2.10.6/library/sabr/src/test/java/com/google/android/exoplayer2/source/sabr/parser/adapter/SabrMatroskaAdapterTest.java b/exoplayer-amzn-2.10.6/library/sabr/src/test/java/com/google/android/exoplayer2/source/sabr/parser/adapter/SabrMatroskaAdapterTest.java new file mode 100644 index 00000000000..bb1c29ce249 --- /dev/null +++ b/exoplayer-amzn-2.10.6/library/sabr/src/test/java/com/google/android/exoplayer2/source/sabr/parser/adapter/SabrMatroskaAdapterTest.java @@ -0,0 +1,84 @@ +package com.google.android.exoplayer2.source.sabr.parser.adapter; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import android.net.Uri; + +import androidx.test.ext.junit.runners.AndroidJUnit4; + +import com.google.android.exoplayer2.extractor.Extractor; +import com.google.android.exoplayer2.extractor.ExtractorInput; +import com.google.android.exoplayer2.extractor.ExtractorOutput; +import com.google.android.exoplayer2.extractor.PositionHolder; +import com.google.android.exoplayer2.source.sabr.parser.SabrStream; +import com.google.android.exoplayer2.source.sabr.parser.exceptions.SabrProtocolError; +import com.google.android.exoplayer2.source.sabr.parser.misc.SabrExtractorInputTest; +import com.google.android.exoplayer2.source.sabr.protos.videostreaming.StreamerContext.ClientInfo; +import com.google.android.exoplayer2.testutil.FakeExtractorInput; +import com.google.android.exoplayer2.upstream.DataSpec; +import com.google.android.exoplayer2.upstream.HttpDataSource.HttpDataSourceException; + +import java.io.IOException; +import java.io.InterruptedIOException; +import java.net.SocketTimeoutException; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.annotation.Config; + +@RunWith(AndroidJUnit4.class) +@Config(sdk = 28) +public class SabrMatroskaAdapterTest { + private static final DataSpec DATA_SPEC = new DataSpec(Uri.parse("https://rr1---sn-primary.googlevideo.com/videoplayback")); + + private final SabrStream sabrStream = new SabrStream( + "https://rr1---sn-primary.googlevideo.com/videoplayback", "", ClientInfo.getDefaultInstance(), + -1, -1, -1, null, false, "test", 60_000); + private final SabrMatroskaAdapter adapter = new SabrMatroskaAdapter(sabrStream); + + @Before + public void setUp() { + adapter.init(mock(ExtractorOutput.class)); + } + + @Test + public void reportsABrokenConnection() throws Exception { + HttpDataSourceException error = new HttpDataSourceException( + new SocketTimeoutException("timeout"), DATA_SPEC, HttpDataSourceException.TYPE_READ); + + assertEquals(Extractor.RESULT_END_OF_INPUT, adapter.read(failingInput(error), new PositionHolder())); + assertSame(error, sabrStream.pollResponseError()); + } + + @Test + public void doesNotReportACanceledRead() throws Exception { + HttpDataSourceException error = new HttpDataSourceException( + new InterruptedIOException("interrupted"), DATA_SPEC, HttpDataSourceException.TYPE_READ); + + assertEquals(Extractor.RESULT_END_OF_INPUT, adapter.read(failingInput(error), new PositionHolder())); + assertNull(sabrStream.pollResponseError()); + } + + /** + * The server refused the request: the load fails with it. Swallowed, the chunk ended as if it had come, and the next one was + * refused again. + */ + @Test(expected = SabrProtocolError.class) + public void propagatesASabrError() throws Exception { + adapter.read(new FakeExtractorInput.Builder().setData(SabrExtractorInputTest.sabrErrorResponse()).build(), new PositionHolder()); + } + + private static ExtractorInput failingInput(IOException error) throws Exception { + ExtractorInput input = mock(ExtractorInput.class); + when(input.readFully(any(), anyInt(), anyInt(), anyBoolean())).thenThrow(error); + return input; + } +} diff --git a/exoplayer-amzn-2.10.6/library/sabr/src/test/java/com/google/android/exoplayer2/source/sabr/parser/exceptions/SabrProtocolErrorTest.java b/exoplayer-amzn-2.10.6/library/sabr/src/test/java/com/google/android/exoplayer2/source/sabr/parser/exceptions/SabrProtocolErrorTest.java new file mode 100644 index 00000000000..ee7df66355b --- /dev/null +++ b/exoplayer-amzn-2.10.6/library/sabr/src/test/java/com/google/android/exoplayer2/source/sabr/parser/exceptions/SabrProtocolErrorTest.java @@ -0,0 +1,55 @@ +package com.google.android.exoplayer2.source.sabr.parser.exceptions; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import com.google.android.exoplayer2.source.sabr.protos.videostreaming.SabrError; + +import org.junit.Test; + +public class SabrProtocolErrorTest { + /** + * What the server said, on one line: e.g. the player's message and the diagnostics + */ + @Test + public void keepsWhatTheServerSaid() { + SabrProtocolError error = new SabrProtocolError(SabrError.newBuilder() + .setType("sabr.malformed_config") + .setAction(2) + .setError(com.google.android.exoplayer2.source.sabr.protos.videostreaming.Error.newBuilder().setStatusCode(400)) + .build()); + + assertEquals("sabr.malformed_config", error.type); + assertEquals(2, error.action); + assertEquals(400, error.statusCode); + assertEquals("SABR Protocol Error: sabr.malformed_config, action 2, status 400", error.getMessage()); + } + + /** + * Left out by the server, it isn't made up: an action of 0 isn't one the server sent + */ + @Test + public void leavesOutWhatTheServerDidnt() { + SabrProtocolError error = new SabrProtocolError(SabrError.getDefaultInstance()); + + assertNull(error.type); + assertEquals(SabrProtocolError.UNSET, error.action); + assertEquals(SabrProtocolError.UNSET, error.statusCode); + assertEquals("SABR Protocol Error: unknown", error.getMessage()); + } + + /** + * An error without its status: the action is still told + */ + @Test + public void tellsTheActionWithoutAStatus() { + SabrProtocolError error = new SabrProtocolError(SabrError.newBuilder() + .setType("sabr.no_available_formats") + .setAction(2) + .setError(com.google.android.exoplayer2.source.sabr.protos.videostreaming.Error.getDefaultInstance()) + .build()); + + assertEquals(SabrProtocolError.UNSET, error.statusCode); + assertEquals("SABR Protocol Error: sabr.no_available_formats, action 2", error.getMessage()); + } +} diff --git a/exoplayer-amzn-2.10.6/library/sabr/src/test/java/com/google/android/exoplayer2/source/sabr/parser/misc/SabrExtractorInputTest.java b/exoplayer-amzn-2.10.6/library/sabr/src/test/java/com/google/android/exoplayer2/source/sabr/parser/misc/SabrExtractorInputTest.java new file mode 100644 index 00000000000..1e50edaf5fe --- /dev/null +++ b/exoplayer-amzn-2.10.6/library/sabr/src/test/java/com/google/android/exoplayer2/source/sabr/parser/misc/SabrExtractorInputTest.java @@ -0,0 +1,416 @@ +package com.google.android.exoplayer2.source.sabr.parser.misc; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import androidx.test.ext.junit.runners.AndroidJUnit4; + +import com.google.android.exoplayer2.C; +import com.google.android.exoplayer2.source.sabr.parser.SabrStream; +import com.google.android.exoplayer2.source.sabr.parser.exceptions.PoTokenError; +import com.google.android.exoplayer2.source.sabr.parser.exceptions.SabrProtocolError; +import com.google.android.exoplayer2.source.sabr.parser.models.VideoSelector; +import com.google.android.exoplayer2.source.sabr.parser.parts.PoTokenStatusSabrPart.PoTokenStatus; +import com.google.android.exoplayer2.source.sabr.parser.ump.UMPPartId; +import com.google.android.exoplayer2.source.sabr.protos.misc.FormatId; +import com.google.android.exoplayer2.source.sabr.protos.videostreaming.FormatInitializationMetadata; +import com.google.android.exoplayer2.source.sabr.protos.videostreaming.MediaHeader; +import com.google.android.exoplayer2.source.sabr.protos.videostreaming.SabrError; +import com.google.android.exoplayer2.source.sabr.protos.videostreaming.StreamProtectionStatus; +import com.google.android.exoplayer2.source.sabr.protos.videostreaming.StreamProtectionStatus.Status; +import com.google.android.exoplayer2.source.sabr.protos.videostreaming.StreamerContext.ClientInfo; +import com.google.android.exoplayer2.testutil.FakeExtractorInput; + +import java.io.ByteArrayOutputStream; +import java.util.Arrays; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.annotation.Config; + +@RunWith(AndroidJUnit4.class) +@Config(sdk = 28) +public class SabrExtractorInputTest { + private static final String PO_TOKEN = "dG9rZW4"; + + /** + * Attestation required with the poToken sent: the server rejected it, and won't send media past its grace period + */ + @Test + public void aRejectedPoTokenFailsTheLoad() throws Exception { + assertEquals(PoTokenStatus.INVALID, readFailure(PO_TOKEN, Status.ATTESTATION_REQUIRED).status); + } + + /** + * Attestation required with none sent: the client needs one + */ + @Test + public void aMissingPoTokenFailsTheLoad() throws Exception { + assertEquals(PoTokenStatus.MISSING, readFailure(null, Status.ATTESTATION_REQUIRED).status); + } + + /** + * A response each, pending and OK go on: the media still comes + */ + @Test + public void otherStatusesDontFailTheLoad() throws Exception { + assertEquals(C.RESULT_END_OF_INPUT, read(PO_TOKEN, Status.ATTESTATION_PENDING)); + assertEquals(C.RESULT_END_OF_INPUT, read(null, Status.ATTESTATION_PENDING)); + assertEquals(C.RESULT_END_OF_INPUT, read(PO_TOKEN, Status.OK)); + assertEquals(C.RESULT_END_OF_INPUT, read(null, Status.OK)); + } + + /** + * Past its grace period with the poToken's attestation pending, the server answers each request at once with no media: the + * player stalled at 0:59, and the same client's reload froze there (51AQC7FS, BQ0MY38T). The load fails as the media + * stops coming, a poToken sent or not. + */ + @Test + public void pendingResponsesWithoutMediaFailTheLoad() throws Exception { + SabrExtractorInput input = new SabrExtractorInput(newStream(PO_TOKEN)); + readResponse(input, statusResponse(Status.ATTESTATION_PENDING)); + readResponse(input, statusResponse(Status.ATTESTATION_PENDING)); + + assertEquals(PoTokenStatus.PENDING, readFailure(input, statusResponse(Status.ATTESTATION_PENDING)).status); + + SabrExtractorInput withoutPoToken = new SabrExtractorInput(newStream(null)); + readResponse(withoutPoToken, statusResponse(Status.ATTESTATION_PENDING)); + readResponse(withoutPoToken, statusResponse(Status.ATTESTATION_PENDING)); + + assertEquals(PoTokenStatus.PENDING_MISSING, + readFailure(withoutPoToken, statusResponse(Status.ATTESTATION_PENDING)).status); + } + + /** + * Media in between: the responses without any were for another reason (e.g. a redirect), and the count starts over + */ + @Test + public void mediaBetweenPendingResponsesKeepsTheLoadGoing() throws Exception { + SabrExtractorInput input = new SabrExtractorInput(newStream(PO_TOKEN)); + readResponse(input, statusResponse(Status.ATTESTATION_PENDING)); + readResponse(input, statusResponse(Status.ATTESTATION_PENDING)); + + assertArrayEquals(INIT_AND_MEDIA_DATA, readResponse(input, mediaResponse(Status.ATTESTATION_PENDING))); + + readResponse(input, statusResponse(Status.ATTESTATION_PENDING)); + readResponse(input, statusResponse(Status.ATTESTATION_PENDING)); + } + + /** + * A seek cancels a chunk partway through a segment, leaving the input undisposed (see ContainerMediaChunk#load), and the next + * chunk's response is read with it: from its own start, not through the cancelled response's segment. In the app the old segment + * read the new response through the chunk source's one data source, swallowing its first bytes, and its next part was read out of + * step: "Unknown part encountered" 95-786 ms after a seek in 15 of 16 cases (V9H5DRS0, AYTTSQJK, FVNAAYZD, RF6HBNNH, F8DMFX2M…). + */ + @Test + public void aResponseAfterACancelledOneIsReadFromItsStart() throws Exception { + SabrExtractorInput input = new SabrExtractorInput(newStream(PO_TOKEN)); + input.init(new FakeExtractorInput.Builder().setData(mediaResponse(Status.OK)).build()); + input.read(new byte[2], 0, 2); // into the init segment, then cancelled + + assertArrayEquals(INIT_AND_MEDIA_DATA, readResponse(input, mediaResponse(Status.OK))); + } + + /** + * An init segment isn't the media: the server sends it past the grace period too (51AQC7FS: both tracks' to the reload at 0:59) + */ + @Test + public void anInitSegmentIsntTheMedia() throws Exception { + SabrExtractorInput input = new SabrExtractorInput(newStream(PO_TOKEN)); + readResponse(input, statusResponse(Status.ATTESTATION_PENDING)); + readResponse(input, statusResponse(Status.ATTESTATION_PENDING)); + + assertEquals(PoTokenStatus.PENDING, readFailure(input, initSegmentResponse(Status.ATTESTATION_PENDING)).status); + } + + /** + * Attested, the server sends the media: a response without any is for another reason + */ + @Test + public void okResponsesWithoutMediaDontFailTheLoad() throws Exception { + SabrExtractorInput input = new SabrExtractorInput(newStream(PO_TOKEN)); + + for (int i = 0; i < 5; i++) { + readResponse(input, statusResponse(Status.OK)); + } + } + + /** + * A live stream's response has none while the segment asked for doesn't exist yet (see DefaultSabrChunkSource) + */ + @Test + public void aLiveStreamsPendingResponsesWithoutMediaDontFailTheLoad() throws Exception { + SabrStream sabrStream = newStream(PO_TOKEN); + sabrStream.setLive(true); + SabrExtractorInput input = new SabrExtractorInput(sabrStream); + + for (int i = 0; i < 5; i++) { + readResponse(input, statusResponse(Status.ATTESTATION_PENDING)); + } + } + + /** + * The init chunk's response isn't a media one: it's cut at its init segment (see theInitChunkReadsUpToItsInitSegment) + */ + @Test + public void initResponsesDontCount() throws Exception { + SabrStream sabrStream = newStream(PO_TOKEN); + sabrStream.setInitRequest(true); + SabrExtractorInput input = new SabrExtractorInput(sabrStream); + + for (int i = 0; i < 5; i++) { + readResponse(input, statusResponse(Status.ATTESTATION_PENDING)); + } + } + + /** + * Read again past its end (the extractor may), a response is still one + */ + @Test + public void aResponseReadPastItsEndIsOne() throws Exception { + SabrExtractorInput input = new SabrExtractorInput(newStream(PO_TOKEN)); + input.init(new FakeExtractorInput.Builder().setData(statusResponse(Status.ATTESTATION_PENDING)).build()); + + for (int i = 0; i < 5; i++) { + assertEquals(C.RESULT_END_OF_INPUT, input.read(new byte[1], 0, 1)); + } + + input.dispose(); + readResponse(input, statusResponse(Status.ATTESTATION_PENDING)); + + assertEquals(PoTokenStatus.PENDING, readFailure(input, statusResponse(Status.ATTESTATION_PENDING)).status); + } + + /** + * The server refused the request (e.g. its ustreamer config no longer applies): the load fails with what it said + */ + @Test + public void aSabrErrorFailsTheLoad() throws Exception { + SabrExtractorInput input = new SabrExtractorInput(newStream()); + input.init(new FakeExtractorInput.Builder().setData(sabrErrorResponse()).build()); + + try { + input.read(new byte[1], 0, 1); + fail("No SabrProtocolError"); + } catch (SabrProtocolError e) { + assertEquals("sabr.malformed_config", e.type); + assertEquals(2, e.action); + assertEquals(400, e.statusCode); + } + } + + /** + * A response that has only a SabrError, as the server sends it + */ + public static byte[] sabrErrorResponse() throws Exception { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + part(out, UMPPartId.SABR_ERROR, SabrError.newBuilder() + .setType("sabr.malformed_config") + .setAction(2) + .setError(com.google.android.exoplayer2.source.sabr.protos.videostreaming.Error.newBuilder().setStatusCode(400)) + .build().toByteArray()); + return out.toByteArray(); + } + + /** + * The init chunk's request is answered with the init segment, then a media segment: only the init segment is read, the media + * segment is left to the media chunk that asks for it + */ + @Test + public void theInitChunkReadsUpToItsInitSegment() throws Exception { + SabrStream sabrStream = newStream(); + sabrStream.setInitRequest(true); + FakeExtractorInput response = new FakeExtractorInput.Builder().setData(initResponse()).build(); + + assertArrayEquals(INIT_DATA, readAll(sabrStream, response)); + // The media segment wasn't downloaded + assertTrue(response.getPosition() < response.getLength()); + } + + /** + * A media chunk's response is read whole, an init segment in it too + */ + @Test + public void aMediaChunkReadsTheWholeResponse() throws Exception { + SabrStream sabrStream = newStream(); + sabrStream.setInitRequest(false); + FakeExtractorInput response = new FakeExtractorInput.Builder().setData(initResponse()).build(); + byte[] expected = Arrays.copyOf(INIT_DATA, INIT_DATA.length + MEDIA_DATA.length); + System.arraycopy(MEDIA_DATA, 0, expected, INIT_DATA.length, MEDIA_DATA.length); + + assertArrayEquals(expected, readAll(sabrStream, response)); + assertEquals(response.getLength(), response.getPosition()); + } + + private static final int ITAG = 315; + private static final byte[] INIT_DATA = {1, 2, 3, 4}; + private static final byte[] MEDIA_DATA = {5, 6, 7, 8, 9, 10}; + private static final byte[] INIT_AND_MEDIA_DATA = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + + private static SabrStream newStream() { + return newStream(null); + } + + private static SabrStream newStream(String poToken) { + SabrStream sabrStream = new SabrStream( + "https://rr1---sn-primary.googlevideo.com/videoplayback", "", ClientInfo.getDefaultInstance(), + -1, -1, -1, poToken, false, "test", 60_000); + sabrStream.setFormatSelector(new VideoSelector("video", false, FormatId.newBuilder().setItag(ITAG).build())); + return sabrStream; + } + + /** + * As the server sends it: the format's metadata, its init segment (header 0), then its first media segment (header 1) + */ + private static byte[] initResponse() throws Exception { + return formatResponse(true); + } + + /** + * The format's metadata and its init segment (header 0), then with the media, its first media segment (header 1) + */ + private static byte[] formatResponse(boolean withMedia) throws Exception { + FormatId formatId = FormatId.newBuilder().setItag(ITAG).build(); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + part(out, UMPPartId.FORMAT_INITIALIZATION_METADATA, FormatInitializationMetadata.newBuilder() + .setFormatId(formatId) + .setMimeType("video/webm; codecs=\"vp09.00.51.08\"") + .setEndSegmentNumber(10) + .setDurationUnits(50_000) + .setDurationTimescale(1_000) + .build().toByteArray()); + segment(out, MediaHeader.newBuilder().setHeaderId(0).setFormatId(formatId).setIsInitSeg(true) + .setContentLength(INIT_DATA.length).build(), 0, INIT_DATA); + + if (withMedia) { + segment(out, MediaHeader.newBuilder().setHeaderId(1).setFormatId(formatId).setSequenceNumber(1).setStartMs(0) + .setDurationMs(5_000).setContentLength(MEDIA_DATA.length).build(), 1, MEDIA_DATA); + } + + return out.toByteArray(); + } + + /** + * A response that has only the StreamProtectionStatus, as the server answers past the grace period + */ + private static byte[] statusResponse(Status status) throws Exception { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + part(out, UMPPartId.STREAM_PROTECTION_STATUS, StreamProtectionStatus.newBuilder().setStatus(status).build().toByteArray()); + return out.toByteArray(); + } + + /** + * The StreamProtectionStatus, the format's metadata, its init segment and its first media segment + */ + private static byte[] mediaResponse(Status status) throws Exception { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + out.write(statusResponse(status)); + out.write(formatResponse(true)); + return out.toByteArray(); + } + + /** + * The StreamProtectionStatus, the format's metadata and its init segment: no media + */ + private static byte[] initSegmentResponse(Status status) throws Exception { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + out.write(statusResponse(status)); + out.write(formatResponse(false)); + return out.toByteArray(); + } + + private static void segment(ByteArrayOutputStream out, MediaHeader header, int headerId, byte[] data) throws Exception { + part(out, UMPPartId.MEDIA_HEADER, header.toByteArray()); + byte[] media = new byte[1 + data.length]; + media[0] = (byte) headerId; + System.arraycopy(data, 0, media, 1, data.length); + part(out, UMPPartId.MEDIA, media); + part(out, UMPPartId.MEDIA_END, new byte[] {(byte) headerId}); + } + + /** + * Ids and sizes below 128: a one-byte varint each + */ + private static void part(ByteArrayOutputStream out, int partId, byte[] payload) throws Exception { + out.write(partId); + out.write(payload.length); + out.write(payload); + } + + private static byte[] readAll(SabrStream sabrStream, FakeExtractorInput response) throws Exception { + SabrExtractorInput input = new SabrExtractorInput(sabrStream); + input.init(response); + ByteArrayOutputStream result = new ByteArrayOutputStream(); + byte[] buffer = new byte[16]; + int read; + + while ((read = input.read(buffer, 0, buffer.length)) != C.RESULT_END_OF_INPUT) { + result.write(buffer, 0, read); + } + + return result.toByteArray(); + } + + /** + * As the adapters read a media chunk's response (see SabrMatroskaAdapter): to its end, then the input disposed + */ + private static byte[] readResponse(SabrExtractorInput input, byte[] response) throws Exception { + input.init(new FakeExtractorInput.Builder().setData(response).build()); + ByteArrayOutputStream result = new ByteArrayOutputStream(); + byte[] buffer = new byte[16]; + int read; + + try { + while ((read = input.read(buffer, 0, buffer.length)) != C.RESULT_END_OF_INPUT) { + result.write(buffer, 0, read); + } + } finally { + input.dispose(); + } + + return result.toByteArray(); + } + + private static PoTokenError readFailure(SabrExtractorInput input, byte[] response) throws Exception { + try { + readResponse(input, response); + } catch (PoTokenError e) { + return e; + } + + fail("No PoTokenError"); + return null; + } + + private static PoTokenError readFailure(String poToken, Status status) throws Exception { + try { + read(poToken, status); + } catch (PoTokenError e) { + return e; + } + + fail("No PoTokenError for " + status); + return null; + } + + /** + * A response that has only the StreamProtectionStatus + */ + private static int read(String poToken, Status status) throws Exception { + SabrStream sabrStream = new SabrStream( + "https://rr1---sn-primary.googlevideo.com/videoplayback", "", ClientInfo.getDefaultInstance(), + -1, -1, -1, poToken, false, "test", 60_000); + SabrExtractorInput input = new SabrExtractorInput(sabrStream); + byte[] payload = StreamProtectionStatus.newBuilder().setStatus(status).build().toByteArray(); + // Both are below 128: a one-byte varint each + byte[] response = new byte[2 + payload.length]; + response[0] = (byte) UMPPartId.STREAM_PROTECTION_STATUS; + response[1] = (byte) payload.length; + System.arraycopy(payload, 0, response, 2, payload.length); + + input.init(new FakeExtractorInput.Builder().setData(response).build()); + + return input.read(new byte[1], 0, 1); + } +} From 6f4d97d0c5ffbd0ada182df181d2fe39f67594de Mon Sep 17 00:00:00 2001 From: Yuriy Liskov Date: Mon, 30 Nov 2026 00:06:39 +0200 Subject: [PATCH 3/5] bump 32.86 --- smarttubetv/build.gradle | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/smarttubetv/build.gradle b/smarttubetv/build.gradle index b1ad8b3a60b..111bdec698c 100644 --- a/smarttubetv/build.gradle +++ b/smarttubetv/build.gradle @@ -57,8 +57,8 @@ android { applicationId "app.smarttube" minSdkVersion project.properties.minSdkVersion targetSdkVersion project.properties.targetSdkVersion - versionCode 2475 - versionName "32.85" + versionCode 2476 + versionName "32.86" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" buildConfigField "long", "TIMESTAMP", System.currentTimeMillis() + "L" From 5e31b3eb3b6166dcb7eb8d9ef65b07fd29fe957e Mon Sep 17 00:00:00 2001 From: Yuriy Liskov Date: Mon, 30 Nov 2026 00:16:38 +0200 Subject: [PATCH 4/5] fix(SABR): replace java.util.function.BooleanSupplier with own interface (API 17) --- .../android/exoplayer2/source/sabr/ValidatedNetwork.java | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/ValidatedNetwork.java b/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/ValidatedNetwork.java index 2a6c8bcefe1..80d18f8735f 100644 --- a/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/ValidatedNetwork.java +++ b/exoplayer-amzn-2.10.6/library/sabr/src/main/java/com/google/android/exoplayer2/source/sabr/ValidatedNetwork.java @@ -2,14 +2,17 @@ import androidx.annotation.Nullable; -import java.util.function.BooleanSupplier; - /** * Whether the device has a network that reaches the internet, as the app knows it (the library has no Context). With none, a * request that can't connect says nothing about its host: no other host is tried and none is marked failed, or one Wi-Fi drop * would keep the player off its media network for half an hour (see GoogleVideoHosts#markNetworkFailed). */ public final class ValidatedNetwork { + /** Replacements for java.util.function.BooleanSupplier that needs API 24 */ + public interface BooleanSupplier { + boolean getAsBoolean(); + } + private static volatile @Nullable BooleanSupplier sSupplier; private ValidatedNetwork() { @@ -20,7 +23,7 @@ public static void setSupplier(@Nullable BooleanSupplier supplier) { } /** - * True when the app didn't say (e.g. in tests): today's behaviour + * True when the app didn't say (e.g. in tests): today's behavior */ public static boolean isAvailable() { BooleanSupplier supplier = sSupplier; From a60f213fbeb5851b789d2417d77e435d3b5afceb Mon Sep 17 00:00:00 2001 From: Yuriy Liskov Date: Mon, 30 Nov 2026 00:52:41 +0200 Subject: [PATCH 5/5] fix(ErrorFixerController): skip fix on tickle if the video played less than a minute --- .../app/models/playback/controllers/ErrorFixerController.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/common/src/main/java/com/liskovsoft/smartyoutubetv2/common/app/models/playback/controllers/ErrorFixerController.java b/common/src/main/java/com/liskovsoft/smartyoutubetv2/common/app/models/playback/controllers/ErrorFixerController.java index 9c3a810fbec..65fff733305 100644 --- a/common/src/main/java/com/liskovsoft/smartyoutubetv2/common/app/models/playback/controllers/ErrorFixerController.java +++ b/common/src/main/java/com/liskovsoft/smartyoutubetv2/common/app/models/playback/controllers/ErrorFixerController.java @@ -52,7 +52,7 @@ public void onTickle() { private void handleUnthrownErrorsIfNeeded() { // Handle only those errors where the video not playing but not sign of buffering - if (getPlayer() == null || !getPlayer().getPlayWhenReady() || mBufferingDetector.isBuffering()) { + if (getPlayer() == null || getPlayer().getPositionMs() < 58_000 || !getPlayer().getPlayWhenReady() || mBufferingDetector.isBuffering()) { return; }