youpipe: start SABR implementation
- Commit
1119a085a136d33c668305603d88dcf5baf42555- Author
- Vayun Mathur <[email protected]>
- When
- 2026-07-22 20:17 UTC (4 months ago)
- Parents
74cc616
Diff
education/build.gradle.kts
diff --git a/education/build.gradle.kts b/education/build.gradle.ktsindex f1ff5f20c0..1141ad705d 100644--- a/education/build.gradle.kts+++ b/education/build.gradle.kts@@ -22,7 +22,7 @@ dependencies { implementation("androidx.compose.material:material-icons-extended") // Video playback (Khan/YouTube streaming via NewPipe + media3), like :youpipe.- implementation(libs.newpipeextractor)+ implementation(project(":youpipe:extractor")) implementation(libs.androidx.media3.exoplayer) implementation(libs.androidx.media3.ui.compose.material3) implementation(project(":library:network"))
gradle/libs.versions.toml
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.tomlindex 7a6d35109c..673f2008c5 100644--- a/gradle/libs.versions.toml+++ b/gradle/libs.versions.toml@@ -1,4 +1,12 @@ [versions]+# rhino 1.9.0 requires Android minSDK >= 26; rhino-engine only published for 1.8.x+rhino = "1.8.1"+nanojson = "e9d656ddb49a412a5a0a5d5ef20ca7ef09549996"+jsr305 = "3.0.2"+protobufJavalite = "4.35.0"+protobufPlugin = "0.10.0"+quickjs = "1.0.5"+brotli = "0.1.2" # Build & Core Language agp = "9.4.0-alpha04" # Google Play Services for RCS attestation (DroidGuard, SafetyNet, Firebase IID)@@ -27,7 +35,6 @@ coreKtx = "1.19.0" kotlinxCoroutines = "1.11.0" lifecycle = "2.11.0" litertlmAndroid = "0.14.0"-newpipeextractor = "v0.26.3" sqlcipherAndroid = "4.17.0" sqlite = "2.7.0" workRuntimeKtx = "2.11.2"@@ -106,6 +113,14 @@ androidx-camera-compose = { group = "androidx.camera", name = "camera-compose", androidx-webkit = { group = "androidx.webkit", name = "webkit", version.ref = "webkit" } geckoview = { module = "org.mozilla.geckoview:geckoview-arm64-v8a", version.ref = "geckoview" } jsoup = { module = "org.jsoup:jsoup", version.ref = "jsoup" }+rhino = { module = "org.mozilla:rhino", version.ref = "rhino" }+rhino-engine = { module = "org.mozilla:rhino-engine", version.ref = "rhino" }+newpipe-nanojson = { module = "com.github.TeamNewPipe:nanojson", version.ref = "nanojson" }+google-jsr305 = { module = "com.google.code.findbugs:jsr305", version.ref = "jsr305" }+protobuf-javalite = { module = "com.google.protobuf:protobuf-javalite", version.ref = "protobufJavalite" }+quickjs-kt = { module = "io.github.dokar3:quickjs-kt", version.ref = "quickjs" }+brotli-dec = { module = "org.brotli:dec", version.ref = "brotli" }+javax-annotation-api = { module = "javax.annotation:javax.annotation-api", version = "1.3.2" } # Instrumented screenshot tests (metadata generation) junit = { module = "junit:junit", version.ref = "junit" }@@ -132,6 +147,7 @@ androidx-compose-material3-adaptive-navigation-suite = { group = "androidx.compo # Media3 (ExoPlayer & Session) androidx-media3-exoplayer = { module = "androidx.media3:media3-exoplayer", version.ref = "media3Exoplayer" }+androidx-media3-exoplayer-dash = { module = "androidx.media3:media3-exoplayer-dash", version.ref = "media3Exoplayer" } androidx-media3-session = { module = "androidx.media3:media3-session", version.ref = "media3Exoplayer" } androidx-media3-ui-compose-material3 = { module = "androidx.media3:media3-ui-compose-material3", version.ref = "media3Exoplayer" } androidx-media3-datasource-okhttp = { group = "androidx.media3", name = "media3-datasource-okhttp", version.ref = "media3Exoplayer" }@@ -145,7 +161,6 @@ flatgeobuf = { module = "org.wololo:flatgeobuf", version.ref = "flatgeobuf" } kotlin-gradle-plugin = { module = "org.jetbrains.kotlin:kotlin-gradle-plugin", version.ref = "kotlinGradlePlugin" } litertlm-android = { module = "com.google.ai.edge.litertlm:litertlm-android", version.ref = "litertlmAndroid" } kotlinx-coroutines-android = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-android", version.ref = "kotlinxCoroutines" }-newpipeextractor = { module = "com.github.TeamNewPipe:NewPipeExtractor", version.ref = "newpipeextractor" } reorderable = { module = "sh.calvin.reorderable:reorderable", version.ref = "reorderable" } # Maps@@ -167,6 +182,7 @@ androidx-glance-material3 = { module = "androidx.glance:glance-material3", versi ktor-client-core = { group = "io.ktor", name = "ktor-client-core", version.ref = "ktor" } ktor-client-cio = { group = "io.ktor", name = "ktor-client-cio", version.ref = "ktor" } ktor-client-websockets = { group = "io.ktor", name = "ktor-client-websockets", version.ref = "ktor" }+ktor-client-okhttp = { group = "io.ktor", name = "ktor-client-okhttp", version.ref = "ktor" } ktor-client-content-negotiation = { group = "io.ktor", name = "ktor-client-content-negotiation", version.ref = "ktor" } ktor-serialization-kotlinx-json = { group = "io.ktor", name = "ktor-serialization-kotlinx-json", version.ref = "ktor" } okio = { group = "com.squareup.okio", name = "okio", version.ref = "okio" }@@ -231,3 +247,4 @@ android-library = { id = "com.android.library", version.ref = "agp" } kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" } kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" } ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" }+protobuf = { id = "com.google.protobuf", version.ref = "protobufPlugin" }
library/network/build.gradle.kts
diff --git a/library/network/build.gradle.kts b/library/network/build.gradle.ktsindex 41f3bb4e3d..78b445eb19 100644--- a/library/network/build.gradle.kts+++ b/library/network/build.gradle.kts@@ -3,7 +3,7 @@ plugins { } dependencies {- implementation(libs.ktor.client.cio)+ implementation(libs.ktor.client.okhttp) implementation(libs.ktor.client.core) implementation(libs.ktor.client.content.negotiation) implementation(libs.ktor.serialization.kotlinx.json)
library/network/src/main/java/com/vayunmathur/library/network/NetworkClient.kt
diff --git a/library/network/src/main/java/com/vayunmathur/library/network/NetworkClient.kt b/library/network/src/main/java/com/vayunmathur/library/network/NetworkClient.ktindex 82ba413330..0f3df31a2e 100644--- a/library/network/src/main/java/com/vayunmathur/library/network/NetworkClient.kt+++ b/library/network/src/main/java/com/vayunmathur/library/network/NetworkClient.kt@@ -2,7 +2,7 @@ package com.vayunmathur.library.network import io.ktor.client.HttpClient import io.ktor.client.call.body-import io.ktor.client.engine.cio.CIO+import io.ktor.client.engine.okhttp.OkHttp import io.ktor.client.plugins.HttpTimeout import io.ktor.client.plugins.contentnegotiation.ContentNegotiation import io.ktor.client.request.HttpRequestBuilder@@ -44,7 +44,7 @@ object NetworkClient { isLenient = true } - val client = HttpClient(CIO) {+ val client = HttpClient(OkHttp) { install(HttpTimeout) { requestTimeoutMillis = 60_000 connectTimeoutMillis = 30_000@@ -88,6 +88,25 @@ object NetworkClient { return response.status.value to response.body<ByteArray>() } + /**+ * Like [performRequestBytes] but also returns the response headers. Used by SABR streaming,+ * which needs the raw (binary-safe) body plus headers (e.g. Content-Type) in one request.+ */+ suspend fun performRequestBytesFull(+ url: String,+ method: String = "GET",+ headers: Map<String, *> = emptyMap<String, Any>(),+ body: Any? = null+ ): Triple<Int, Map<String, List<String>>, ByteArray> {+ val response: HttpResponse = client.request(url) {+ this.method = HttpMethod.parse(method)+ applyHeaders(headers)+ body?.let { setBody(it) }+ }+ val respHeaders = response.headers.entries().associate { it.key to it.value }+ return Triple(response.status.value, respHeaders, response.body<ByteArray>())+ }+ suspend fun performRequest( url: String, method: String = "GET",
youpipe/build.gradle.kts
diff --git a/youpipe/build.gradle.kts b/youpipe/build.gradle.ktsindex 6871e86510..aa3cbe1ec7 100644--- a/youpipe/build.gradle.kts+++ b/youpipe/build.gradle.kts@@ -26,12 +26,17 @@ android { dependencies { implementation(libs.coil.compose) implementation(project(":youpipe:extractor"))+ implementation(libs.quickjs.kt)+ implementation(libs.newpipe.nanojson)+ implementation(libs.androidx.webkit)+ implementation(project(":youpipe:ffmpeg")) implementRoom(libs) implementation(project(":library:room")) implementation(libs.androidx.media3.ui.compose.material3) implementation(libs.androidx.media3.exoplayer)+ implementation(libs.androidx.media3.exoplayer.dash) implementation(libs.androidx.media3.session) implementation(libs.androidx.media3.datasource.okhttp)
youpipe/extractor/build.gradle.kts
diff --git a/youpipe/extractor/build.gradle.kts b/youpipe/extractor/build.gradle.ktsindex c365dd85df..850dc92c7b 100644--- a/youpipe/extractor/build.gradle.kts+++ b/youpipe/extractor/build.gradle.kts@@ -24,6 +24,8 @@ dependencies { implementation(libs.protobuf.javalite) implementation(libs.rhino) implementation(libs.rhino.engine)+ implementation(libs.bouncycastle)+ implementation(libs.brotli.dec) } protobuf {
youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/NewPipe.java
diff --git a/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/NewPipe.java b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/NewPipe.javaindex 77fe1667a8..9f43509e1f 100644--- a/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/NewPipe.java+++ b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/NewPipe.java@@ -24,6 +24,7 @@ import org.schabi.newpipe.extractor.downloader.Downloader; import org.schabi.newpipe.extractor.exceptions.ExtractionException; import org.schabi.newpipe.extractor.localization.ContentCountry; import org.schabi.newpipe.extractor.localization.Localization;+import org.schabi.newpipe.extractor.services.youtube.YoutubeSessionPoTokenProvider; import org.schabi.newpipe.extractor.utils.ExtractorLogger; import java.util.List;@@ -39,6 +40,8 @@ public final class NewPipe { private static Downloader downloader; private static Localization preferredLocalization; private static ContentCountry preferredContentCountry;+ @Nullable+ private static YoutubeSessionPoTokenProvider youtubeSessionPoTokenProvider; private NewPipe() { }@@ -66,6 +69,20 @@ public final class NewPipe { return downloader; } + /*//////////////////////////////////////////////////////////////////////////+ // YouTube SABR session PoToken SPI+ //////////////////////////////////////////////////////////////////////////*/++ public static void setYoutubeSessionPoTokenProvider(+ @Nullable final YoutubeSessionPoTokenProvider provider) {+ youtubeSessionPoTokenProvider = provider;+ }++ @Nullable+ public static YoutubeSessionPoTokenProvider getYoutubeSessionPoTokenProvider() {+ return youtubeSessionPoTokenProvider;+ }+ /*////////////////////////////////////////////////////////////////////////// // Utils //////////////////////////////////////////////////////////////////////////*/
youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/downloader/Downloader.java
diff --git a/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/downloader/Downloader.java b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/downloader/Downloader.javaindex 218848d0ac..3531b065b2 100644--- a/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/downloader/Downloader.java+++ b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/downloader/Downloader.java@@ -6,6 +6,7 @@ import org.schabi.newpipe.extractor.localization.Localization; import javax.annotation.Nonnull; import javax.annotation.Nullable;+import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.Collections; import java.util.HashMap;@@ -244,6 +245,50 @@ public abstract class Downloader { public abstract Response execute(@Nonnull Request request) throws IOException, ReCaptchaException; + /**+ * Do a streaming GET request: the response body is exposed as an {@link java.io.InputStream}+ * instead of a buffered {@code byte[]}, so large SABR media batches are not held whole in+ * memory. The compatibility default buffers the whole response; implementations backed by a+ * real streaming HTTP client should override this to return the connection's body stream.+ */+ public StreamingResponse getStreaming(final String url,+ @Nullable final Map<String, List<String>> headers,+ @Nullable final Localization localization)+ throws IOException, ReCaptchaException {+ final Response response = get(url, headers, localization);+ final byte[] raw = response.responseBody() == null+ ? new byte[0] : response.responseBody().getBytes(java.nio.charset.StandardCharsets.ISO_8859_1);+ return new StreamingResponse(response.responseCode(), response.responseHeaders(),+ new ByteArrayInputStream(raw));+ }++ /**+ * Streaming GET with a caller-supplied deadline. Implementations that support per-call+ * timeouts should override this; the compatibility default preserves the regular behavior.+ */+ public StreamingResponse getStreaming(final String url,+ @Nullable final Map<String, List<String>> headers,+ @Nullable final Localization localization,+ final long timeoutMs)+ throws IOException, ReCaptchaException {+ return getStreaming(url, headers, localization);+ }++ /**+ * Do a streaming POST request. See {@link #getStreaming(String, Map, Localization)}.+ */+ public StreamingResponse postStreaming(final String url,+ @Nullable final Map<String, List<String>> headers,+ @Nullable final byte[] dataToSend,+ @Nullable final Localization localization)+ throws IOException, ReCaptchaException {+ final Response response = post(url, headers, dataToSend, localization);+ final byte[] raw = response.responseBody() == null+ ? new byte[0] : response.responseBody().getBytes(java.nio.charset.StandardCharsets.ISO_8859_1);+ return new StreamingResponse(response.responseCode(), response.responseHeaders(),+ new ByteArrayInputStream(raw));+ }+ @Override public String toString() { return getClass().getSimpleName();
youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/downloader/StreamingResponse.java
diff --git a/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/downloader/StreamingResponse.java b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/downloader/StreamingResponse.javanew file mode 100644index 0000000000..2c711629a8--- /dev/null+++ b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/downloader/StreamingResponse.java@@ -0,0 +1,57 @@+package org.schabi.newpipe.extractor.downloader;++import javax.annotation.Nonnull;+import javax.annotation.Nullable;+import java.io.Closeable;+import java.io.IOException;+import java.io.InputStream;+import java.util.Collections;+import java.util.List;+import java.util.Map;++/**+ * A streaming HTTP response: the body is exposed as an {@link InputStream} instead of a buffered+ * {@code byte[]}, so a large response (e.g. a SABR media batch, which can be 50-150MB at 4K) is not+ * held whole in memory. The caller MUST {@link #close()} it to release the underlying connection.+ */+public class StreamingResponse implements Closeable {+ private final int responseCode;+ @Nonnull+ private final Map<String, List<String>> responseHeaders;+ @Nonnull+ private final InputStream body;++ public StreamingResponse(final int responseCode,+ @Nullable final Map<String, List<String>> responseHeaders,+ @Nonnull final InputStream body) {+ this.responseCode = responseCode;+ this.responseHeaders = responseHeaders == null ? Collections.emptyMap() : responseHeaders;+ this.body = body;+ }++ public int responseCode() {+ return responseCode;+ }++ @Nonnull+ public InputStream body() {+ return body;+ }++ /** First value for a header name (case-insensitive), or {@code null}. */+ @Nullable+ public String getHeader(final String name) {+ for (final Map.Entry<String, List<String>> entry : responseHeaders.entrySet()) {+ final String key = entry.getKey();+ if (key != null && key.equalsIgnoreCase(name) && !entry.getValue().isEmpty()) {+ return entry.getValue().get(0);+ }+ }+ return null;+ }++ @Override+ public void close() throws IOException {+ body.close();+ }+}
youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/YoutubeApiDecoder.java
diff --git a/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/YoutubeApiDecoder.java b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/YoutubeApiDecoder.javanew file mode 100644index 0000000000..2abdb57a39--- /dev/null+++ b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/YoutubeApiDecoder.java@@ -0,0 +1,43 @@+package org.schabi.newpipe.extractor.services.youtube;++import java.util.Map;++import javax.annotation.Nonnull;++/**+ * Holder for batch signature / n-parameter decoding results.+ *+ * <p>PipePipe's upstream {@code YoutubeApiDecoder} routes decoding through a remote API; this fork+ * instead performs local decoding via {@link YoutubeJavaScriptPlayerManager#deobfuscateBatch}. Only+ * the {@link BatchDecodeResult} value type is kept so the {@code sabr} package can consume decoded+ * values by the same type name.</p>+ */+public final class YoutubeApiDecoder {++ private YoutubeApiDecoder() {+ }++ /**+ * Result class for batch decode operations: maps of obfuscated value to decoded value.+ */+ public static final class BatchDecodeResult {+ private final Map<String, String> signatures;+ private final Map<String, String> nParameters;++ public BatchDecodeResult(@Nonnull final Map<String, String> signatures,+ @Nonnull final Map<String, String> nParameters) {+ this.signatures = signatures;+ this.nParameters = nParameters;+ }++ @Nonnull+ public Map<String, String> getSignatures() {+ return signatures;+ }++ @Nonnull+ public Map<String, String> getNParameters() {+ return nParameters;+ }+ }+}
youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/YoutubeJavaScriptPlayerManager.java
diff --git a/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/YoutubeJavaScriptPlayerManager.java b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/YoutubeJavaScriptPlayerManager.javaindex b080eb0bdf..df054e7544 100644--- a/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/YoutubeJavaScriptPlayerManager.java+++ b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/YoutubeJavaScriptPlayerManager.java@@ -8,6 +8,7 @@ import org.schabi.newpipe.extractor.utils.JavaScript; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.HashMap;+import java.util.List; import java.util.Map; import java.util.Objects; @@ -282,6 +283,98 @@ public final class YoutubeJavaScriptPlayerManager { } } + /**+ * Batch-deobfuscate a set of signatures and raw throttling ({@code n}) parameters in one call,+ * returning a {@link YoutubeApiDecoder.BatchDecodeResult}.+ *+ * <p>This is the local-decoding equivalent of PipePipe's remote batch decoder: it reuses this+ * fork's per-item rhino-based decoding ({@link #deobfuscateSignature} and the throttling+ * function) so the {@code sabr} package can resolve SABR initialization URLs.</p>+ *+ * @param videoId the video ID used to fetch the base JavaScript player+ * @param signatures obfuscated signatures to decode (nullable/empty allowed)+ * @param throttlingParams raw obfuscated {@code n} parameters to decode (nullable/empty allowed)+ * @return a result mapping each obfuscated value to its decoded value+ * @throws ParsingException if decoding fails+ */+ @Nonnull+ public static YoutubeApiDecoder.BatchDecodeResult deobfuscateBatch(+ @Nonnull final String videoId,+ @Nullable final List<String> signatures,+ @Nullable final List<String> throttlingParams) throws ParsingException {+ final Map<String, String> sigResults = new HashMap<>();+ final Map<String, String> nResults = new HashMap<>();+ if (signatures != null) {+ for (final String sig : signatures) {+ if (sig != null && !sig.isEmpty() && !sigResults.containsKey(sig)) {+ sigResults.put(sig, deobfuscateSignature(videoId, sig));+ }+ }+ }+ if (throttlingParams != null) {+ for (final String n : throttlingParams) {+ if (n != null && !n.isEmpty() && !nResults.containsKey(n)) {+ nResults.put(n, deobfuscateThrottlingParameterRaw(videoId, n));+ }+ }+ }+ return new YoutubeApiDecoder.BatchDecodeResult(sigResults, nResults);+ }++ /**+ * Deobfuscate a raw throttling ({@code n}) parameter (not embedded in a URL) using the base+ * JavaScript player's throttling function, caching the result.+ */+ @Nonnull+ private static String deobfuscateThrottlingParameterRaw(+ @Nonnull final String videoId,+ @Nonnull final String obfuscatedThrottlingParameter) throws ParsingException {+ final String cacheResult = CACHED_THROTTLING_PARAMETERS.get(obfuscatedThrottlingParameter);+ if (cacheResult != null) {+ return cacheResult;+ }++ extractJavaScriptCodeIfNeeded(videoId);++ if (throttlingDeobfFuncExtractionEx != null) {+ throw throttlingDeobfFuncExtractionEx;+ }++ if (cachedThrottlingDeobfuscationFunction == null) {+ try {+ cachedThrottlingDeobfuscationFunctionName =+ YoutubeThrottlingParameterUtils.getDeobfuscationFunctionName(+ cachedJavaScriptPlayerCode);+ cachedThrottlingDeobfuscationFunction =+ YoutubeThrottlingParameterUtils.getDeobfuscationFunction(+ cachedJavaScriptPlayerCode,+ cachedThrottlingDeobfuscationFunctionName);+ } catch (final ParsingException e) {+ throttlingDeobfFuncExtractionEx = e;+ throw e;+ } catch (final Exception e) {+ throttlingDeobfFuncExtractionEx = new ParsingException(+ "Could not get throttling parameter deobfuscation JavaScript function", e);+ throw e;+ }+ }++ try {+ final String deobfuscated = JavaScript.run(+ cachedThrottlingDeobfuscationFunction,+ cachedThrottlingDeobfuscationFunctionName,+ obfuscatedThrottlingParameter);+ if (isNullOrEmpty(deobfuscated)) {+ throw new IllegalStateException("Extracted n-parameter is empty");+ }+ CACHED_THROTTLING_PARAMETERS.put(obfuscatedThrottlingParameter, deobfuscated);+ return deobfuscated;+ } catch (final Exception e) {+ throw new ParsingException(+ "Could not run throttling parameter deobfuscation JavaScript function", e);+ }+ }+ /** * Get the current cache size of throttling parameters. *
youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/YoutubeParsingHelper.java
diff --git a/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/YoutubeParsingHelper.java b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/YoutubeParsingHelper.javaindex f8a00f9652..c209607db6 100644--- a/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/YoutubeParsingHelper.java+++ b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/YoutubeParsingHelper.java@@ -1207,6 +1207,50 @@ public final class YoutubeParsingHelper { return Map.of("Cookie", List.of(generateConsentCookie())); } + /**+ * Add the YouTube consent cookie to an existing mutable headers map (used by SABR requests).+ */+ public static void addCookieHeader(@Nonnull final Map<String, List<String>> headers) {+ if (headers.get("Cookie") == null) {+ headers.put("Cookie", new java.util.ArrayList<>(List.of(generateConsentCookie())));+ } else {+ headers.get("Cookie").add(generateConsentCookie());+ }+ }++ /**+ * Add logged-in (cookie/authorization) headers for SABR requests. This fork does not support+ * an authenticated YouTube session, so this is a no-op kept for API compatibility with the+ * ported {@code sabr} package.+ */+ public static void addLoggedInHeaders(@Nonnull final Map<String, List<String>> headers) {+ // No authenticated session in this fork.+ }++ /**+ * Obtain a session-bound PO token via the configured+ * {@link org.schabi.newpipe.extractor.services.youtube.YoutubeSessionPoTokenProvider}, or+ * {@code null} if none is configured or minting fails.+ */+ @javax.annotation.Nullable+ public static YoutubeSessionPoToken getSessionPoToken(+ @Nonnull final String clientName,+ @Nonnull final Localization localization,+ @Nonnull final ContentCountry contentCountry) {+ final YoutubeSessionPoTokenProvider provider =+ org.schabi.newpipe.extractor.NewPipe.getYoutubeSessionPoTokenProvider();+ if (provider == null) {+ return null;+ }+ try {+ return provider.getSessionPoToken(clientName, localization, contentCountry, false);+ } catch (final Exception error) {+ System.err.println("Could not obtain session-bound YouTube PO token: "+ + error.getClass().getSimpleName() + ": " + error.getMessage());+ return null;+ }+ }+ @Nonnull public static String generateConsentCookie() { return "SOCS=" + (isConsentAccepted()
youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/YoutubeSessionPoToken.java
diff --git a/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/YoutubeSessionPoToken.java b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/YoutubeSessionPoToken.javanew file mode 100644index 0000000000..f3706625c4--- /dev/null+++ b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/YoutubeSessionPoToken.java@@ -0,0 +1,31 @@+package org.schabi.newpipe.extractor.services.youtube;++import java.util.Objects;++import javax.annotation.Nonnull;++/**+ * A session-bound proof-of-origin token and the visitor data it is bound to.+ */+public final class YoutubeSessionPoToken {+ @Nonnull+ private final String visitorData;+ @Nonnull+ private final String poToken;++ public YoutubeSessionPoToken(@Nonnull final String visitorData,+ @Nonnull final String poToken) {+ this.visitorData = Objects.requireNonNull(visitorData);+ this.poToken = Objects.requireNonNull(poToken);+ }++ @Nonnull+ public String getVisitorData() {+ return visitorData;+ }++ @Nonnull+ public String getPoToken() {+ return poToken;+ }+}
youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/YoutubeSessionPoTokenProvider.java
diff --git a/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/YoutubeSessionPoTokenProvider.java b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/YoutubeSessionPoTokenProvider.javanew file mode 100644index 0000000000..716f1dbe63--- /dev/null+++ b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/YoutubeSessionPoTokenProvider.java@@ -0,0 +1,26 @@+package org.schabi.newpipe.extractor.services.youtube;++import org.schabi.newpipe.extractor.exceptions.ExtractionException;+import org.schabi.newpipe.extractor.localization.ContentCountry;+import org.schabi.newpipe.extractor.localization.Localization;++import java.io.IOException;++import javax.annotation.Nonnull;+import javax.annotation.Nullable;++/**+ * Supplies the visitor-bound token used by YouTube {@code /player} requests.+ *+ * <p>Implementations must be thread-safe. Returning {@code null} lets extraction continue without+ * a token, which is required as a compatibility fallback when the local attestation runtime is not+ * available.</p>+ */+public interface YoutubeSessionPoTokenProvider {+ @Nullable+ YoutubeSessionPoToken getSessionPoToken(@Nonnull String clientName,+ @Nonnull Localization localization,+ @Nonnull ContentCountry contentCountry,+ boolean loggedIn)+ throws IOException, ExtractionException;+}
youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/extractors/YoutubeStreamExtractor.java
diff --git a/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/extractors/YoutubeStreamExtractor.java b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/extractors/YoutubeStreamExtractor.javaindex 966568fce8..8e1ce1d0c4 100644--- a/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/extractors/YoutubeStreamExtractor.java+++ b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/extractors/YoutubeStreamExtractor.java@@ -68,6 +68,9 @@ import org.schabi.newpipe.extractor.services.youtube.YoutubeJavaScriptPlayerMana import org.schabi.newpipe.extractor.services.youtube.YoutubeMetaInfoHelper; import org.schabi.newpipe.extractor.services.youtube.YoutubeParsingHelper; import org.schabi.newpipe.extractor.services.youtube.YoutubeStreamHelper;+import org.schabi.newpipe.extractor.services.youtube.sabr.YoutubeSabrClientProfile;+import org.schabi.newpipe.extractor.services.youtube.sabr.YoutubeSabrInfo;+import org.schabi.newpipe.extractor.services.youtube.sabr.YoutubeSabrProbe; import org.schabi.newpipe.extractor.services.youtube.linkHandler.YoutubeChannelLinkHandlerFactory; import org.schabi.newpipe.extractor.stream.AudioStream; import org.schabi.newpipe.extractor.stream.DeliveryMethod;@@ -93,6 +96,7 @@ import java.time.format.DateTimeParseException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections;+import java.util.Comparator; import java.util.List; import java.util.Locale; import java.util.Objects;@@ -155,6 +159,14 @@ public class YoutubeStreamExtractor extends StreamExtractor { @Nullable private String iosStreamingUrlsPoToken; + // SABR (Server Adaptive BitRate) session-based streams, built lazily from the ANDROID player+ // response when it carries a serverAbrStreamingUrl.+ private boolean sabrStreamsBuilt;+ @Nonnull+ private final List<AudioStream> sabrAudioStreams = new ArrayList<>();+ @Nonnull+ private final List<VideoStream> sabrVideoOnlyStreams = new ArrayList<>();+ public YoutubeStreamExtractor(final StreamingService service, final LinkHandler linkHandler) { super(service, linkHandler); }@@ -682,8 +694,11 @@ public class YoutubeStreamExtractor extends StreamExtractor { @Override public List<AudioStream> getAudioStreams() throws ExtractionException { assertPageFetched();- return getItags(ADAPTIVE_FORMATS, ItagItem.ItagType.AUDIO,+ final List<AudioStream> streams = getItags(ADAPTIVE_FORMATS, ItagItem.ItagType.AUDIO, getAudioStreamBuilderHelper(), "audio");+ buildSabrStreamsIfNeeded();+ streams.addAll(sabrAudioStreams);+ return streams; } @Override@@ -696,8 +711,11 @@ public class YoutubeStreamExtractor extends StreamExtractor { @Override public List<VideoStream> getVideoOnlyStreams() throws ExtractionException { assertPageFetched();- return getItags(ADAPTIVE_FORMATS, ItagItem.ItagType.VIDEO_ONLY,+ final List<VideoStream> streams = getItags(ADAPTIVE_FORMATS, ItagItem.ItagType.VIDEO_ONLY, getVideoStreamBuilderHelper(true), "video-only");+ buildSabrStreamsIfNeeded();+ streams.addAll(sabrVideoOnlyStreams);+ return streams; } @Override@@ -1124,6 +1142,156 @@ public class YoutubeStreamExtractor extends StreamExtractor { } @Nonnull+ private boolean hasSabrStreamingUrl() {+ if (playerResponse == null) {+ return false;+ }+ final JsonObject streamingData = playerResponse.getObject(STREAMING_DATA);+ return streamingData != null+ && !streamingData.getString("serverAbrStreamingUrl", "").isEmpty();+ }++ @Nullable+ private YoutubeSabrInfo buildSabrInfo(@Nonnull final String videoId) {+ if (playerResponse == null) {+ return null;+ }+ try {+ return YoutubeSabrProbe.fromPlayerResponse(videoId,+ YoutubeSabrClientProfile.ANDROID,+ androidCpn == null ? generateContentPlaybackNonce() : androidCpn,+ playerResponse, null);+ } catch (final Exception e) {+ return null;+ }+ }++ /**+ * Build the SABR audio and video-only streams once, from the ANDROID player response's+ * {@code adaptiveFormats}. Each stream uses {@link DeliveryMethod#SABR}, has {@code isUrl=false}+ * (its content is the serverAbrStreamingUrl, for reference only), and carries the shared+ * {@link YoutubeSabrInfo} as its delivery-method info so the client can drive a session.+ */+ private void buildSabrStreamsIfNeeded() {+ if (sabrStreamsBuilt) {+ return;+ }+ sabrStreamsBuilt = true;+ if (!hasSabrStreamingUrl()) {+ return;+ }+ final String videoId;+ try {+ videoId = getId();+ } catch (final Exception e) {+ return;+ }+ final YoutubeSabrInfo sabrInfo = buildSabrInfo(videoId);+ if (sabrInfo == null) {+ return;+ }+ final JsonObject streamingData = playerResponse.getObject(STREAMING_DATA);+ final String serverAbrStreamingUrl =+ streamingData.getString("serverAbrStreamingUrl", "");+ final JsonArray adaptiveFormats = streamingData.getArray(ADAPTIVE_FORMATS);+ if (adaptiveFormats == null) {+ return;+ }++ for (int i = 0; i < adaptiveFormats.size(); i++) {+ final JsonObject formatData = adaptiveFormats.getObject(i);+ try {+ final ItagItem itagItem = ItagItem.getItag(formatData.getInt("itag"));+ fillSabrItagItem(itagItem, formatData);+ final String id = String.valueOf(itagItem.id);++ if (itagItem.itagType == ItagItem.ItagType.AUDIO) {+ final AudioStream.Builder builder = new AudioStream.Builder()+ .setContent(serverAbrStreamingUrl, false)+ .setMediaFormat(itagItem.getMediaFormat())+ .setAverageBitrate(itagItem.getAverageBitrate())+ .setItagItem(itagItem)+ .setDeliveryMethod(DeliveryMethod.SABR)+ .setDeliveryMethodInfo(sabrInfo);+ String streamId = id;+ if (formatData.has("audioTrack")) {+ final JsonObject audioTrack = formatData.getObject("audioTrack");+ if (audioTrack.has("id")) {+ final String trackId = audioTrack.getString("id");+ final String displayName = audioTrack.getString("displayName");+ final String langPart = trackId.split("\\.")[0];+ builder.setAudioTrackId(trackId)+ .setAudioTrackName(displayName != null ? displayName : langPart)+ .setAudioLocale(new Locale(langPart.split("-")[0]));+ streamId = id + "-" + trackId;+ }+ }+ final String audioStreamId = streamId;+ final AudioStream stream = builder.setId(audioStreamId).build();+ if (sabrAudioStreams.stream()+ .noneMatch(s -> audioStreamId.equals(s.getId()))) {+ sabrAudioStreams.add(stream);+ }+ } else if (itagItem.itagType == ItagItem.ItagType.VIDEO_ONLY) {+ final String resolution = itagItem.getResolutionString();+ final VideoStream stream = new VideoStream.Builder()+ .setId(id)+ .setContent(serverAbrStreamingUrl, false)+ .setMediaFormat(itagItem.getMediaFormat())+ .setIsVideoOnly(true)+ .setItagItem(itagItem)+ .setResolution(resolution != null ? resolution : "")+ .setDeliveryMethod(DeliveryMethod.SABR)+ .setDeliveryMethodInfo(sabrInfo)+ .build();+ if (sabrVideoOnlyStreams.stream().noneMatch(s -> id.equals(s.getId()))) {+ sabrVideoOnlyStreams.add(stream);+ }+ }+ } catch (final Exception e) {+ // Skip unknown itags or malformed formats; do not fail the whole extraction.+ }+ }++ sabrAudioStreams.sort(Comparator.comparingInt(AudioStream::getAverageBitrate).reversed());+ }++ private static void fillSabrItagItem(@Nonnull final ItagItem itagItem,+ @Nonnull final JsonObject formatData) {+ final String mimeType = formatData.getString("mimeType", "");+ final String codec = mimeType.contains("codecs") ? mimeType.split("\"")[1] : "";++ itagItem.setBitrate(formatData.getInt("bitrate"));+ itagItem.setWidth(formatData.getInt("width"));+ itagItem.setHeight(formatData.getInt("height"));+ if (formatData.has("initRange")) {+ final JsonObject initRange = formatData.getObject("initRange");+ itagItem.setInitStart(Integer.parseInt(initRange.getString("start", "-1")));+ itagItem.setInitEnd(Integer.parseInt(initRange.getString("end", "-1")));+ }+ if (formatData.has("indexRange")) {+ final JsonObject indexRange = formatData.getObject("indexRange");+ itagItem.setIndexStart(Integer.parseInt(indexRange.getString("start", "-1")));+ itagItem.setIndexEnd(Integer.parseInt(indexRange.getString("end", "-1")));+ }+ itagItem.setQuality(formatData.getString("quality"));+ itagItem.setCodec(codec);+ final int fps = formatData.getInt("fps", -1);+ if (fps != -1) {+ itagItem.setFps(fps);+ }+ if (itagItem.itagType == ItagItem.ItagType.AUDIO) {+ if (formatData.has("audioSampleRate")) {+ itagItem.setSampleRate(Integer.parseInt(formatData.getString("audioSampleRate")));+ }+ itagItem.setAudioChannels(formatData.getInt("audioChannels", 2));+ }+ itagItem.setContentLength(Long.parseLong(formatData.getString("contentLength",+ String.valueOf(ItagItem.CONTENT_LENGTH_UNKNOWN))));+ itagItem.setApproxDurationMs(Long.parseLong(formatData.getString("approxDurationMs",+ String.valueOf(ItagItem.APPROX_DURATION_MS_UNKNOWN))));+ }+ private <T extends Stream> List<T> getItags( final String streamingDataKey, final ItagItem.ItagType itagTypeWanted,
youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/sabr/BuiltinSabrSessionPolicy.java
diff --git a/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/sabr/BuiltinSabrSessionPolicy.java b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/sabr/BuiltinSabrSessionPolicy.javanew file mode 100644index 0000000000..96ffbae734--- /dev/null+++ b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/sabr/BuiltinSabrSessionPolicy.java@@ -0,0 +1,60 @@+package org.schabi.newpipe.extractor.services.youtube.sabr;++import javax.annotation.Nonnull;+import java.util.ArrayList;+import java.util.List;++/** Bundled protocol behavior used when no verified JavaScript policy is active. */+public final class BuiltinSabrSessionPolicy implements SabrSessionPolicy {+ @Nonnull+ @Override+ public Result evaluate(@Nonnull final State state, @Nonnull final Event event) {+ if (event instanceof RequestEvent) {+ return Result.request(state, state.getRequestNumber() == 0+ ? ActionType.SEND_INITIAL_REQUEST : ActionType.SEND_FOLLOW_UP_REQUEST,+ ((RequestEvent) event).getProposedBody());+ }+ final ControlResponseEvent control = (ControlResponseEvent) event;+ final SabrDecodedResponse response = control.getResponse();+ final List<Action> actions = new ArrayList<>();+ State next = state;+ actions.add(new Action(ActionType.APPLY_RESPONSE_STATE));+ final String redirectUrl = response.getRedirectUrl();+ if (redirectUrl != null && !redirectUrl.isEmpty()) {+ actions.add(new Action(ActionType.APPLY_REDIRECT));+ next = new State(state.getRequestNumber(), state.getRedirectCount() + 1,+ state.getPoTokenRefreshes(), state.getReloads());+ }+ if (response.getSabrErrorDetails() != null) {+ actions.add(new Action(ActionType.FAIL_SABR_ERROR));+ return Result.control(next, actions, new ControlDecision(0, redirectUrl,+ response.getSabrErrorDetails().summarize()),+ SabrResponseStatePatch.builtin(response));+ }+ if (response.isReloadRequested()) {+ actions.add(new Action(ActionType.TRY_RELOAD));+ return Result.control(next, actions, new ControlDecision(0, redirectUrl, null),+ SabrResponseStatePatch.builtin(response));+ }+ if (response.isProtectionBoundaryNoMediaResponse()) {+ actions.add(new Action(control.getMode() == ControlMode.FETCH_SEGMENT+ ? ActionType.REQUIRE_PO_TOKEN : ActionType.REFRESH_PO_TOKEN));+ }+ if (control.getMode() == ControlMode.PUMP && control.getSegmentCount() > 0) {+ next = state.resetRecoveryBudgets();+ actions.add(new Action(ActionType.RESET_RECOVERY_BUDGETS));+ }+ final int backoff = Math.max(0, response.getBackoffTimeMs());+ if (backoff > 0) {+ actions.add(new Action(control.shouldHonorBackoff()+ ? ActionType.SLEEP_BACKOFF : ActionType.DEFER_BACKOFF));+ } else if (!control.shouldHonorBackoff()) {+ actions.add(new Action(ActionType.CLEAR_DEMAND_BACKOFF));+ }+ actions.add(new Action(control.getMode() == ControlMode.FETCH_SEGMENT+ && response.isProtectionBoundaryNoMediaResponse()+ ? ActionType.RETRY : ActionType.CONTINUE));+ return Result.control(next, actions, new ControlDecision(backoff, redirectUrl, null),+ SabrResponseStatePatch.builtin(response));+ }+}
youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/sabr/SabrBufferedRange.java
diff --git a/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/sabr/SabrBufferedRange.java b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/sabr/SabrBufferedRange.javanew file mode 100644index 0000000000..8404a73f84--- /dev/null+++ b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/sabr/SabrBufferedRange.java@@ -0,0 +1,89 @@+package org.schabi.newpipe.extractor.services.youtube.sabr;++import javax.annotation.Nonnull;+import javax.annotation.Nullable;++public final class SabrBufferedRange {+ private static final int MAX_INT32_VALUE = Integer.MAX_VALUE;++ private final int itag;+ private final long lastModified;+ @Nullable+ private final String xtags;+ private final long startTimeMs;+ private final long durationMs;+ private final int startSegmentIndex;+ private final int endSegmentIndex;+ private final int timescale;++ public SabrBufferedRange(final int itag,+ final long lastModified,+ @Nullable final String xtags,+ final long startTimeMs,+ final long durationMs,+ final int startSegmentIndex,+ final int endSegmentIndex,+ final int timescale) {+ this.itag = itag;+ this.lastModified = lastModified;+ this.xtags = xtags;+ this.startTimeMs = startTimeMs;+ this.durationMs = durationMs;+ this.startSegmentIndex = startSegmentIndex;+ this.endSegmentIndex = endSegmentIndex;+ this.timescale = timescale;+ }++ @Nonnull+ static SabrBufferedRange full(@Nonnull final YoutubeSabrFormat format) {+ return new SabrBufferedRange(format.getItag(), format.getLastModified(), format.getXtags(),+ 0, MAX_INT32_VALUE, MAX_INT32_VALUE, MAX_INT32_VALUE, 1000);+ }++ @Nonnull+ byte[] toProto() {+ return toProto(true);+ }++ @Nonnull+ byte[] toProto(final boolean includeTimeRange) {+ final SabrProto.Writer range = new SabrProto.Writer();+ range.writeMessage(1, formatIdProto());+ range.writeUInt64(2, startTimeMs);+ range.writeUInt64(3, durationMs);+ range.writeInt32(4, startSegmentIndex);+ range.writeInt32(5, endSegmentIndex);+ if (includeTimeRange) {+ range.writeMessage(6, timeRangeProto());+ }+ return range.toByteArray();+ }++ @Nonnull+ public String summarize() {+ return "itag=" + itag+ + ":seq=" + startSegmentIndex + "-" + endSegmentIndex+ + ":time=" + startTimeMs + "+" + durationMs+ + ":timescale=" + timescale;+ }++ @Nonnull+ private byte[] formatIdProto() {+ final SabrProto.Writer format = new SabrProto.Writer();+ format.writeInt32(1, itag);+ if (lastModified > 0) {+ format.writeUInt64(2, lastModified);+ }+ format.writeStringIfNotEmpty(3, xtags);+ return format.toByteArray();+ }++ @Nonnull+ private byte[] timeRangeProto() {+ final SabrProto.Writer timeRange = new SabrProto.Writer();+ timeRange.writeUInt64(1, startTimeMs);+ timeRange.writeUInt64(2, durationMs);+ timeRange.writeInt32(3, timescale);+ return timeRange.toByteArray();+ }+}
youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/sabr/SabrColdStartPoToken.java
diff --git a/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/sabr/SabrColdStartPoToken.java b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/sabr/SabrColdStartPoToken.javanew file mode 100644index 0000000000..53cc7b43c3--- /dev/null+++ b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/sabr/SabrColdStartPoToken.java@@ -0,0 +1,46 @@+package org.schabi.newpipe.extractor.services.youtube.sabr;++import javax.annotation.Nonnull;+import java.security.SecureRandom;+import java.nio.charset.StandardCharsets;++final class SabrColdStartPoToken {+ private static final int MAX_IDENTIFIER_BYTES = 118;+ private static final SecureRandom RANDOM = new SecureRandom();++ private SabrColdStartPoToken() {+ }++ @Nonnull+ static byte[] generate(@Nonnull final String identifier, final int clientState)+ throws SabrProtocolException {+ final byte[] identifierBytes = identifier.getBytes(StandardCharsets.UTF_8);+ if (identifierBytes.length > MAX_IDENTIFIER_BYTES) {+ throw new SabrProtocolException("PO token identifier is too long");+ }++ final int timestamp = (int) (System.currentTimeMillis() / 1000L);+ final byte[] key = new byte[] {(byte) RANDOM.nextInt(256), (byte) RANDOM.nextInt(256)};+ final byte[] header = new byte[] {+ key[0],+ key[1],+ 0,+ (byte) clientState,+ (byte) ((timestamp >> 24) & 0xff),+ (byte) ((timestamp >> 16) & 0xff),+ (byte) ((timestamp >> 8) & 0xff),+ (byte) (timestamp & 0xff)+ };++ final byte[] packet = new byte[2 + header.length + identifierBytes.length];+ packet[0] = 34;+ packet[1] = (byte) (header.length + identifierBytes.length);+ System.arraycopy(header, 0, packet, 2, header.length);+ System.arraycopy(identifierBytes, 0, packet, 2 + header.length, identifierBytes.length);++ for (int i = key.length; i < packet.length - 2; i++) {+ packet[2 + i] ^= packet[2 + (i % key.length)];+ }+ return packet;+ }+}
youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/sabr/SabrContextSendingPolicy.java
diff --git a/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/sabr/SabrContextSendingPolicy.java b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/sabr/SabrContextSendingPolicy.javanew file mode 100644index 0000000000..e0f5a04f13--- /dev/null+++ b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/sabr/SabrContextSendingPolicy.java@@ -0,0 +1,91 @@+package org.schabi.newpipe.extractor.services.youtube.sabr;++import javax.annotation.Nonnull;+import java.util.ArrayList;+import java.util.Collections;+import java.util.List;++public final class SabrContextSendingPolicy {+ private final List<Integer> startPolicy = new ArrayList<>();+ private final List<Integer> stopPolicy = new ArrayList<>();+ private final List<Integer> discardPolicy = new ArrayList<>();++ private SabrContextSendingPolicy() {+ }++ @Nonnull+ public static SabrContextSendingPolicy normalized(@Nonnull final List<Integer> start,+ @Nonnull final List<Integer> stop,+ @Nonnull final List<Integer> discard) {+ if (start.size() > 128 || stop.size() > 128 || discard.size() > 128+ || containsNegative(start) || containsNegative(stop) || containsNegative(discard)) {+ throw new IllegalArgumentException("Invalid normalized SABR context policy");+ }+ final SabrContextSendingPolicy policy = new SabrContextSendingPolicy();+ policy.startPolicy.addAll(start);+ policy.stopPolicy.addAll(stop);+ policy.discardPolicy.addAll(discard);+ return policy;+ }++ private static boolean containsNegative(@Nonnull final List<Integer> values) {+ for (final Integer value : values) {+ if (value == null || value < 0) return true;+ }+ return false;+ }++ @Nonnull+ static SabrContextSendingPolicy decode(@Nonnull final byte[] data)+ throws SabrProtocolException {+ final SabrContextSendingPolicy policy = new SabrContextSendingPolicy();+ for (final SabrProto.Field field : SabrProto.readFields(data)) {+ switch (field.getNumber()) {+ case 1:+ policy.readPolicyValues(field, policy.startPolicy);+ break;+ case 2:+ policy.readPolicyValues(field, policy.stopPolicy);+ break;+ case 3:+ policy.readPolicyValues(field, policy.discardPolicy);+ break;+ default:+ break;+ }+ }+ return policy;+ }++ private void readPolicyValues(@Nonnull final SabrProto.Field field,+ @Nonnull final List<Integer> output)+ throws SabrProtocolException {+ if (field.getWireType() == SabrProto.WIRE_VARINT) {+ output.add((int) field.getVarint());+ } else if (field.getWireType() == SabrProto.WIRE_LENGTH_DELIMITED) {+ for (final Long value : SabrProto.readPackedVarints(field.getBytes())) {+ output.add(value.intValue());+ }+ }+ }++ @Nonnull+ public List<Integer> getStartPolicy() {+ return Collections.unmodifiableList(startPolicy);+ }++ @Nonnull+ public List<Integer> getStopPolicy() {+ return Collections.unmodifiableList(stopPolicy);+ }++ @Nonnull+ public List<Integer> getDiscardPolicy() {+ return Collections.unmodifiableList(discardPolicy);+ }++ @Nonnull+ public String summarize() {+ return "start=" + startPolicy + ", stop=" + stopPolicy + ", discard=" + discardPolicy;+ }+}
youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/sabr/SabrContextUpdate.java
diff --git a/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/sabr/SabrContextUpdate.java b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/sabr/SabrContextUpdate.javanew file mode 100644index 0000000000..b9cd871993--- /dev/null+++ b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/sabr/SabrContextUpdate.java@@ -0,0 +1,131 @@+package org.schabi.newpipe.extractor.services.youtube.sabr;++import javax.annotation.Nonnull;+import javax.annotation.Nullable;++public final class SabrContextUpdate {+ static final int WRITE_POLICY_OVERWRITE = 1;+ static final int WRITE_POLICY_KEEP_EXISTING = 2;++ private final int type;+ private final int scope;+ @Nonnull+ private final byte[] value;+ private final boolean sendByDefault;+ private final int writePolicy;+ @Nullable+ private final SabrContextValue decodedValue;++ private SabrContextUpdate(final int type,+ final int scope,+ @Nonnull final byte[] value,+ final boolean sendByDefault,+ final int writePolicy,+ @Nullable final SabrContextValue decodedValue) {+ this.type = type;+ this.scope = scope;+ this.value = value.clone();+ this.sendByDefault = sendByDefault;+ this.writePolicy = writePolicy;+ this.decodedValue = decodedValue;+ }++ @Nonnull+ public static SabrContextUpdate normalized(final int type, final int scope,+ @Nonnull final byte[] value,+ final boolean sendByDefault,+ final int writePolicy) {+ if (type < 0 || value.length == 0 || value.length > 64 * 1024) {+ throw new IllegalArgumentException("Invalid normalized SABR context update");+ }+ return new SabrContextUpdate(type, scope, value, sendByDefault, writePolicy, null);+ }++ @Nonnull+ static SabrContextUpdate decode(@Nonnull final byte[] data) throws SabrProtocolException {+ int type = -1;+ int scope = -1;+ byte[] value = new byte[0];+ boolean sendByDefault = false;+ int writePolicy = -1;+ SabrContextValue decodedValue = null;++ for (final SabrProto.Field field : SabrProto.readFields(data)) {+ switch (field.getNumber()) {+ case 1:+ type = (int) field.getVarint();+ break;+ case 2:+ scope = (int) field.getVarint();+ break;+ case 3:+ value = field.getBytes();+ try {+ decodedValue = SabrContextValue.decode(value);+ } catch (final SabrProtocolException ignored) {+ decodedValue = null;+ }+ break;+ case 4:+ sendByDefault = field.getVarint() != 0;+ break;+ case 5:+ writePolicy = (int) field.getVarint();+ break;+ default:+ break;+ }+ }++ return new SabrContextUpdate(type, scope, value, sendByDefault, writePolicy,+ decodedValue);+ }++ @Nonnull+ byte[] toStreamerContextProto() {+ final SabrProto.Writer context = new SabrProto.Writer();+ context.writeInt32(1, type);+ context.writeBytes(2, value);+ return context.toByteArray();+ }++ public int getType() {+ return type;+ }++ public int getScope() {+ return scope;+ }++ @Nonnull+ public byte[] getValue() {+ return value.clone();+ }++ int getValueLength() {+ return value.length;+ }++ public boolean isSendByDefault() {+ return sendByDefault;+ }++ public int getWritePolicy() {+ return writePolicy;+ }++ @Nullable+ public SabrContextValue getDecodedValue() {+ return decodedValue;+ }++ @Nonnull+ public String summarize() {+ return "type=" + type+ + ", scope=" + scope+ + ", valueBytes=" + value.length+ + ", sendByDefault=" + sendByDefault+ + ", writePolicy=" + writePolicy+ + ", value=" + (decodedValue == null ? "undecoded" : decodedValue.summarize());+ }+}
youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/sabr/SabrContextValue.java
diff --git a/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/sabr/SabrContextValue.java b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/sabr/SabrContextValue.javanew file mode 100644index 0000000000..bb74860482--- /dev/null+++ b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/sabr/SabrContextValue.java@@ -0,0 +1,156 @@+package org.schabi.newpipe.extractor.services.youtube.sabr;++import javax.annotation.Nonnull;+import javax.annotation.Nullable;++public final class SabrContextValue {+ @Nullable+ private final TimingInfo timingInfo;+ private final int signatureLength;+ private final int field5;++ private SabrContextValue(@Nullable final TimingInfo timingInfo,+ final int signatureLength,+ final int field5) {+ this.timingInfo = timingInfo;+ this.signatureLength = signatureLength;+ this.field5 = field5;+ }++ @Nonnull+ static SabrContextValue decode(@Nonnull final byte[] data) throws SabrProtocolException {+ TimingInfo timingInfo = null;+ int signatureLength = 0;+ int field5 = -1;+ for (final SabrProto.Field field : SabrProto.readFields(data)) {+ if (field.getNumber() == 1+ && field.getWireType() == SabrProto.WIRE_LENGTH_DELIMITED) {+ timingInfo = TimingInfo.decode(field.getBytes());+ } else if (field.getNumber() == 2+ && field.getWireType() == SabrProto.WIRE_LENGTH_DELIMITED) {+ signatureLength = field.getBytes().length;+ } else if (field.getNumber() == 5+ && field.getWireType() == SabrProto.WIRE_VARINT) {+ field5 = (int) field.getVarint();+ }+ }+ return new SabrContextValue(timingInfo, signatureLength, field5);+ }++ @Nullable+ public TimingInfo getTimingInfo() {+ return timingInfo;+ }++ public int getSignatureLength() {+ return signatureLength;+ }++ public int getField5() {+ return field5;+ }++ @Nonnull+ public String summarize() {+ return "timing=" + (timingInfo == null ? "null" : timingInfo.summarize())+ + ", signatureBytes=" + signatureLength+ + ", field5=" + field5;+ }++ public static final class TimingInfo {+ private final long timestampMs;+ private final int durationMs;+ @Nullable+ private final ContentInfo contentInfo;++ private TimingInfo(final long timestampMs,+ final int durationMs,+ @Nullable final ContentInfo contentInfo) {+ this.timestampMs = timestampMs;+ this.durationMs = durationMs;+ this.contentInfo = contentInfo;+ }++ @Nonnull+ private static TimingInfo decode(@Nonnull final byte[] data) throws SabrProtocolException {+ long timestampMs = -1;+ int durationMs = -1;+ ContentInfo contentInfo = null;+ for (final SabrProto.Field field : SabrProto.readFields(data)) {+ if (field.getNumber() == 1 && field.getWireType() == SabrProto.WIRE_VARINT) {+ timestampMs = field.getVarint();+ } else if (field.getNumber() == 2+ && field.getWireType() == SabrProto.WIRE_VARINT) {+ durationMs = (int) field.getVarint();+ } else if (field.getNumber() == 3+ && field.getWireType() == SabrProto.WIRE_LENGTH_DELIMITED) {+ contentInfo = ContentInfo.decode(field.getBytes());+ }+ }+ return new TimingInfo(timestampMs, durationMs, contentInfo);+ }++ public long getTimestampMs() {+ return timestampMs;+ }++ public int getDurationMs() {+ return durationMs;+ }++ @Nullable+ public ContentInfo getContentInfo() {+ return contentInfo;+ }++ @Nonnull+ private String summarize() {+ return "timestampMs=" + timestampMs+ + "/durationMs=" + durationMs+ + "/content=" + (contentInfo == null ? "null" : contentInfo.summarize());+ }+ }++ public static final class ContentInfo {+ @Nullable+ private final String contentId;+ private final int contentType;++ private ContentInfo(@Nullable final String contentId,+ final int contentType) {+ this.contentId = contentId;+ this.contentType = contentType;+ }++ @Nonnull+ private static ContentInfo decode(@Nonnull final byte[] data) throws SabrProtocolException {+ String contentId = null;+ int contentType = -1;+ for (final SabrProto.Field field : SabrProto.readFields(data)) {+ if (field.getNumber() == 1+ && field.getWireType() == SabrProto.WIRE_LENGTH_DELIMITED) {+ contentId = field.getString();+ } else if (field.getNumber() == 2+ && field.getWireType() == SabrProto.WIRE_VARINT) {+ contentType = (int) field.getVarint();+ }+ }+ return new ContentInfo(contentId, contentType);+ }++ @Nullable+ public String getContentId() {+ return contentId;+ }++ public int getContentType() {+ return contentType;+ }++ @Nonnull+ private String summarize() {+ return "contentIdLength=" + (contentId == null ? 0 : contentId.length())+ + "/contentType=" + contentType;+ }+ }+}
youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/sabr/SabrDecodedResponse.java
diff --git a/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/sabr/SabrDecodedResponse.java b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/sabr/SabrDecodedResponse.javanew file mode 100644index 0000000000..b4ea9aaf7d--- /dev/null+++ b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/sabr/SabrDecodedResponse.java@@ -0,0 +1,490 @@+package org.schabi.newpipe.extractor.services.youtube.sabr;++import javax.annotation.Nonnull;+import javax.annotation.Nullable;+import java.util.ArrayList;+import java.util.Collections;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;++public final class SabrDecodedResponse {+ private static final int MAX_MALFORMED_PARTS = 16;+ private static final int MAX_MALFORMED_MESSAGE_CHARS = 256;+ private final List<UmpPart> parts = new ArrayList<>();+ private final List<String> partSummaries = new ArrayList<>();+ private final List<String> wireFieldSummaries = new ArrayList<>();+ private final List<SabrFormatInitializationMetadata> formatInitializationMetadata =+ new ArrayList<>();+ private final List<SabrMediaHeader> mediaHeaders = new ArrayList<>();+ private final List<SabrContextUpdate> sabrContextUpdates = new ArrayList<>();+ private final List<SabrLiveMetadata> liveMetadata = new ArrayList<>();+ private final List<SabrOnesieHeader> onesieHeaders = new ArrayList<>();+ private final List<SabrOnesieData> onesieData = new ArrayList<>();+ private final Map<Integer, Long> mediaBytesByHeaderId = new LinkedHashMap<>();+ private final List<Integer> mediaEndHeaderIds = new ArrayList<>();+ private final List<Integer> unknownPartTypes = new ArrayList<>();+ private final List<String> malformedParts = new ArrayList<>();+ private final Map<Integer, List<String>> genericPartDescriptions = new LinkedHashMap<>();+ @Nullable+ private String redirectUrl;+ @Nullable+ private SabrRedirect redirect;+ @Nullable+ private SabrSeek sabrSeek;+ @Nullable+ private String sabrError;+ @Nullable+ private SabrError sabrErrorDetails;+ @Nullable+ private SabrReloadPlayerResponse reloadPlayerResponse;+ @Nullable+ private SabrFormatSelectionConfig formatSelectionConfig;+ @Nullable+ private SabrSelectableFormats selectableFormats;+ @Nullable+ private SabrNextRequestPolicy nextRequestPolicy;+ @Nullable+ private SabrRequestIdentifier requestIdentifier;+ @Nullable+ private SabrPlaybackStartPolicy playbackStartPolicy;+ @Nullable+ private SabrContextSendingPolicy sabrContextSendingPolicy;+ @Nullable+ private SabrRequestCancellationPolicy requestCancellationPolicy;+ @Nullable+ private SabrStreamProtectionStatus streamProtection;+ @Nullable+ private SabrPrewarmConnection prewarmConnection;+ @Nullable+ private SabrSnackbarMessage snackbarMessage;+ private int streamProtectionStatus = -1;+ private int streamProtectionMaxRetries = -1;+ private int backoffTimeMs = -1;+ private boolean reloadRequested;++ void addPart(@Nonnull final UmpPart part) {+ parts.add(part);+ addPartSummary(partSummaries, part.getType(), part.getSize());+ }++ void setPartSummaries(@Nonnull final List<String> summaries) {+ partSummaries.clear();+ partSummaries.addAll(summaries);+ }++ static void addPartSummary(@Nonnull final List<String> summaries,+ final int type,+ final int size) {+ final String value = type + ":" + size;+ if (summaries.isEmpty()) {+ summaries.add(value);+ return;+ }+ final int lastIndex = summaries.size() - 1;+ final String last = summaries.get(lastIndex);+ if (last.equals(value)) {+ summaries.set(lastIndex, value + "x2");+ } else if (last.startsWith(value + 'x')) {+ summaries.set(lastIndex, value+ + 'x' + (Integer.parseInt(last.substring(value.length() + 1)) + 1));+ } else {+ summaries.add(value);+ }+ }++ void addUnknownPartType(final int type) {+ unknownPartTypes.add(type);+ }++ void addMalformedPart(final int type, final int size,+ @Nonnull final SabrProtocolException error) {+ if (malformedParts.size() >= MAX_MALFORMED_PARTS) {+ return;+ }+ final String message = String.valueOf(error.getMessage());+ malformedParts.add(type + ":" + size + ":" + (message.length()+ > MAX_MALFORMED_MESSAGE_CHARS+ ? message.substring(0, MAX_MALFORMED_MESSAGE_CHARS) : message));+ }++ void addWireFieldSummary(final int type, @Nonnull final String summary) {+ wireFieldSummaries.add(type + "={" + summary + '}');+ }++ void addGenericPartDescription(final int type, @Nonnull final String description) {+ List<String> descriptions = genericPartDescriptions.get(type);+ if (descriptions == null) {+ descriptions = new ArrayList<>();+ genericPartDescriptions.put(type, descriptions);+ }+ descriptions.add(description);+ }++ void addFormatInitializationMetadata(+ @Nonnull final SabrFormatInitializationMetadata metadata) {+ formatInitializationMetadata.add(metadata);+ }++ void addMediaHeader(@Nonnull final SabrMediaHeader header) {+ mediaHeaders.add(header);+ }++ void addSabrContextUpdate(@Nonnull final SabrContextUpdate sabrContextUpdate) {+ sabrContextUpdates.add(sabrContextUpdate);+ }++ void addLiveMetadata(@Nonnull final SabrLiveMetadata metadata) {+ liveMetadata.add(metadata);+ }++ void addOnesieHeader(@Nonnull final SabrOnesieHeader onesieHeader) {+ onesieHeaders.add(onesieHeader);+ }++ void addOnesieData(@Nonnull final SabrOnesieData data) {+ onesieData.add(data);+ }++ void addMediaBytes(final int headerId, final long bytes) {+ final Long current = mediaBytesByHeaderId.get(headerId);+ mediaBytesByHeaderId.put(headerId, current == null ? bytes : current + bytes);+ }++ void addMediaEndHeaderId(final int headerId) {+ mediaEndHeaderIds.add(headerId);+ }++ void setRedirectUrl(@Nullable final String redirectUrl) {+ this.redirectUrl = redirectUrl;+ }++ void setRedirect(@Nullable final SabrRedirect redirect) {+ this.redirect = redirect;+ }++ void setSabrSeek(@Nullable final SabrSeek sabrSeek) {+ this.sabrSeek = sabrSeek;+ }++ void setSabrError(@Nullable final String sabrError) {+ this.sabrError = sabrError;+ }++ void setSabrErrorDetails(@Nullable final SabrError sabrErrorDetails) {+ this.sabrErrorDetails = sabrErrorDetails;+ }++ void setReloadPlayerResponse(@Nullable final SabrReloadPlayerResponse reloadPlayerResponse) {+ this.reloadPlayerResponse = reloadPlayerResponse;+ }++ void setFormatSelectionConfig(@Nullable final SabrFormatSelectionConfig formatSelectionConfig) {+ this.formatSelectionConfig = formatSelectionConfig;+ }++ void setSelectableFormats(@Nullable final SabrSelectableFormats selectableFormats) {+ this.selectableFormats = selectableFormats;+ }++ void setNextRequestPolicy(@Nullable final SabrNextRequestPolicy nextRequestPolicy) {+ this.nextRequestPolicy = nextRequestPolicy;+ }++ void setRequestIdentifier(@Nullable final SabrRequestIdentifier requestIdentifier) {+ this.requestIdentifier = requestIdentifier;+ }++ void setPlaybackStartPolicy(@Nullable final SabrPlaybackStartPolicy playbackStartPolicy) {+ this.playbackStartPolicy = playbackStartPolicy;+ }++ void setSabrContextSendingPolicy(+ @Nullable final SabrContextSendingPolicy sabrContextSendingPolicy) {+ this.sabrContextSendingPolicy = sabrContextSendingPolicy;+ }++ void setRequestCancellationPolicy(+ @Nullable final SabrRequestCancellationPolicy requestCancellationPolicy) {+ this.requestCancellationPolicy = requestCancellationPolicy;+ }++ void setStreamProtection(@Nullable final SabrStreamProtectionStatus streamProtection) {+ this.streamProtection = streamProtection;+ }++ void setPrewarmConnection(@Nullable final SabrPrewarmConnection prewarmConnection) {+ this.prewarmConnection = prewarmConnection;+ }++ void setSnackbarMessage(@Nullable final SabrSnackbarMessage snackbarMessage) {+ this.snackbarMessage = snackbarMessage;+ }++ void setStreamProtectionStatus(final int streamProtectionStatus) {+ this.streamProtectionStatus = streamProtectionStatus;+ }++ void setStreamProtectionMaxRetries(final int streamProtectionMaxRetries) {+ this.streamProtectionMaxRetries = streamProtectionMaxRetries;+ }++ void setBackoffTimeMs(final int backoffTimeMs) {+ this.backoffTimeMs = backoffTimeMs;+ }++ void setReloadRequested(final boolean reloadRequested) {+ this.reloadRequested = reloadRequested;+ }++ @Nonnull+ public List<UmpPart> getParts() {+ return Collections.unmodifiableList(parts);+ }++ @Nonnull+ public List<SabrFormatInitializationMetadata> getFormatInitializationMetadata() {+ return Collections.unmodifiableList(formatInitializationMetadata);+ }++ @Nonnull+ public List<SabrMediaHeader> getMediaHeaders() {+ return Collections.unmodifiableList(mediaHeaders);+ }++ @Nonnull+ public List<SabrContextUpdate> getSabrContextUpdates() {+ return Collections.unmodifiableList(sabrContextUpdates);+ }++ @Nonnull+ public List<SabrLiveMetadata> getLiveMetadata() {+ return Collections.unmodifiableList(liveMetadata);+ }++ @Nonnull+ public List<SabrOnesieHeader> getOnesieHeaders() {+ return Collections.unmodifiableList(onesieHeaders);+ }++ @Nonnull+ public List<SabrOnesieData> getOnesieData() {+ return Collections.unmodifiableList(onesieData);+ }++ @Nonnull+ public Map<Integer, Long> getMediaBytesByHeaderId() {+ return Collections.unmodifiableMap(mediaBytesByHeaderId);+ }++ @Nonnull+ public List<Integer> getMediaEndHeaderIds() {+ return Collections.unmodifiableList(mediaEndHeaderIds);+ }++ @Nonnull+ public List<String> getIntegrityIssues() {+ final List<String> issues = new ArrayList<>();+ final List<Integer> mediaHeaderIds = new ArrayList<>();+ for (final SabrMediaHeader header : mediaHeaders) {+ if (mediaHeaderIds.contains(header.getHeaderId())) {+ issues.add("duplicate-media-header:" + header.getHeaderId());+ }+ mediaHeaderIds.add(header.getHeaderId());+ final Long mediaBytes = mediaBytesByHeaderId.get(header.getHeaderId());+ if (mediaBytes == null) {+ issues.add("missing-media:" + header.getHeaderId());+ } else if (header.getContentLength() >= 0 && mediaBytes != header.getContentLength()) {+ issues.add("length-mismatch:" + header.getHeaderId()+ + ":expected=" + header.getContentLength()+ + ":actual=" + mediaBytes);+ }+ if (!mediaEndHeaderIds.contains(header.getHeaderId())) {+ issues.add("missing-media-end:" + header.getHeaderId());+ }+ }+ for (final Integer headerId : mediaBytesByHeaderId.keySet()) {+ if (!mediaHeaderIds.contains(headerId)) {+ issues.add("media-without-header:" + headerId);+ }+ }+ for (final Integer headerId : mediaEndHeaderIds) {+ if (!mediaHeaderIds.contains(headerId)) {+ issues.add("media-end-without-header:" + headerId);+ }+ }+ return issues;+ }++ @Nonnull+ public List<Integer> getUnknownPartTypes() {+ return Collections.unmodifiableList(unknownPartTypes);+ }++ @Nonnull+ public List<String> getMalformedParts() {+ return Collections.unmodifiableList(malformedParts);+ }++ @Nonnull+ public Map<Integer, List<String>> getGenericPartDescriptions() {+ final Map<Integer, List<String>> copy = new LinkedHashMap<>();+ for (final Map.Entry<Integer, List<String>> entry : genericPartDescriptions.entrySet()) {+ copy.put(entry.getKey(), Collections.unmodifiableList(new ArrayList<>(entry.getValue())));+ }+ return Collections.unmodifiableMap(copy);+ }++ @Nullable+ public String getRedirectUrl() {+ return redirectUrl;+ }++ @Nullable+ public SabrRedirect getRedirect() {+ return redirect;+ }++ @Nullable+ public SabrSeek getSabrSeek() {+ return sabrSeek;+ }++ @Nullable+ public String getSabrError() {+ return sabrError;+ }++ @Nullable+ public SabrError getSabrErrorDetails() {+ return sabrErrorDetails;+ }++ @Nullable+ public SabrReloadPlayerResponse getReloadPlayerResponse() {+ return reloadPlayerResponse;+ }++ @Nullable+ public SabrFormatSelectionConfig getFormatSelectionConfig() {+ return formatSelectionConfig;+ }++ @Nullable+ public SabrSelectableFormats getSelectableFormats() {+ return selectableFormats;+ }++ @Nullable+ public SabrNextRequestPolicy getNextRequestPolicy() {+ return nextRequestPolicy;+ }++ @Nullable+ public SabrRequestIdentifier getRequestIdentifier() {+ return requestIdentifier;+ }++ @Nullable+ public SabrPlaybackStartPolicy getPlaybackStartPolicy() {+ return playbackStartPolicy;+ }++ @Nullable+ public SabrContextSendingPolicy getSabrContextSendingPolicy() {+ return sabrContextSendingPolicy;+ }++ @Nullable+ public SabrRequestCancellationPolicy getRequestCancellationPolicy() {+ return requestCancellationPolicy;+ }++ @Nullable+ public SabrStreamProtectionStatus getStreamProtection() {+ return streamProtection;+ }++ @Nullable+ public SabrPrewarmConnection getPrewarmConnection() {+ return prewarmConnection;+ }++ @Nullable+ public SabrSnackbarMessage getSnackbarMessage() {+ return snackbarMessage;+ }++ public int getStreamProtectionStatus() {+ return streamProtectionStatus;+ }++ public int getStreamProtectionMaxRetries() {+ return streamProtectionMaxRetries;+ }++ public int getBackoffTimeMs() {+ return backoffTimeMs;+ }++ public boolean isReloadRequested() {+ return reloadRequested;+ }++ public boolean hasMedia() {+ return !mediaHeaders.isEmpty() || !mediaBytesByHeaderId.isEmpty();+ }++ public boolean isNoMediaResponse() {+ return !hasMedia();+ }++ public boolean isPolicyOnlyResponse() {+ return isNoMediaResponse() && nextRequestPolicy != null;+ }++ public boolean isProtectedNoMediaResponse() {+ return isNoMediaResponse() && streamProtectionStatus >= 3;+ }++ public boolean isProtectionBoundaryNoMediaResponse() {+ return isNoMediaResponse() && streamProtectionStatus >= 2;+ }++ @Nonnull+ public String summarizeForDiagnostics() {+ final List<String> initialization = new ArrayList<>();+ for (final SabrFormatInitializationMetadata metadata : formatInitializationMetadata) {+ initialization.add(metadata.summarize());+ }+ final List<String> headers = new ArrayList<>();+ for (final SabrMediaHeader header : mediaHeaders) {+ headers.add(header.summarize());+ }+ return "parts=" + partSummaries+ + ", wireFields=" + wireFieldSummaries+ + ", controls=" + genericPartDescriptions+ + ", initialization=" + initialization+ + ", mediaHeaders=" + headers+ + ", mediaBytes=" + mediaBytesByHeaderId+ + ", mediaEnds=" + mediaEndHeaderIds+ + ", integrity=" + getIntegrityIssues()+ + ", malformedParts=" + malformedParts+ + ", unknownParts=" + unknownPartTypes+ + ", protection=" + streamProtectionStatus + '/' + streamProtectionMaxRetries+ + ", backoffMs=" + backoffTimeMs+ + ", reload=" + reloadRequested;+ }++ @Nonnull+ public String summarizeNoMediaResponse() {+ return "parts=" + parts.size()+ + ", status=" + streamProtectionStatus+ + ", maxRetries=" + streamProtectionMaxRetries+ + ", backoffMs=" + backoffTimeMs+ + ", policy=" + (nextRequestPolicy != null)+ + ", reload=" + reloadRequested+ + ", redirect=" + (redirectUrl != null && !redirectUrl.isEmpty())+ + ", error=" + (sabrError == null ? "null" : sabrError);+ }+}
youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/sabr/SabrError.java
diff --git a/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/sabr/SabrError.java b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/sabr/SabrError.javanew file mode 100644index 0000000000..3cd4c6d6bf--- /dev/null+++ b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/sabr/SabrError.java@@ -0,0 +1,46 @@+package org.schabi.newpipe.extractor.services.youtube.sabr;++import javax.annotation.Nonnull;+import javax.annotation.Nullable;++public final class SabrError {+ @Nullable+ private final String type;+ private final int code;++ private SabrError(@Nullable final String type,+ final int code) {+ this.type = type;+ this.code = code;+ }++ @Nonnull+ static SabrError decode(@Nonnull final byte[] data) throws SabrProtocolException {+ String type = null;+ int code = 0;+ for (final SabrProto.Field field : SabrProto.readFields(data)) {+ if (field.getNumber() == 1+ && field.getWireType() == SabrProto.WIRE_LENGTH_DELIMITED) {+ type = field.getString();+ } else if (field.getNumber() == 2+ && field.getWireType() == SabrProto.WIRE_VARINT) {+ code = (int) field.getVarint();+ }+ }+ return new SabrError(type, code);+ }++ @Nullable+ public String getType() {+ return type;+ }++ public int getCode() {+ return code;+ }++ @Nonnull+ public String summarize() {+ return "type=" + (type == null ? "null" : type) + ", code=" + code;+ }+}
youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/sabr/SabrFormatInitializationMetadata.java
diff --git a/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/sabr/SabrFormatInitializationMetadata.java b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/sabr/SabrFormatInitializationMetadata.javanew file mode 100644index 0000000000..aa8ab78191--- /dev/null+++ b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/sabr/SabrFormatInitializationMetadata.java@@ -0,0 +1,246 @@+package org.schabi.newpipe.extractor.services.youtube.sabr;++import javax.annotation.Nonnull;+import javax.annotation.Nullable;++public final class SabrFormatInitializationMetadata {+ @Nonnull+ private final byte[] rawSummaryBytes;+ @Nullable+ private final String videoId;+ private final int itag;+ private final long lastModified;+ @Nullable+ private final String xtags;+ private final long endTimeMs;+ private final long endSegmentNumber;+ @Nullable+ private final String mimeType;+ private final long initRangeStart;+ private final long initRangeEnd;+ private final long indexRangeStart;+ private final long indexRangeEnd;+ private final long field8;+ private final long durationUnits;+ private final long durationTimescale;++ private SabrFormatInitializationMetadata(@Nullable final String videoId,+ @Nonnull final byte[] rawSummaryBytes,+ final int itag,+ final long lastModified,+ @Nullable final String xtags,+ final long endTimeMs,+ final long endSegmentNumber,+ @Nullable final String mimeType,+ final long initRangeStart,+ final long initRangeEnd,+ final long indexRangeStart,+ final long indexRangeEnd,+ final long field8,+ final long durationUnits,+ final long durationTimescale) {+ this.videoId = videoId;+ this.rawSummaryBytes = rawSummaryBytes;+ this.itag = itag;+ this.lastModified = lastModified;+ this.xtags = xtags;+ this.endTimeMs = endTimeMs;+ this.endSegmentNumber = endSegmentNumber;+ this.mimeType = mimeType;+ this.initRangeStart = initRangeStart;+ this.initRangeEnd = initRangeEnd;+ this.indexRangeStart = indexRangeStart;+ this.indexRangeEnd = indexRangeEnd;+ this.field8 = field8;+ this.durationUnits = durationUnits;+ this.durationTimescale = durationTimescale;+ }++ @Nonnull+ public static SabrFormatInitializationMetadata normalized(+ @Nullable final String videoId, final int itag, final long lastModified,+ @Nullable final String xtags, final long endTimeMs, final long endSegmentNumber,+ @Nullable final String mimeType, final long initRangeStart, final long initRangeEnd,+ final long indexRangeStart, final long indexRangeEnd, final long field8,+ final long durationUnits, final long durationTimescale) {+ if (itag <= 0 || endSegmentNumber < -1 || durationUnits < -1+ || durationTimescale < -1) {+ throw new IllegalArgumentException("Invalid normalized SABR format metadata");+ }+ return new SabrFormatInitializationMetadata(videoId, new byte[0], itag, lastModified,+ xtags, endTimeMs, endSegmentNumber, mimeType, initRangeStart, initRangeEnd,+ indexRangeStart, indexRangeEnd, field8, durationUnits, durationTimescale);+ }++ @Nonnull+ static SabrFormatInitializationMetadata decode(@Nonnull final byte[] data)+ throws SabrProtocolException {+ String videoId = null;+ int itag = -1;+ long lastModified = -1;+ String xtags = null;+ long endTimeMs = -1;+ long endSegmentNumber = -1;+ String mimeType = null;+ long initRangeStart = -1;+ long initRangeEnd = -1;+ long indexRangeStart = -1;+ long indexRangeEnd = -1;+ long field8 = -1;+ long durationUnits = -1;+ long durationTimescale = -1;++ for (final SabrProto.Field field : SabrProto.readFields(data)) {+ switch (field.getNumber()) {+ case 1:+ videoId = field.getString();+ break;+ case 2:+ for (final SabrProto.Field formatField : SabrProto.readFields(field.getBytes())) {+ if (formatField.getNumber() == 1) {+ itag = (int) formatField.getVarint();+ } else if (formatField.getNumber() == 2) {+ lastModified = formatField.getVarint();+ } else if (formatField.getNumber() == 3) {+ xtags = formatField.getString();+ }+ }+ break;+ case 3:+ endTimeMs = field.getVarint();+ break;+ case 4:+ endSegmentNumber = field.getVarint();+ break;+ case 5:+ mimeType = field.getString();+ break;+ case 6:+ final Range initRange = decodeRange(field.getBytes());+ initRangeStart = initRange.start;+ initRangeEnd = initRange.end;+ break;+ case 7:+ final Range indexRange = decodeRange(field.getBytes());+ indexRangeStart = indexRange.start;+ indexRangeEnd = indexRange.end;+ break;+ case 8:+ field8 = field.getVarint();+ break;+ case 9:+ durationUnits = field.getVarint();+ break;+ case 10:+ durationTimescale = field.getVarint();+ break;+ default:+ break;+ }+ }++ return new SabrFormatInitializationMetadata(videoId, data.clone(), itag, lastModified, xtags,+ endTimeMs, endSegmentNumber, mimeType, initRangeStart, initRangeEnd,+ indexRangeStart, indexRangeEnd, field8, durationUnits, durationTimescale);+ }++ @Nonnull+ private static Range decodeRange(@Nonnull final byte[] data) throws SabrProtocolException {+ long start = -1;+ long end = -1;+ for (final SabrProto.Field field : SabrProto.readFields(data)) {+ if ((field.getNumber() == 1 || field.getNumber() == 3)+ && field.getWireType() == SabrProto.WIRE_VARINT) {+ start = field.getVarint();+ } else if ((field.getNumber() == 2 || field.getNumber() == 4)+ && field.getWireType() == SabrProto.WIRE_VARINT) {+ end = field.getVarint();+ }+ }+ return new Range(start, end);+ }++ @Nullable+ public String getVideoId() {+ return videoId;+ }++ public int getItag() {+ return itag;+ }++ public long getLastModified() {+ return lastModified;+ }++ @Nullable+ public String getXtags() {+ return xtags;+ }++ public long getEndSegmentNumber() {+ return endSegmentNumber;+ }++ @Nullable+ public String getMimeType() {+ return mimeType;+ }++ public long getDurationUnits() {+ return durationUnits;+ }++ public long getDurationTimescale() {+ return durationTimescale;+ }++ public long getInitRangeStart() {+ return initRangeStart;+ }++ public long getInitRangeEnd() {+ return initRangeEnd;+ }++ public long getIndexRangeStart() {+ return indexRangeStart;+ }++ public long getIndexRangeEnd() {+ return indexRangeEnd;+ }++ public long getField8() {+ return field8;+ }++ @Nonnull+ public String summarize() {+ String unknown = "unknown-error";+ try {+ unknown = SabrProto.summarizeUnknownFields(rawSummaryBytes, 1, 2, 3, 4, 5, 6, 7, 8,+ 9, 10);+ } catch (final Exception ignored) {+ }+ return "itag=" + itag+ + ", endSegment=" + endSegmentNumber+ + ", endTimeMs=" + endTimeMs+ + ", mime=" + (mimeType == null ? "null" : mimeType)+ + ", init=" + initRangeStart + '-' + initRangeEnd+ + ", index=" + indexRangeStart + '-' + indexRangeEnd+ + ", field8=" + field8+ + ", duration=" + durationUnits + '/' + durationTimescale+ + ", unknown=" + unknown;+ }++ private static final class Range {+ private final long start;+ private final long end;++ private Range(final long start, final long end) {+ this.start = start;+ this.end = end;+ }+ }+}
youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/sabr/SabrFormatSelectionConfig.java
diff --git a/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/sabr/SabrFormatSelectionConfig.java b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/sabr/SabrFormatSelectionConfig.javanew file mode 100644index 0000000000..8129f80782--- /dev/null+++ b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/sabr/SabrFormatSelectionConfig.java@@ -0,0 +1,83 @@+package org.schabi.newpipe.extractor.services.youtube.sabr;++import javax.annotation.Nonnull;+import javax.annotation.Nullable;+import java.util.ArrayList;+import java.util.Collections;+import java.util.List;++public final class SabrFormatSelectionConfig {+ @Nonnull+ private final List<Integer> itags;+ @Nullable+ private final String videoId;+ private final int resolution;++ private SabrFormatSelectionConfig(@Nonnull final List<Integer> itags,+ @Nullable final String videoId,+ final int resolution) {+ this.itags = Collections.unmodifiableList(new ArrayList<>(itags));+ this.videoId = videoId;+ this.resolution = resolution;+ }++ @Nonnull+ static SabrFormatSelectionConfig decode(@Nonnull final byte[] data)+ throws SabrProtocolException {+ final List<Integer> itags = new ArrayList<>();+ String videoId = null;+ int resolution = 0;+ for (final SabrProto.Field field : SabrProto.readFields(data)) {+ if (field.getNumber() == 2) {+ if (field.getWireType() == SabrProto.WIRE_VARINT) {+ itags.add((int) field.getVarint());+ } else if (field.getWireType() == SabrProto.WIRE_LENGTH_DELIMITED) {+ for (final Long itag : SabrProto.readPackedVarints(field.getBytes())) {+ itags.add(itag.intValue());+ }+ }+ } else if (field.getNumber() == 3+ && field.getWireType() == SabrProto.WIRE_LENGTH_DELIMITED) {+ videoId = field.getString();+ } else if (field.getNumber() == 4+ && field.getWireType() == SabrProto.WIRE_VARINT) {+ resolution = (int) field.getVarint();+ }+ }+ return new SabrFormatSelectionConfig(itags, videoId, resolution);+ }++ @Nonnull+ public List<Integer> getItags() {+ return itags;+ }++ @Nullable+ public String getVideoId() {+ return videoId;+ }++ public int getResolution() {+ return resolution;+ }++ @Nonnull+ public String summarize() {+ final StringBuilder builder = new StringBuilder();+ builder.append("itags=").append(itags.size()).append('[');+ final int sampleSize = Math.min(8, itags.size());+ for (int i = 0; i < sampleSize; i++) {+ if (i > 0) {+ builder.append(',');+ }+ builder.append(itags.get(i));+ }+ if (itags.size() > sampleSize) {+ builder.append(",...");+ }+ builder.append(']')+ .append(", videoIdLength=").append(videoId == null ? 0 : videoId.length())+ .append(", resolution=").append(resolution);+ return builder.toString();+ }+}
youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/sabr/SabrLiveMetadata.java
diff --git a/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/sabr/SabrLiveMetadata.java b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/sabr/SabrLiveMetadata.javanew file mode 100644index 0000000000..ca24c52cde--- /dev/null+++ b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/sabr/SabrLiveMetadata.java@@ -0,0 +1,176 @@+package org.schabi.newpipe.extractor.services.youtube.sabr;++import javax.annotation.Nonnull;+import javax.annotation.Nullable;++public final class SabrLiveMetadata {+ @Nullable+ private final String broadcastId;+ private final long headSequenceNumber;+ private final long headTimeMs;+ private final long wallTimeMs;+ @Nullable+ private final String videoId;+ private final boolean postLiveDvr;+ private final long headm;+ private final long minSeekableTimeTicks;+ private final int minSeekableTimescale;+ private final long maxSeekableTimeTicks;+ private final int maxSeekableTimescale;++ private SabrLiveMetadata(@Nullable final String broadcastId,+ final long headSequenceNumber,+ final long headTimeMs,+ final long wallTimeMs,+ @Nullable final String videoId,+ final boolean postLiveDvr,+ final long headm,+ final long minSeekableTimeTicks,+ final int minSeekableTimescale,+ final long maxSeekableTimeTicks,+ final int maxSeekableTimescale) {+ this.broadcastId = broadcastId;+ this.headSequenceNumber = headSequenceNumber;+ this.headTimeMs = headTimeMs;+ this.wallTimeMs = wallTimeMs;+ this.videoId = videoId;+ this.postLiveDvr = postLiveDvr;+ this.headm = headm;+ this.minSeekableTimeTicks = minSeekableTimeTicks;+ this.minSeekableTimescale = minSeekableTimescale;+ this.maxSeekableTimeTicks = maxSeekableTimeTicks;+ this.maxSeekableTimescale = maxSeekableTimescale;+ }++ @Nonnull+ public static SabrLiveMetadata normalized(@Nullable final String broadcastId,+ final long headSequenceNumber,+ final long headTimeMs,+ final long wallTimeMs,+ @Nullable final String videoId,+ final boolean postLiveDvr,+ final long headm,+ final long minSeekableTimeTicks,+ final int minSeekableTimescale,+ final long maxSeekableTimeTicks,+ final int maxSeekableTimescale) {+ if (headSequenceNumber < -1 || headTimeMs < -1 || wallTimeMs < -1+ || minSeekableTimeTicks < -1 || minSeekableTimescale < -1+ || maxSeekableTimeTicks < -1 || maxSeekableTimescale < -1) {+ throw new IllegalArgumentException("Invalid normalized SABR live metadata");+ }+ return new SabrLiveMetadata(broadcastId, headSequenceNumber, headTimeMs, wallTimeMs,+ videoId, postLiveDvr, headm, minSeekableTimeTicks, minSeekableTimescale,+ maxSeekableTimeTicks, maxSeekableTimescale);+ }++ @Nonnull+ static SabrLiveMetadata decode(@Nonnull final byte[] data) throws SabrProtocolException {+ String broadcastId = null;+ long headSequenceNumber = -1;+ long headTimeMs = -1;+ long wallTimeMs = -1;+ String videoId = null;+ boolean postLiveDvr = false;+ long headm = -1;+ long minSeekableTimeTicks = -1;+ int minSeekableTimescale = -1;+ long maxSeekableTimeTicks = -1;+ int maxSeekableTimescale = -1;+ for (final SabrProto.Field field : SabrProto.readFields(data)) {+ switch (field.getNumber()) {+ case 1:+ broadcastId = field.getString();+ break;+ case 3:+ headSequenceNumber = field.getVarint();+ break;+ case 4:+ headTimeMs = field.getVarint();+ break;+ case 5:+ wallTimeMs = field.getVarint();+ break;+ case 6:+ videoId = field.getString();+ break;+ case 8:+ postLiveDvr = field.getVarint() != 0;+ break;+ case 10:+ headm = field.getVarint();+ break;+ case 12:+ minSeekableTimeTicks = field.getVarint();+ break;+ case 13:+ minSeekableTimescale = (int) field.getVarint();+ break;+ case 14:+ maxSeekableTimeTicks = field.getVarint();+ break;+ case 15:+ maxSeekableTimescale = (int) field.getVarint();+ break;+ default:+ break;+ }+ }+ return new SabrLiveMetadata(broadcastId, headSequenceNumber, headTimeMs, wallTimeMs,+ videoId, postLiveDvr, headm, minSeekableTimeTicks, minSeekableTimescale,+ maxSeekableTimeTicks, maxSeekableTimescale);+ }++ /** Latest segment the live edge has reached, or -1 if unknown. */+ public long getHeadSequenceNumber() {+ return headSequenceNumber;+ }++ /** Wall-clock-ish position (ms) of the live head, or -1 if unknown. */+ public long getHeadTimeMs() {+ return headTimeMs;+ }++ public long getWallTimeMs() {+ return wallTimeMs;+ }++ /** True for an ended live stream still seekable as DVR. */+ public boolean isPostLiveDvr() {+ return postLiveDvr;+ }++ @Nullable+ public String getBroadcastId() {+ return broadcastId;+ }++ public long getMinSeekableTimeTicks() {+ return minSeekableTimeTicks;+ }++ public int getMinSeekableTimescale() {+ return minSeekableTimescale;+ }++ public long getMaxSeekableTimeTicks() {+ return maxSeekableTimeTicks;+ }++ public int getMaxSeekableTimescale() {+ return maxSeekableTimescale;+ }++ @Nonnull+ public String summarize() {+ return "broadcastIdLength=" + (broadcastId == null ? 0 : broadcastId.length())+ + ", headSeq=" + headSequenceNumber+ + ", headTimeMs=" + headTimeMs+ + ", wallTimeMs=" + wallTimeMs+ + ", videoIdLength=" + (videoId == null ? 0 : videoId.length())+ + ", postLiveDvr=" + postLiveDvr+ + ", headm=" + headm+ + ", minSeekable=" + minSeekableTimeTicks + '/' + minSeekableTimescale+ + ", maxSeekable=" + maxSeekableTimeTicks + '/' + maxSeekableTimescale;+ }+}
youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/sabr/SabrMediaHeader.java
diff --git a/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/sabr/SabrMediaHeader.java b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/sabr/SabrMediaHeader.javanew file mode 100644index 0000000000..968b3e3732--- /dev/null+++ b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/sabr/SabrMediaHeader.java@@ -0,0 +1,335 @@+package org.schabi.newpipe.extractor.services.youtube.sabr;++import javax.annotation.Nonnull;+import javax.annotation.Nullable;++public final class SabrMediaHeader {+ private final int headerId;+ @Nullable+ private final String videoId;+ private final int itag;+ private final long lastModified;+ @Nullable+ private final String xtags;+ private final long startRange;+ private final int compressionAlgorithm;+ private final boolean initSegment;+ private final int sequenceNumber;+ private final long bitrateBps;+ private final long startMs;+ private final long durationMs;+ private final long contentLength;+ private final long timeRangeStartTicks;+ private final long timeRangeDurationTicks;+ private final int timeRangeTimescale;+ private final long sequenceLastModified;++ private SabrMediaHeader(final int headerId,+ @Nullable final String videoId,+ final int itag,+ final long lastModified,+ @Nullable final String xtags,+ final long startRange,+ final int compressionAlgorithm,+ final boolean initSegment,+ final int sequenceNumber,+ final long bitrateBps,+ final long startMs,+ final long durationMs,+ final long contentLength,+ final long timeRangeStartTicks,+ final long timeRangeDurationTicks,+ final int timeRangeTimescale,+ final long sequenceLastModified) {+ this.headerId = headerId;+ this.videoId = videoId;+ this.itag = itag;+ this.lastModified = lastModified;+ this.xtags = xtags;+ this.startRange = startRange;+ this.compressionAlgorithm = compressionAlgorithm;+ this.initSegment = initSegment;+ this.sequenceNumber = sequenceNumber;+ this.bitrateBps = bitrateBps;+ this.startMs = startMs;+ this.durationMs = durationMs;+ this.contentLength = contentLength;+ this.timeRangeStartTicks = timeRangeStartTicks;+ this.timeRangeDurationTicks = timeRangeDurationTicks;+ this.timeRangeTimescale = timeRangeTimescale;+ this.sequenceLastModified = sequenceLastModified;+ }++ @Nonnull+ public static SabrMediaHeader normalized(final int headerId,+ @Nullable final String videoId,+ final int itag, final long lastModified,+ @Nullable final String xtags,+ final long startRange, final int compressionAlgorithm,+ final boolean initSegment, final int sequenceNumber,+ final long bitrateBps, final long startMs,+ final long durationMs, final long contentLength,+ final long timeRangeStartTicks,+ final long timeRangeDurationTicks,+ final int timeRangeTimescale,+ final long sequenceLastModified) {+ return new SabrMediaHeader(headerId, videoId, itag, lastModified, xtags, startRange,+ compressionAlgorithm, initSegment, sequenceNumber, bitrateBps, startMs, durationMs,+ contentLength, timeRangeStartTicks, timeRangeDurationTicks, timeRangeTimescale,+ sequenceLastModified);+ }++ @Nonnull+ static SabrMediaHeader decode(@Nonnull final byte[] data) throws SabrProtocolException {+ int headerId = -1;+ String videoId = null;+ int itag = -1;+ long lastModified = -1;+ String xtags = null;+ long startRange = -1;+ int compressionAlgorithm = -1;+ boolean initSegment = false;+ int sequenceNumber = -1;+ long bitrateBps = -1;+ long startMs = -1;+ long durationMs = -1;+ long contentLength = -1;+ long timeRangeStartTicks = -1;+ long timeRangeDurationTicks = -1;+ int timeRangeTimescale = -1;+ long sequenceLastModified = -1;++ for (final SabrProto.Field field : SabrProto.readFields(data)) {+ switch (field.getNumber()) {+ case 1:+ headerId = (int) field.getVarint();+ break;+ case 2:+ videoId = field.getString();+ break;+ case 3:+ itag = (int) field.getVarint();+ break;+ case 4:+ lastModified = field.getVarint();+ break;+ case 5:+ xtags = field.getString();+ break;+ case 6:+ startRange = field.getVarint();+ break;+ case 7:+ compressionAlgorithm = (int) field.getVarint();+ break;+ case 8:+ initSegment = field.getVarint() != 0;+ break;+ case 9:+ sequenceNumber = (int) field.getVarint();+ break;+ case 10:+ bitrateBps = field.getVarint();+ break;+ case 11:+ startMs = field.getVarint();+ break;+ case 12:+ durationMs = field.getVarint();+ break;+ case 13:+ final FormatId formatId = decodeFormatId(field.getBytes());+ if (itag < 0) {+ itag = formatId.itag;+ }+ if (lastModified < 0) {+ lastModified = formatId.lastModified;+ }+ if (xtags == null) {+ xtags = formatId.xtags;+ }+ break;+ case 14:+ contentLength = field.getVarint();+ break;+ case 15:+ final TimeRange timeRange = decodeTimeRange(field.getBytes());+ timeRangeStartTicks = timeRange.startTicks;+ timeRangeDurationTicks = timeRange.durationTicks;+ timeRangeTimescale = timeRange.timescale;+ break;+ case 16:+ sequenceLastModified = field.getVarint();+ break;+ default:+ break;+ }+ }++ if (timeRangeTimescale > 0) {+ if (startMs < 0 && timeRangeStartTicks >= 0) {+ startMs = timeRangeStartTicks * 1000L / timeRangeTimescale;+ }+ if (durationMs < 0 && timeRangeDurationTicks >= 0) {+ durationMs = timeRangeDurationTicks * 1000L / timeRangeTimescale;+ }+ }++ return new SabrMediaHeader(headerId, videoId, itag, lastModified, xtags, startRange,+ compressionAlgorithm, initSegment, sequenceNumber, bitrateBps, startMs, durationMs,+ contentLength, timeRangeStartTicks, timeRangeDurationTicks, timeRangeTimescale,+ sequenceLastModified);+ }++ @Nonnull+ private static FormatId decodeFormatId(@Nonnull final byte[] data) throws SabrProtocolException {+ int itag = -1;+ long lastModified = -1;+ String xtags = null;+ for (final SabrProto.Field field : SabrProto.readFields(data)) {+ if (field.getNumber() == 1 && field.getWireType() == SabrProto.WIRE_VARINT) {+ itag = (int) field.getVarint();+ } else if (field.getNumber() == 2 && field.getWireType() == SabrProto.WIRE_VARINT) {+ lastModified = field.getVarint();+ } else if (field.getNumber() == 3+ && field.getWireType() == SabrProto.WIRE_LENGTH_DELIMITED) {+ xtags = field.getString();+ }+ }+ return new FormatId(itag, lastModified, xtags);+ }++ @Nonnull+ private static TimeRange decodeTimeRange(@Nonnull final byte[] data)+ throws SabrProtocolException {+ long startTicks = -1;+ long durationTicks = -1;+ int timescale = -1;+ for (final SabrProto.Field field : SabrProto.readFields(data)) {+ if (field.getNumber() == 1 && field.getWireType() == SabrProto.WIRE_VARINT) {+ startTicks = field.getVarint();+ } else if (field.getNumber() == 2 && field.getWireType() == SabrProto.WIRE_VARINT) {+ durationTicks = field.getVarint();+ } else if (field.getNumber() == 3 && field.getWireType() == SabrProto.WIRE_VARINT) {+ timescale = (int) field.getVarint();+ }+ }+ return new TimeRange(startTicks, durationTicks, timescale);+ }++ public int getHeaderId() {+ return headerId;+ }++ @Nullable+ public String getVideoId() {+ return videoId;+ }++ public int getItag() {+ return itag;+ }++ public long getLastModified() {+ return lastModified;+ }++ @Nullable+ public String getXtags() {+ return xtags;+ }++ public long getStartRange() {+ return startRange;+ }++ public int getCompressionAlgorithm() {+ return compressionAlgorithm;+ }++ public boolean isInitSegment() {+ return initSegment;+ }++ public int getSequenceNumber() {+ return sequenceNumber;+ }++ public long getBitrateBps() {+ return bitrateBps;+ }++ public long getStartMs() {+ return startMs;+ }++ public long getDurationMs() {+ return durationMs;+ }++ public long getContentLength() {+ return contentLength;+ }++ public long getTimeRangeStartTicks() {+ return timeRangeStartTicks;+ }++ public long getTimeRangeDurationTicks() {+ return timeRangeDurationTicks;+ }++ public int getTimeRangeTimescale() {+ return timeRangeTimescale;+ }++ public long getSequenceLastModified() {+ return sequenceLastModified;+ }++ @Nonnull+ public String summarize() {+ return "id=" + headerId+ + ", itag=" + itag+ + ", init=" + initSegment+ + ", seq=" + sequenceNumber+ + ", startRange=" + startRange+ + ", startMs=" + startMs+ + ", durationMs=" + durationMs+ + ", contentLength=" + contentLength+ + ", compression=" + compressionAlgorithm+ + ", bitrateBps=" + bitrateBps+ + ", timeRange=" + timeRangeStartTicks + '+' + timeRangeDurationTicks+ + '/' + timeRangeTimescale+ + ", sequenceLmt=" + sequenceLastModified;+ }++ private static final class FormatId {+ private final int itag;+ private final long lastModified;+ @Nullable+ private final String xtags;++ private FormatId(final int itag,+ final long lastModified,+ @Nullable final String xtags) {+ this.itag = itag;+ this.lastModified = lastModified;+ this.xtags = xtags;+ }+ }++ private static final class TimeRange {+ private final long startTicks;+ private final long durationTicks;+ private final int timescale;++ private TimeRange(final long startTicks,+ final long durationTicks,+ final int timescale) {+ this.startTicks = startTicks;+ this.durationTicks = durationTicks;+ this.timescale = timescale;+ }+ }+}
youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/sabr/SabrMediaProtocol.java
diff --git a/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/sabr/SabrMediaProtocol.java b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/sabr/SabrMediaProtocol.javanew file mode 100644index 0000000000..233e2a023d--- /dev/null+++ b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/sabr/SabrMediaProtocol.java@@ -0,0 +1,31 @@+package org.schabi.newpipe.extractor.services.youtube.sabr;++import javax.annotation.Nonnull;++/** Host-facing media envelope operations. Control policy code never receives media payloads. */+public interface SabrMediaProtocol {+ int getHeaderPartType();+ int getMediaPartType();+ int getEndPartType();++ @Nonnull+ SabrMediaHeader decodeHeader(@Nonnull byte[] payload) throws SabrProtocolException;++ @Nonnull+ static SabrMediaProtocol builtin() {+ return BuiltinHolder.INSTANCE;+ }++ final class BuiltinHolder {+ private static final SabrMediaProtocol INSTANCE = new SabrMediaProtocol() {+ @Override public int getHeaderPartType() { return SabrResponseDecoder.MEDIA_HEADER; }+ @Override public int getMediaPartType() { return SabrResponseDecoder.MEDIA; }+ @Override public int getEndPartType() { return SabrResponseDecoder.MEDIA_END; }+ @Nonnull @Override public SabrMediaHeader decodeHeader(@Nonnull final byte[] payload)+ throws SabrProtocolException {+ return SabrMediaHeader.decode(payload);+ }+ };+ private BuiltinHolder() { }+ }+}
youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/sabr/SabrMediaSegment.java
diff --git a/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/sabr/SabrMediaSegment.java b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/sabr/SabrMediaSegment.javanew file mode 100644index 0000000000..b5dc7f4628--- /dev/null+++ b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/sabr/SabrMediaSegment.java@@ -0,0 +1,333 @@+package org.schabi.newpipe.extractor.services.youtube.sabr;++import javax.annotation.Nonnull;+import javax.annotation.Nullable;+import java.io.ByteArrayInputStream;+import java.io.ByteArrayOutputStream;+import java.io.File;+import java.io.FileInputStream;+import java.io.IOException;+import java.io.InputStream;+import java.io.InterruptedIOException;+import java.io.RandomAccessFile;++public final class SabrMediaSegment {+ private static final int COPY_BUFFER_SIZE = 8192;++ @Nonnull+ private final SabrMediaHeader header;+ @Nullable+ private final byte[] data;+ @Nullable+ private final File file;+ private final int length;+ @Nullable+ private final ProgressiveFileState progressiveState;++ SabrMediaSegment(@Nonnull final SabrMediaHeader header, @Nonnull final byte[] data) {+ this.header = header;+ // No defensive copy: the collector hands over a freshly built array it does not retain.+ // Media segments reach several MB (4K), so cloning here doubled peak memory and caused OOM+ // under rapid switching. The array is treated as immutable from here on.+ this.data = data;+ this.file = null;+ this.length = data.length;+ this.progressiveState = null;+ }++ SabrMediaSegment(@Nonnull final SabrMediaHeader header,+ @Nonnull final File file,+ final int length) {+ this.header = header;+ this.data = null;+ this.file = file;+ this.length = length;+ this.progressiveState = null;+ }++ private SabrMediaSegment(@Nonnull final SabrMediaHeader header,+ @Nonnull final File file,+ final int length,+ @Nonnull final ProgressiveFileState progressiveState) {+ this.header = header;+ this.data = null;+ this.file = file;+ this.length = length;+ this.progressiveState = progressiveState;+ }++ @Nonnull+ static SabrMediaSegment progressive(@Nonnull final SabrMediaHeader header,+ @Nonnull final File file,+ final int length) {+ return new SabrMediaSegment(header, file, length, new ProgressiveFileState(length));+ }++ @Nonnull+ public SabrMediaHeader getHeader() {+ return header;+ }++ /**+ * Read-only: callers must not mutate the returned array. Disk-backed segments are loaded only+ * for legacy callers; playback should use {@link #openStream()} to avoid pulling large media+ * segments back onto the Java heap.+ */+ @Nonnull+ public byte[] getData() {+ if (data != null) {+ return data;+ }+ try (InputStream input = openStream();+ ByteArrayOutputStream output = new ByteArrayOutputStream(length)) {+ final byte[] buffer = new byte[COPY_BUFFER_SIZE];+ int read;+ while ((read = input.read(buffer)) != -1) {+ output.write(buffer, 0, read);+ }+ return output.toByteArray();+ } catch (final IOException e) {+ throw new IllegalStateException("Could not read disk-backed SABR media segment", e);+ }+ }++ @Nonnull+ public InputStream openStream() throws IOException {+ if (data != null) {+ return new ByteArrayInputStream(data);+ }+ if (file == null) {+ throw new IOException("SABR media segment has no backing data");+ }+ if (progressiveState != null) {+ progressiveState.throwIfFailed();+ try {+ return new ProgressiveFileInputStream(file, progressiveState);+ } catch (final IOException e) {+ progressiveState.throwIfFailed();+ throw e;+ }+ }+ return new FileInputStream(file);+ }++ public boolean isDiskBacked() {+ return file != null;+ }++ public boolean isComplete() {+ return progressiveState == null || progressiveState.isComplete();+ }++ public boolean hasFailed() {+ return progressiveState != null && progressiveState.hasFailed();+ }++ void onBytesWritten(final int count) {+ if (progressiveState != null) {+ progressiveState.onBytesWritten(count);+ }+ }++ void completeProgressive() {+ if (progressiveState != null) {+ progressiveState.complete();+ }+ }++ void failProgressive(@Nonnull final IOException failure) {+ if (progressiveState != null) {+ progressiveState.fail(failure);+ }+ }++ public void delete() {+ failProgressive(new IOException("SABR media segment was discarded"));+ if (file != null && !file.delete() && file.exists()) {+ file.deleteOnExit();+ }+ }++ public int getLength() {+ return length;+ }++ @Nullable+ File getFile() {+ return file;+ }++ private static final class ProgressiveFileState {+ private final int expectedLength;+ private int bytesWritten;+ private boolean complete;+ @Nullable+ private IOException failure;++ private ProgressiveFileState(final int expectedLength) {+ this.expectedLength = expectedLength;+ }++ private synchronized void onBytesWritten(final int count) {+ if (count <= 0 || complete || failure != null) {+ return;+ }+ bytesWritten += count;+ notifyAll();+ }++ private synchronized void complete() {+ if (failure == null) {+ complete = true;+ }+ notifyAll();+ }++ private synchronized void fail(@Nonnull final IOException exception) {+ if (!complete && failure == null) {+ failure = exception;+ }+ notifyAll();+ }++ private synchronized boolean isComplete() {+ return complete;+ }++ private synchronized boolean hasFailed() {+ return failure != null;+ }++ private synchronized int awaitAvailable(+ final long position,+ @Nonnull final ProgressiveFileInputStream reader) throws IOException {+ int readable = readableBytes(position);+ while (readable <= 0 && !complete && failure == null && !reader.closed) {+ try {+ wait();+ } catch (final InterruptedException e) {+ Thread.currentThread().interrupt();+ final InterruptedIOException interrupted = new InterruptedIOException(+ "Interrupted waiting for SABR media bytes");+ interrupted.initCause(e);+ throw interrupted;+ }+ readable = readableBytes(position);+ }+ if (reader.closed) {+ throw new InterruptedIOException("SABR media stream was closed");+ }+ if (failure != null) {+ throw failure;+ }+ return complete ? (int) Math.max(0, bytesWritten - position) : readable;+ }++ private synchronized int available(final long position) throws IOException {+ if (failure != null) {+ throw failure;+ }+ return complete ? (int) Math.max(0, bytesWritten - position)+ : readableBytes(position);+ }++ private int readableBytes(final long position) {+ final int available = (int) Math.max(0, bytesWritten - position);+ if (!complete && bytesWritten >= expectedLength+ && position + available >= expectedLength) {+ // Keep one byte unavailable until MEDIA_END validates the segment. Media3 knows+ // the declared DataSource length and may never issue a separate EOF read.+ return Math.max(0, available - 1);+ }+ return available;+ }++ private synchronized void signalReaders() {+ notifyAll();+ }++ private synchronized void throwIfFailed() throws IOException {+ if (failure != null) {+ throw failure;+ }+ }+ }++ private static final class ProgressiveFileInputStream extends InputStream {+ @Nonnull+ private final RandomAccessFile input;+ @Nonnull+ private final ProgressiveFileState state;+ private long position;+ private volatile boolean closed;++ private ProgressiveFileInputStream(@Nonnull final File file,+ @Nonnull final ProgressiveFileState state)+ throws IOException {+ this.input = new RandomAccessFile(file, "r");+ this.state = state;+ }++ @Override+ public int read() throws IOException {+ final byte[] one = new byte[1];+ final int read = read(one, 0, 1);+ return read < 0 ? -1 : one[0] & 0xff;+ }++ @Override+ public int read(@Nonnull final byte[] bytes, final int offset, final int count)+ throws IOException {+ if (closed) {+ throw new IOException("SABR media stream is closed");+ }+ if (count == 0) {+ return 0;+ }+ while (true) {+ final int available = state.awaitAvailable(position, this);+ if (available <= 0) {+ return -1;+ }+ input.seek(position);+ final int read = input.read(bytes, offset, Math.min(count, available));+ if (read > 0) {+ position += read;+ return read;+ }+ }+ }++ @Override+ public long skip(final long count) throws IOException {+ if (count <= 0) {+ return 0;+ }+ final int available = state.awaitAvailable(position, this);+ if (available <= 0) {+ return 0;+ }+ final long skipped = Math.min(count, available);+ position += skipped;+ input.seek(position);+ return skipped;+ }++ @Override+ public int available() throws IOException {+ if (closed) {+ return 0;+ }+ return state.available(position);+ }++ @Override+ public void close() throws IOException {+ if (!closed) {+ closed = true;+ state.signalReaders();+ input.close();+ }+ }+ }+}
youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/sabr/SabrMediaSegmentCollector.java
diff --git a/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/sabr/SabrMediaSegmentCollector.java b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/sabr/SabrMediaSegmentCollector.javanew file mode 100644index 0000000000..c29c4c5a31--- /dev/null+++ b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/sabr/SabrMediaSegmentCollector.java@@ -0,0 +1,487 @@+package org.schabi.newpipe.extractor.services.youtube.sabr;++import org.brotli.dec.BrotliI
Diff truncated.