youpipe: sabr solved
- Commit
63c645865f4e5f8eeafc8a1e677baef06269860d- Author
- Vayun Mathur <[email protected]>
- When
- 2026-07-22 22:10 UTC (4 months ago)
- Parents
7ca4ab7
Diff
youpipe/build.gradle.kts
diff --git a/youpipe/build.gradle.kts b/youpipe/build.gradle.ktsindex aa3cbe1ec7..36046f9d3f 100644--- a/youpipe/build.gradle.kts+++ b/youpipe/build.gradle.kts@@ -45,6 +45,7 @@ dependencies { implementation(libs.androidx.compose.runtime.livedata) implementation(project(":library:network"))+ implementation(libs.okhttp) testImplementation(libs.junit) }\ No newline at end of file
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.javaindex 2abdb57a39..b12934167b 100644--- 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.java@@ -1,26 +1,322 @@ package org.schabi.newpipe.extractor.services.youtube; -import java.util.Map;+import com.grack.nanojson.JsonArray;+import com.grack.nanojson.JsonObject;+import com.grack.nanojson.JsonParser;+import com.grack.nanojson.JsonParserException;+import org.schabi.newpipe.extractor.NewPipe;+import org.schabi.newpipe.extractor.downloader.Response;+import org.schabi.newpipe.extractor.exceptions.ParsingException;+import org.schabi.newpipe.extractor.localization.Localization; import javax.annotation.Nonnull;+import javax.annotation.Nullable;+import java.io.IOException;+import java.net.URLEncoder;+import java.nio.charset.StandardCharsets;+import java.util.Collections;+import java.util.HashMap;+import java.util.List;+import java.util.Map; /**- * Holder for batch signature / n-parameter decoding results.+ * Decoder for YouTube signature and throttling parameters using the PipePipe API. *- * <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>+ * <p>+ * This class replaces the local JavaScript-based decoding with API calls to+ * https://api.pipepipe.dev/decoder/decode+ * </p> */ public final class YoutubeApiDecoder { + private static final String API_BASE_URL = "https://api.pipepipe.dev/decoder/decode";+ private static final String USER_AGENT = "PipePipe/4.9.0";++ @Nonnull+ private static final Map<String, String> DECODE_CACHE = new HashMap<>();++ @Nullable+ private static volatile YoutubeJavaScriptDecoder localDecoder;+ private YoutubeApiDecoder() { } /**- * Result class for batch decode operations: maps of obfuscated value to decoded value.+ * Decode a signature parameter using the PipePipe API.+ *+ * @param playerId the YouTube player ID (8-character hash)+ * @param signature the obfuscated signature to decode+ * @return the deobfuscated signature+ * @throws ParsingException if the API call fails or returns invalid data+ */+ @Nonnull+ static String decodeSignature(@Nonnull final String playerId,+ @Nonnull final String signature) throws ParsingException {+ return decode(playerId, "sig", signature);+ }++ /**+ * Decode a throttling parameter (n parameter) using the PipePipe API.+ *+ * @param playerId the YouTube player ID (8-character hash)+ * @param nParameter the obfuscated n parameter to decode+ * @return the deobfuscated n parameter+ * @throws ParsingException if the API call fails or returns invalid data+ */+ @Nonnull+ static String decodeThrottlingParameter(@Nonnull final String playerId,+ @Nonnull final String nParameter)+ throws ParsingException {+ return decode(playerId, "n", nParameter);+ }++ /**+ * Generic decode method that calls the PipePipe API.+ *+ * @param playerId the YouTube player ID (8-character hash)+ * @param paramType the parameter type ("sig" or "n")+ * @param value the obfuscated value to decode+ * @return the deobfuscated value+ * @throws ParsingException if the API call fails or returns invalid data+ */+ @Nonnull+ private static String decode(@Nonnull final String playerId,+ @Nonnull final String paramType,+ @Nonnull final String value) throws ParsingException {+ final String cacheKey = playerId + ":" + paramType + ":" + value;+ final String cachedResult = DECODE_CACHE.get(cacheKey);+ if (cachedResult != null) {+ return cachedResult;+ }++ final YoutubeJavaScriptDecoder decoder = localDecoder;+ if (decoder != null) {+ try {+ final BatchDecodeResult result = decoder.decodeBatch(playerId,+ "sig".equals(paramType) ? Collections.singletonList(value) : null,+ "n".equals(paramType) ? Collections.singletonList(value) : null);+ final String decodedValue = "sig".equals(paramType)+ ? result.getSignatures().get(value) : result.getNParameters().get(value);+ if (decodedValue == null || decodedValue.isEmpty()) {+ throw new ParsingException("Local decoder returned empty value for: " + value);+ }+ DECODE_CACHE.put(cacheKey, decodedValue);+ return decodedValue;+ } catch (final Exception localFailure) {+ disableLocalDecoder(decoder);+ }+ }++ try {+ final String encodedValue = URLEncoder.encode(value, StandardCharsets.UTF_8.name());+ final String url = API_BASE_URL + "?player=" + playerId + "&" + paramType + "=" + encodedValue;++ final Map<String, java.util.List<String>> headers = new HashMap<>();+ headers.put("User-Agent", Collections.singletonList(USER_AGENT));++ final Response response = NewPipe.getDownloader().get(url, headers, Localization.DEFAULT);+ final String responseBody = response.responseBody();+ final JsonObject jsonResponse = JsonParser.object().from(responseBody);++ if (!"result".equals(jsonResponse.getString("type"))) {+ throw new ParsingException("API returned unexpected type: " + jsonResponse.getString("type"));+ }++ final JsonObject firstResponse = jsonResponse.getArray("responses").getObject(0);+ if (!"result".equals(firstResponse.getString("type"))) {+ throw new ParsingException("API response item has unexpected type: " + firstResponse.getString("type"));+ }++ final JsonObject data = firstResponse.getObject("data");+ final String decodedValue = data.getString(value);++ if (decodedValue == null || decodedValue.isEmpty()) {+ throw new ParsingException("API returned empty decoded value for: " + value);+ }++ DECODE_CACHE.put(cacheKey, decodedValue);+ return decodedValue;+ } catch (final IOException e) {+ throw new ParsingException("Failed to call decode API", e);+ } catch (final JsonParserException e) {+ throw new ParsingException("Failed to parse API response", e);+ } catch (final Exception e) {+ throw new ParsingException("Unexpected error during decoding", e);+ }+ }++ static void clearCache() {+ DECODE_CACHE.clear();+ }++ private static void disableLocalDecoder(@Nonnull final YoutubeJavaScriptDecoder decoder) {+ if (localDecoder == decoder) {+ localDecoder = null;+ clearCache();+ }+ }++ public static void setLocalDecoder(@Nullable final YoutubeJavaScriptDecoder decoder) {+ localDecoder = decoder;+ clearCache();+ }++ @Nullable+ static YoutubeJavaScriptDecoder getLocalDecoder() {+ return localDecoder;+ }++ static int getCacheSize() {+ return DECODE_CACHE.size();+ }++ /**+ * Batch decode multiple signatures and throttling parameters in a single API call.+ *+ * @param playerId the YouTube player ID (8-character hash)+ * @param signatureParams list of obfuscated signatures to decode (can be null or empty)+ * @param nParams list of obfuscated n parameters to decode (can be null or empty)+ * @return a BatchDecodeResult containing the decoded values+ * @throws ParsingException if the API call fails or returns invalid data+ */+ @Nonnull+ static BatchDecodeResult decodeBatch(@Nonnull final String playerId,+ @Nullable final List<String> signatureParams,+ @Nullable final List<String> nParams)+ throws ParsingException {+ final YoutubeJavaScriptDecoder decoder = localDecoder;+ if (decoder != null) {+ try {+ return decoder.decodeBatch(playerId, signatureParams, nParams);+ } catch (final Exception localFailure) {+ disableLocalDecoder(decoder);+ }+ }+ // Validate input+ final boolean hasSigs = signatureParams != null && !signatureParams.isEmpty();+ final boolean hasNs = nParams != null && !nParams.isEmpty();++ if (!hasSigs && !hasNs) {+ return new BatchDecodeResult(new HashMap<>(), new HashMap<>());+ }++ final Map<String, String> sigResults = new HashMap<>();+ final Map<String, String> nResults = new HashMap<>();+ final List<String> uncachedSigs = new java.util.ArrayList<>();+ final List<String> uncachedNs = new java.util.ArrayList<>();++ if (hasSigs) {+ for (final String sig : signatureParams) {+ final String cachedResult = DECODE_CACHE.get(playerId + ":sig:" + sig);+ if (cachedResult != null) {+ sigResults.put(sig, cachedResult);+ } else {+ uncachedSigs.add(sig);+ }+ }+ }++ if (hasNs) {+ for (final String n : nParams) {+ final String cachedResult = DECODE_CACHE.get(playerId + ":n:" + n);+ if (cachedResult != null) {+ nResults.put(n, cachedResult);+ } else {+ uncachedNs.add(n);+ }+ }+ }++ if (uncachedSigs.isEmpty() && uncachedNs.isEmpty()) {+ return new BatchDecodeResult(sigResults, nResults);+ }++ try {+ final StringBuilder urlBuilder = new StringBuilder(API_BASE_URL);+ urlBuilder.append("?player=").append(playerId);++ if (!uncachedNs.isEmpty()) {+ urlBuilder.append("&n=");+ for (int i = 0; i < uncachedNs.size(); i++) {+ if (i > 0) {+ urlBuilder.append(',');+ }+ urlBuilder.append(URLEncoder.encode(uncachedNs.get(i), StandardCharsets.UTF_8.name()));+ }+ }++ if (!uncachedSigs.isEmpty()) {+ urlBuilder.append("&sig=");+ for (int i = 0; i < uncachedSigs.size(); i++) {+ if (i > 0) {+ urlBuilder.append(',');+ }+ urlBuilder.append(URLEncoder.encode(uncachedSigs.get(i), StandardCharsets.UTF_8.name()));+ }+ }++ final Map<String, java.util.List<String>> headers = new HashMap<>();+ headers.put("User-Agent", Collections.singletonList(USER_AGENT));++ final Response response = NewPipe.getDownloader().get(urlBuilder.toString(), headers, Localization.DEFAULT);+ final String responseBody = response.responseBody();+ final JsonObject jsonResponse = JsonParser.object().from(responseBody);++ if (!"result".equals(jsonResponse.getString("type"))) {+ throw new ParsingException("API returned unexpected type: " + jsonResponse.getString("type"));+ }++ final JsonArray responses = jsonResponse.getArray("responses");++ int responseIndex = 0;+ if (!uncachedNs.isEmpty()) {+ final JsonObject nResponse = responses.getObject(responseIndex++);+ if (!"result".equals(nResponse.getString("type"))) {+ throw new ParsingException("N parameter response has unexpected type: " + nResponse.getString("type"));+ }++ final JsonObject nData = nResponse.getObject("data");+ for (final String nParam : uncachedNs) {+ final String decodedValue = nData.getString(nParam);+ if (decodedValue == null || decodedValue.isEmpty()) {+ throw new ParsingException("API returned empty decoded value for n parameter: " + nParam);+ }+ nResults.put(nParam, decodedValue);+ DECODE_CACHE.put(playerId + ":n:" + nParam, decodedValue);+ }+ }++ if (!uncachedSigs.isEmpty()) {+ final JsonObject sigResponse = responses.getObject(responseIndex);+ if (!"result".equals(sigResponse.getString("type"))) {+ throw new ParsingException("Signature response has unexpected type: " + sigResponse.getString("type"));+ }++ final JsonObject sigData = sigResponse.getObject("data");+ for (final String sig : uncachedSigs) {+ final String decodedValue = sigData.getString(sig);+ if (decodedValue == null || decodedValue.isEmpty()) {+ throw new ParsingException("API returned empty decoded value for signature: " + sig);+ }+ sigResults.put(sig, decodedValue);+ DECODE_CACHE.put(playerId + ":sig:" + sig, decodedValue);+ }+ }++ return new BatchDecodeResult(sigResults, nResults);+ } catch (final IOException e) {+ throw new ParsingException("Failed to call batch decode API", e);+ } catch (final JsonParserException e) {+ throw new ParsingException("Failed to parse batch API response", e);+ } catch (final Exception e) {+ throw new ParsingException("Unexpected error during batch decoding", e);+ }+ }++ /**+ * Result class for batch decode operations. */- public static final class BatchDecodeResult {+ public static class BatchDecodeResult { private final Map<String, String> signatures; private final Map<String, String> nParameters;
youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/YoutubeJavaScriptDecoder.java
diff --git a/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/YoutubeJavaScriptDecoder.java b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/YoutubeJavaScriptDecoder.javanew file mode 100644index 0000000000..4890d8ed64--- /dev/null+++ b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/YoutubeJavaScriptDecoder.java@@ -0,0 +1,39 @@+package org.schabi.newpipe.extractor.services.youtube;++import org.schabi.newpipe.extractor.exceptions.ParsingException;++import java.util.List;++import javax.annotation.Nonnull;+import javax.annotation.Nullable;++public interface YoutubeJavaScriptDecoder {+ @Nonnull+ PlayerData getPlayerData(@Nonnull String videoId) throws ParsingException;++ @Nonnull+ YoutubeApiDecoder.BatchDecodeResult decodeBatch(+ @Nonnull String playerId,+ @Nullable List<String> signatures,+ @Nullable List<String> throttlingParameters) throws ParsingException;++ final class PlayerData {+ @Nonnull+ private final String playerId;+ private final int signatureTimestamp;++ public PlayerData(@Nonnull final String playerId, final int signatureTimestamp) {+ this.playerId = playerId;+ this.signatureTimestamp = signatureTimestamp;+ }++ @Nonnull+ public String getPlayerId() {+ return playerId;+ }++ public int getSignatureTimestamp() {+ return signatureTimestamp;+ }+ }+}
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 df054e7544..61c3932b71 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@@ -1,16 +1,23 @@ package org.schabi.newpipe.extractor.services.youtube; -import static org.schabi.newpipe.extractor.utils.Utils.isNullOrEmpty;-+import com.grack.nanojson.JsonObject;+import com.grack.nanojson.JsonParser;+import com.grack.nanojson.JsonParserException;+import org.schabi.newpipe.extractor.NewPipe;+import org.schabi.newpipe.extractor.downloader.Response; import org.schabi.newpipe.extractor.exceptions.ParsingException;-import org.schabi.newpipe.extractor.utils.JavaScript;+import org.schabi.newpipe.extractor.exceptions.ReCaptchaException;+import org.schabi.newpipe.extractor.localization.Localization;+import org.schabi.newpipe.extractor.utils.Parser; import javax.annotation.Nonnull; import javax.annotation.Nullable;+import java.io.IOException;+import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map;-import java.util.Objects;+import java.util.regex.Pattern; /** * Manage the extraction and the usage of YouTube's player JavaScript needed data in the YouTube@@ -25,31 +32,20 @@ import java.util.Objects; * <p> * This class provides access to methods which allows to get base JavaScript player's signature * timestamp and to deobfuscate streaming URLs' signature and/or throttling parameter of HTML5- * clients.+ * clients using the PipePipe API. * </p> */ public final class YoutubeJavaScriptPlayerManager { - @Nonnull- private static final Map<String, String> CACHED_THROTTLING_PARAMETERS = new HashMap<>();-- private static String cachedJavaScriptPlayerCode;+ private static final Pattern THROTTLING_PARAM_PATTERN = Pattern.compile("[&?]n=([^&]+)"); - @Nullable- private static Integer cachedSignatureTimestamp;- @Nullable- private static String cachedSignatureDeobfuscationFunction;- @Nullable- private static String cachedThrottlingDeobfuscationFunctionName;- @Nullable- private static String cachedThrottlingDeobfuscationFunction;+ private static final String LATEST_PLAYER_URL =+ "https://api.pipepipe.dev/decoder/latest-player";+ private static final String USER_AGENT = "PipePipe/4.9.0";+ private static final long PLAYER_METADATA_TTL_MILLIS = 24L * 60L * 60L * 1000L; @Nullable- private static ParsingException throttlingDeobfFuncExtractionEx;- @Nullable- private static ParsingException sigDeobFuncExtractionEx;- @Nullable- private static ParsingException sigTimestampExtractionEx;+ private static PlayerMetadata playerMetadata; private YoutubeJavaScriptPlayerManager() { }@@ -63,118 +59,53 @@ public final class YoutubeJavaScriptPlayerManager { * </p> * * <p>- * The base JavaScript player file will fetched if it is not already done.+ * The signature timestamp is loaded together with the player ID from the decoder API. * </p> * * <p>- * The result of the extraction is cached until {@link #clearAllCaches()} is called, making- * subsequent calls faster.+ * The metadata is reused for up to 24 hours before being refreshed from the API. * </p> * * @param videoId the video ID used to get the JavaScript base player file (an empty one can be * passed, even it is not recommend in order to spoof better official YouTube * clients) * @return the signature timestamp of the base JavaScript player file- * @throws ParsingException if the extraction of the base JavaScript player file or the- * signature timestamp failed+ * @throws ParsingException if the extraction of the signature timestamp failed */ @Nonnull public static Integer getSignatureTimestamp(@Nonnull final String videoId) throws ParsingException {- // Return the cached result if it is present- if (cachedSignatureTimestamp != null) {- return cachedSignatureTimestamp;- }-- // If the signature timestamp has been not extracted on a previous call, this mean that we- // will fail to extract it on next calls too if the player code has been not changed- // Throw again the corresponding stored exception in this case to improve performance- if (sigTimestampExtractionEx != null) {- throw sigTimestampExtractionEx;- }-- extractJavaScriptCodeIfNeeded(videoId);-- try {- cachedSignatureTimestamp = Integer.valueOf(- YoutubeSignatureUtils.getSignatureTimestamp(cachedJavaScriptPlayerCode));- } catch (final ParsingException e) {- // Store the exception for future calls of this method, in order to improve performance- sigTimestampExtractionEx = e;- throw e;- } catch (final NumberFormatException e) {- sigTimestampExtractionEx =- new ParsingException("Could not convert signature timestamp to a number", e);- } catch (final Exception e) {- sigTimestampExtractionEx = new ParsingException("Could not get signature timestamp", e);- throw e;- }-- return cachedSignatureTimestamp;+ final long startedAtNanos = System.nanoTime();+ final int signatureTimestamp = getPlayerMetadata(videoId).signatureTimestamp;+ logPerformance(videoId, "ejs.signatureTimestamp", startedAtNanos);+ return signatureTimestamp; } /**- * Deobfuscate a signature of a streaming URL using its corresponding JavaScript base player's- * function.+ * Deobfuscate a signature of a streaming URL using the PipePipe API. * * <p> * Obfuscated signatures are only present on streaming URLs of some videos with HTML5 clients. * </p> *- * @param videoId the video ID used to get the JavaScript base player file (an+ * @param videoId the video ID used to get the JavaScript base player ID (an * empty one can be passed, even it is not recommend in order to * spoof better official YouTube clients) * @param obfuscatedSignature the obfuscated signature of a streaming URL * @return the deobfuscated signature- * @throws ParsingException if the extraction of the base JavaScript player file or the- * signature deobfuscation function failed+ * @throws ParsingException if the extraction of the player ID or the API call failed */ @Nonnull public static String deobfuscateSignature(@Nonnull final String videoId, @Nonnull final String obfuscatedSignature) throws ParsingException {- // If the signature deobfuscation function has been not extracted on a previous call, this- // mean that we will fail to extract it on next calls too if the player code has been not- // changed- // Throw again the corresponding stored exception in this case to improve performance- if (sigDeobFuncExtractionEx != null) {- throw sigDeobFuncExtractionEx;- }-- extractJavaScriptCodeIfNeeded(videoId);-- if (cachedSignatureDeobfuscationFunction == null) {- try {- cachedSignatureDeobfuscationFunction = YoutubeSignatureUtils.getDeobfuscationCode(- cachedJavaScriptPlayerCode);- } catch (final ParsingException e) {- // Store the exception for future calls of this method, in order to improve- // performance- sigDeobFuncExtractionEx = e;- throw e;- } catch (final Exception e) {- sigDeobFuncExtractionEx = new ParsingException(- "Could not get signature parameter deobfuscation JavaScript function", e);- throw e;- }- }-- try {- // Return an empty parameter in the case the function returns null- return Objects.requireNonNullElse(- JavaScript.run(cachedSignatureDeobfuscationFunction,- YoutubeSignatureUtils.DEOBFUSCATION_FUNCTION_NAME,- obfuscatedSignature), "");- } catch (final Exception e) {- // This shouldn't happen as the function validity is checked when it is extracted- throw new ParsingException(- "Could not run signature parameter deobfuscation JavaScript function", e);- }+ return YoutubeApiDecoder.decodeSignature(+ getPlayerMetadata(videoId).playerId, obfuscatedSignature); } /** * Return a streaming URL with the throttling parameter of a given one deobfuscated, if it is- * present, using its corresponding JavaScript base player's function.+ * present, using the PipePipe API. * * <p> * The throttling parameter is present on all streaming URLs of HTML5 clients.@@ -185,263 +116,188 @@ public final class YoutubeJavaScriptPlayerManager { * KB/s) and some streaming URLs could even lead to invalid HTTP responses such a 403 one. * </p> *- * <p>- * As throttling parameters can be common between multiple streaming URLs of the same player- * response, deobfuscated parameters are cached with their obfuscated variant, in order to- * improve performance with multiple calls of this method having the same obfuscated throttling- * parameter.- * </p>- *- * <p>- * The cache's size can be get using {@link #getThrottlingParametersCacheSize()} and the cache- * can be cleared using {@link #clearThrottlingParametersCache()} or {@link #clearAllCaches()}.- * </p>- *- * @param videoId the video ID used to get the JavaScript base player file (an empty one+ * @param videoId the video ID used to get the JavaScript base player ID (an empty one * can be passed, even it is not recommend in order to spoof better * official YouTube clients) * @param streamingUrl a streaming URL * @return the original streaming URL if it has no throttling parameter or a URL with a * deobfuscated throttling parameter- * @throws ParsingException if the extraction of the base JavaScript player file or the- * throttling parameter deobfuscation function failed+ * @throws ParsingException if the extraction of the player ID or the API call failed */ @Nonnull public static String getUrlWithThrottlingParameterDeobfuscated( @Nonnull final String videoId, @Nonnull final String streamingUrl) throws ParsingException { final String obfuscatedThrottlingParameter =- YoutubeThrottlingParameterUtils.getThrottlingParameterFromStreamingUrl(- streamingUrl);+ getThrottlingParameterFromStreamingUrl(streamingUrl); // If the throttling parameter is not present, return the original streaming URL if (obfuscatedThrottlingParameter == null) { return streamingUrl; } - // Do not use the containsKey method of the Map interface in order to avoid a double- // element search, and so to improve performance- final String cacheResult = CACHED_THROTTLING_PARAMETERS.get(- obfuscatedThrottlingParameter);- if (cacheResult != null) {- // If the throttling parameter function has been already ran on the throttling parameter- // of the current streaming URL, replace directly the obfuscated throttling parameter- // with the cached result in the streaming URL- return streamingUrl.replace(obfuscatedThrottlingParameter, cacheResult);- }-- extractJavaScriptCodeIfNeeded(videoId);-- // If the throttling parameter deobfuscation function has been not extracted on a previous- // call, this mean that we will fail to extract it on next calls too if the player code has- // been not changed- // Throw again the corresponding stored exception in this case to improve performance- if (throttlingDeobfFuncExtractionEx != null) {- throw throttlingDeobfFuncExtractionEx;- }+ final PlayerMetadata metadata = getPlayerMetadata(videoId); - if (cachedThrottlingDeobfuscationFunction == null) {- try {- cachedThrottlingDeobfuscationFunctionName =- YoutubeThrottlingParameterUtils.getDeobfuscationFunctionName(- cachedJavaScriptPlayerCode);+ final String deobfuscatedThrottlingParameter = YoutubeApiDecoder.decodeThrottlingParameter(+ metadata.playerId, obfuscatedThrottlingParameter); - cachedThrottlingDeobfuscationFunction =- YoutubeThrottlingParameterUtils.getDeobfuscationFunction(- cachedJavaScriptPlayerCode,- cachedThrottlingDeobfuscationFunctionName);- } catch (final ParsingException e) {- // Store the exception for future calls of this method, in order to improve- // performance- throttlingDeobfFuncExtractionEx = e;- throw e;- } catch (final Exception e) {- throttlingDeobfFuncExtractionEx = new ParsingException(- "Could not get throttling parameter deobfuscation JavaScript function", e);- throw e;- }- }+ return streamingUrl.replace(+ obfuscatedThrottlingParameter, deobfuscatedThrottlingParameter);+ } - try {- final String deobfuscatedThrottlingParameter = JavaScript.run(- cachedThrottlingDeobfuscationFunction,- cachedThrottlingDeobfuscationFunctionName,- obfuscatedThrottlingParameter);+ /**+ * Clear the cached player metadata.+ *+ * <p>+ * The next access will fetch a fresh player ID and signature timestamp from the API.+ * </p>+ */+ public static void clearAllCaches() {+ playerMetadata = null;+ YoutubeApiDecoder.clearCache();+ } - if (isNullOrEmpty(deobfuscatedThrottlingParameter)) {- throw new IllegalStateException("Extracted n-parameter is empty");- }+ public static void clearThrottlingParametersCache() {+ YoutubeApiDecoder.clearCache();+ } - CACHED_THROTTLING_PARAMETERS.put(- obfuscatedThrottlingParameter, deobfuscatedThrottlingParameter);+ public static int getThrottlingParametersCacheSize() {+ return YoutubeApiDecoder.getCacheSize();+ } - return streamingUrl.replace(- obfuscatedThrottlingParameter, deobfuscatedThrottlingParameter);- } catch (final Exception e) {- // This shouldn't happen as the function validity is checked when it is extracted- throw new ParsingException(- "Could not run throttling parameter deobfuscation JavaScript function", e);+ @Nullable+ public static String getThrottlingParameterFromStreamingUrl(+ @Nonnull final String streamingUrl) {+ try {+ return Parser.matchGroup1(THROTTLING_PARAM_PATTERN, streamingUrl);+ } catch (final Parser.RegexException e) {+ return null; } } /**- * Batch-deobfuscate a set of signatures and raw throttling ({@code n}) parameters in one call,- * returning a {@link YoutubeApiDecoder.BatchDecodeResult}.+ * Batch deobfuscate multiple signatures and throttling parameters in a single API call. *- * <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>+ * <p>+ * This method is more efficient than calling {@link #deobfuscateSignature(String, String)}+ * and {@link #getUrlWithThrottlingParameterDeobfuscated(String, String)} individually for+ * each stream, as it combines all parameters into a single API request.+ * </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+ * @param videoId the video ID used to get the JavaScript base player ID+ * @param signatures list of obfuscated signatures to decode (can be null or empty)+ * @param throttlingParams list of obfuscated throttling parameters to decode (can be null or empty)+ * @return a BatchDecodeResult containing decoded signatures and throttling parameters+ * @throws ParsingException if the extraction of the player ID or the API call failed */ @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);+ final String playerId = getPlayerMetadata(videoId).playerId;+ final long startedAtNanos = System.nanoTime();+ final YoutubeApiDecoder.BatchDecodeResult result = YoutubeApiDecoder.decodeBatch(+ playerId, signatures, throttlingParams);+ logPerformanceIfSlow(videoId, "ejs.batch.decode", startedAtNanos);+ return result; } /**- * Deobfuscate a raw throttling ({@code n}) parameter (not embedded in a URL) using the base- * JavaScript player's throttling function, caching the result.+ * Load player metadata from memory or refresh it from the decoder API.+ *+ * @param videoId unused, kept to avoid changing public call sites+ * @throws ParsingException if loading the player metadata failed */ @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;+ private static PlayerMetadata getPlayerMetadata(@Nonnull final String videoId)+ throws ParsingException {+ final PlayerMetadata currentMetadata = playerMetadata;+ if (currentMetadata != null && !currentMetadata.isExpired()) {+ return currentMetadata; } - extractJavaScriptCodeIfNeeded(videoId);-- if (throttlingDeobfFuncExtractionEx != null) {- throw throttlingDeobfFuncExtractionEx;+ final long startedAtNanos = System.nanoTime();+ final YoutubeJavaScriptDecoder decoder = YoutubeApiDecoder.getLocalDecoder();+ if (decoder != null) {+ final YoutubeJavaScriptDecoder.PlayerData data = decoder.getPlayerData(videoId);+ playerMetadata = new PlayerMetadata(data.getPlayerId(), data.getSignatureTimestamp(),+ System.currentTimeMillis() + PLAYER_METADATA_TTL_MILLIS);+ logPerformance(videoId, "ejs.playerMetadata.local", startedAtNanos);+ return playerMetadata; } - 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;- }- }+ playerMetadata = fetchLatestPlayerMetadata();+ logPerformance(videoId, "ejs.playerMetadata.remoteFallback", startedAtNanos);+ return playerMetadata;+ } - 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);- }+ private static void logPerformance(@Nonnull final String videoId,+ @Nonnull final String stage,+ final long startedAtNanos) {+ System.out.println("YT_PERF videoId=" + videoId + " stage=" + stage+ + " durationMs="+ + java.util.concurrent.TimeUnit.NANOSECONDS.toMillis(+ System.nanoTime() - startedAtNanos)); } - /**- * Get the current cache size of throttling parameters.- *- * @return the current cache size of throttling parameters- */- public static int getThrottlingParametersCacheSize() {- return CACHED_THROTTLING_PARAMETERS.size();+ private static void logPerformanceIfSlow(@Nonnull final String videoId,+ @Nonnull final String stage,+ final long startedAtNanos) {+ final long durationMs = java.util.concurrent.TimeUnit.NANOSECONDS.toMillis(+ System.nanoTime() - startedAtNanos);+ if (durationMs >= 5) {+ System.out.println("YT_PERF videoId=" + videoId + " stage=" + stage+ + " durationMs=" + durationMs);+ } } - /**- * Clear all caches.- *- * <p>- * This method will clear all cached JavaScript code and throttling parameters.- * </p>- *- * <p>- * The next time {@link #getSignatureTimestamp(String)},- * {@link #deobfuscateSignature(String, String)} or- * {@link #getUrlWithThrottlingParameterDeobfuscated(String, String)} is called, the JavaScript- * code will be fetched again and the corresponding extraction methods will be ran.- * </p>- */- public static void clearAllCaches() {- cachedJavaScriptPlayerCode = null;- cachedSignatureDeobfuscationFunction = null;- cachedThrottlingDeobfuscationFunctionName = null;- cachedThrottlingDeobfuscationFunction = null;- cachedSignatureTimestamp = null;- clearThrottlingParametersCache();+ @Nonnull+ private static PlayerMetadata fetchLatestPlayerMetadata() throws ParsingException {+ final Map<String, List<String>> headers = new HashMap<>();+ headers.put("User-Agent", Collections.singletonList(USER_AGENT)); - // Clear cached extraction exceptions, if applicable- throttlingDeobfFuncExtractionEx = null;- sigDeobFuncExtractionEx = null;- sigTimestampExtractionEx = null;- }+ try {+ final Response response = NewPipe.getDownloader().get(+ LATEST_PLAYER_URL, headers, Localization.DEFAULT);+ final JsonObject responseJson = JsonParser.object().from(response.responseBody()); - /**- * Clear all cached throttling parameters.- *- * <p>- * The throttling parameter deobfuscation function will be ran again on these parameters if- * streaming URLs containing them are passed in the future.- * </p>- *- * <p>- * This method doesn't clear the cached throttling parameter deobfuscation function, this can- * be done using {@link #clearAllCaches()}.- * </p>- */- public static void clearThrottlingParametersCache() {- CACHED_THROTTLING_PARAMETERS.clear();+ final String playerId = responseJson.getString("player", "");+ if (playerId.isEmpty()) {+ throw new ParsingException("latest-player response missing player");+ }++ if (!responseJson.has("signatureTimestamp")) {+ throw new ParsingException("latest-player response missing signatureTimestamp");+ }++ final int signatureTimestamp = responseJson.getInt("signatureTimestamp");+ return new PlayerMetadata(playerId, signatureTimestamp,+ System.currentTimeMillis() + PLAYER_METADATA_TTL_MILLIS);+ } catch (final IOException e) {+ throw new ParsingException("Failed to fetch latest player metadata", e);+ } catch (final ReCaptchaException e) {+ throw new ParsingException("Failed to fetch latest player metadata", e);+ } catch (final JsonParserException e) {+ throw new ParsingException("Failed to parse latest player metadata", e);+ } } - /**- * Extract the JavaScript code if it isn't already cached.- *- * @param videoId the video ID used to get the JavaScript base player file (an empty one can be- * passed, even it is not recommend in order to spoof better official YouTube- * clients)- * @throws ParsingException if the extraction of the base JavaScript player file failed- */- private static void extractJavaScriptCodeIfNeeded(@Nonnull final String videoId)- throws ParsingException {- if (cachedJavaScriptPlayerCode == null) {- cachedJavaScriptPlayerCode = YoutubeJavaScriptExtractor.extractJavaScriptPlayerCode(- videoId);+ private static final class PlayerMetadata {+ @Nonnull+ private final String playerId;+ private final int signatureTimestamp;+ private final long expiresAt;++ private PlayerMetadata(@Nonnull final String playerId,+ final int signatureTimestamp,+ final long expiresAt) {+ this.playerId = playerId;+ this.signatureTimestamp = signatureTimestamp;+ this.expiresAt = expiresAt;+ }++ private boolean isExpired() {+ return System.currentTimeMillis() >= expiresAt; } } }
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 8e1ce1d0c4..b78867c472 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@@ -69,6 +69,7 @@ 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.YoutubeSabrFormat; 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;@@ -82,6 +83,7 @@ import org.schabi.newpipe.extractor.stream.StreamSegment; import org.schabi.newpipe.extractor.stream.StreamType; import org.schabi.newpipe.extractor.stream.SubtitlesStream; import org.schabi.newpipe.extractor.stream.VideoStream;+import org.schabi.newpipe.extractor.utils.ExtractorLogger; import org.schabi.newpipe.extractor.utils.JsonUtils; import org.schabi.newpipe.extractor.utils.LocaleCompat; import org.schabi.newpipe.extractor.utils.Pair;@@ -1142,89 +1144,72 @@ 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.+ * Fetch SABR (Server Adaptive BitRate) streams once via a WEB-family (MWEB) player request and+ * build audio + video-only streams from the returned {@link YoutubeSabrInfo} formats (which+ * include AV1). Each stream uses {@link DeliveryMethod#SABR}, has {@code isUrl=false}, and+ * carries the shared {@link YoutubeSabrInfo} as its delivery-method info so the client can+ * drive a session.+ *+ * <p>This is deliberately separate from the ANDROID progressive formats: {@code+ * serverAbrStreamingUrl} and the AV1 SABR formats are only served to WEB-family clients, so we+ * must issue a dedicated MWEB {@code /player} request (authenticated with the session PoToken+ * provided via {@link org.schabi.newpipe.extractor.NewPipe#getYoutubeSessionPoTokenProvider()}).+ * A failure here (no PoToken, no SABR offered, network error) is non-fatal and simply yields no+ * SABR streams.</p> */ 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) {+ final YoutubeSabrInfo sabrInfo;+ try {+ sabrInfo = YoutubeSabrProbe.fetchSabrInfo(videoId,+ YoutubeSabrClientProfile.WEB,+ getExtractorLocalization(),+ getExtractorContentCountry());+ } catch (final Exception e) {+ ExtractorLogger.d("YoutubeSabr", "SABR fetch failed for {}: {}", videoId, e); return; }- final JsonObject streamingData = playerResponse.getObject(STREAMING_DATA);- final String serverAbrStreamingUrl =- streamingData.getString("serverAbrStreamingUrl", "");- final JsonArray adaptiveFormats = streamingData.getArray(ADAPTIVE_FORMATS);- if (adaptiveFormats == null) {+ if (sabrInfo == null || sabrInfo.getFormats() == null) {+ ExtractorLogger.d("YoutubeSabr", "SABR fetch returned no info/formats for {}", videoId); return; }-- for (int i = 0; i < adaptiveFormats.size(); i++) {- final JsonObject formatData = adaptiveFormats.getObject(i);+ final String serverAbrStreamingUrl = sabrInfo.getServerAbrStreamingUrl();+ int av1Count = 0;+ for (final YoutubeSabrFormat format : sabrInfo.getFormats()) { try {- final ItagItem itagItem = ItagItem.getItag(formatData.getInt("itag"));- fillSabrItagItem(itagItem, formatData);- final String id = String.valueOf(itagItem.id);+ final ItagItem itagItem = buildSabrItagItem(format);+ if (itagItem == null) {+ continue;+ }+ final String id = String.valueOf(format.getItag()); - if (itagItem.itagType == ItagItem.ItagType.AUDIO) {+ if (format.isAudio()) { final AudioStream.Builder builder = new AudioStream.Builder() .setContent(serverAbrStreamingUrl, false) .setMediaFormat(itagItem.getMediaFormat())- .setAverageBitrate(itagItem.getAverageBitrate())+ .setAverageBitrate(format.getBitrate()) .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 trackId = format.getAudioTrackId();+ if (trackId != null && !trackId.isEmpty()) {+ final String langPart = trackId.split("\\.")[0];+ final String displayName = format.getAudioTrackDisplayName();+ 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();@@ -1232,15 +1217,22 @@ public class YoutubeStreamExtractor extends StreamExtractor { .noneMatch(s -> audioStreamId.equals(s.getId()))) { sabrAudioStreams.add(stream); }- } else if (itagItem.itagType == ItagItem.ItagType.VIDEO_ONLY) {- final String resolution = itagItem.getResolutionString();+ } else if (format.isVideo()) {+ final String codec = itagItem.getCodec();+ if (codec != null && codec.contains("av01")) {+ av1Count++;+ }+ final String qualityLabel = format.getQualityLabel();+ final String resolution = qualityLabel != null && !qualityLabel.isEmpty()+ ? qualityLabel+ : (format.getHeight() > 0 ? format.getHeight() + "p" : ""); final VideoStream stream = new VideoStream.Builder() .setId(id) .setContent(serverAbrStreamingUrl, false) .setMediaFormat(itagItem.getMediaFormat()) .setIsVideoOnly(true) .setItagItem(itagItem)- .setResolution(resolution != null ? resolution : "")+ .setResolution(resolution) .setDeliveryMethod(DeliveryMethod.SABR) .setDeliveryMethodInfo(sabrInfo) .build();@@ -1249,47 +1241,45 @@ public class YoutubeStreamExtractor extends StreamExtractor { } } } catch (final Exception e) {- // Skip unknown itags or malformed formats; do not fail the whole extraction.+ // Skip malformed formats; do not fail the whole extraction. } }-+ ExtractorLogger.d("YoutubeSabr", "SABR built video={} audio={} (av1={}) for {}",+ sabrVideoOnlyStreams.size(), sabrAudioStreams.size(), av1Count, videoId); 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", "");+ /**+ * Construct an {@link ItagItem} for a SABR format, sourcing all fields from the+ * {@link YoutubeSabrFormat}. Unlike {@link ItagItem#getItag(int)} this handles itags not+ * present in the built-in table (notably AV1), which is required so AV1 SABR formats survive to+ * the player/picker instead of being silently dropped.+ */+ @Nullable+ private static ItagItem buildSabrItagItem(@Nonnull final YoutubeSabrFormat format) {+ final String mimeType = format.getMimeType() == null ? "" : format.getMimeType(); 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"));+ final boolean webm = mimeType.contains("webm");+ final ItagItem itagItem;+ if (format.isAudio()) {+ final MediaFormat mediaFormat = webm+ ? (codec.contains("opus") ? MediaFormat.WEBMA_OPUS : MediaFormat.WEBMA)+ : MediaFormat.M4A;+ itagItem = new ItagItem(format.getItag(), ItagItem.ItagType.AUDIO, mediaFormat,+ Math.max(format.getBitrate(), 0));+ } else {+ final MediaFormat mediaFormat = webm ? MediaFormat.WEBM : MediaFormat.MPEG_4;+ final String resolution = format.getHeight() > 0 ? format.getHeight() + "p" : "";+ itagItem = new ItagItem(format.getItag(), ItagItem.ItagType.VIDEO_ONLY, mediaFormat,+ resolution);+ itagItem.setWidth(format.getWidth());+ itagItem.setHeight(format.getHeight());+ }+ itagItem.setBitrate(format.getBitrate()); 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))));+ itagItem.setContentLength(format.getContentLength());+ itagItem.setApproxDurationMs(format.getApproxDurationMs());+ return itagItem; } private <T extends Stream> List<T> getItags(
youpipe/src/main/java/com/vayunmathur/youpipe/ui/VideoPlayer.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/ui/VideoPlayer.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/ui/VideoPlayer.ktindex f31cf579a7..1992a88eb0 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/ui/VideoPlayer.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/ui/VideoPlayer.kt@@ -238,6 +238,21 @@ fun VideoPlayer( val historyVideo by historyFlow.collectAsState(initial = null) val timeWatched = historyVideo?.progress ?: 0 + // PipePipe-style prewarm: when a SABR stream is selected (default or after a quality switch),+ // warm the PoToken + SABR bootstrap for that exact itag so pressing play is instant. The+ // itag parsed here matches what PlaybackService will parse from the same sabr:// URI, so the+ // bootstrap cache key lines up.+ LaunchedEffect(currentVideoStream) {+ val uri = Uri.parse(currentVideoStream.url)+ if (uri.scheme == "sabr") {+ val vid = uri.host+ val itag = uri.getQueryParameter("v")?.toIntOrNull()+ if (vid != null && itag != null) {+ com.vayunmathur.youpipe.util.sabr.SabrSessionStore.prewarm(context, vid, itag)+ }+ }+ }+ // 3. Updated LaunchedEffect to pass audio URI through Metadata Extras LaunchedEffect(controller, currentVideoStream, currentAudioStream, videoInfo.name, videoInfo.author, subtitles) { val player = controller ?: return@LaunchedEffect
youpipe/src/main/java/com/vayunmathur/youpipe/util/MyDownloader.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/util/MyDownloader.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/util/MyDownloader.ktindex e4d685c026..334eb1ebd7 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/util/MyDownloader.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/util/MyDownloader.kt@@ -1,12 +1,15 @@ package com.vayunmathur.youpipe.util import com.vayunmathur.library.network.NetworkClient import kotlinx.coroutines.runBlocking+import okhttp3.OkHttpClient+import okhttp3.Request as OkRequest+import okhttp3.RequestBody.Companion.toRequestBody import org.schabi.newpipe.extractor.downloader.Downloader import org.schabi.newpipe.extractor.downloader.Request import org.schabi.newpipe.extractor.downloader.Response import org.schabi.newpipe.extractor.downloader.StreamingResponse import org.schabi.newpipe.extractor.localization.Localization-import java.io.ByteArrayInputStream+import java.util.concurrent.TimeUnit class MyDownloader : Downloader() { override fun execute(request: Request): Response = runBlocking {@@ -17,7 +20,7 @@ class MyDownloader : Downloader() { val response = NetworkClient.performRequest( url = url, method = method,- headers = request.headers(),+ headers = withDefaultHeaders(request.headers()), body = body ) @@ -30,42 +33,101 @@ class MyDownloader : Downloader() { ) } - // SABR needs binary-safe streaming bodies. NetworkClient.performRequestBytesFull returns the- // raw bytes + headers in a single request; we expose them as an InputStream-backed- // StreamingResponse. (This buffers the response; SABR requests are byte-range bounded by the- // session, so the batches stay reasonably sized.)+ // SABR streaming: faithful port of PipePipe's DownloaderImpl.executeStreaming using OkHttp+ // directly. Ktor's setBody(ByteArray) forces Content-Type: application/octet-stream and its+ // ContentNegotiation(json) sits on the binary path — both of which broke the SABR+ // VideoPlaybackAbrRequest POST (server returned no media). OkHttp with a null-media-type+ // RequestBody sends NO Content-Type (matching PipePipe), exposes the body as a true streaming+ // InputStream (byteStream), and follows redirects — so large media batches aren't buffered. override fun getStreaming( url: String, headers: MutableMap<String, MutableList<String>>?, localization: Localization?- ): StreamingResponse = runBlocking {- val (status, respHeaders, bytes) = NetworkClient.performRequestBytesFull(- url = url,- method = "GET",- headers = headers ?: emptyMap<String, List<String>>()- )- StreamingResponse(status, respHeaders, ByteArrayInputStream(bytes))- }+ ): StreamingResponse = executeStreaming(url, "GET", headers, null, sabrClient) override fun getStreaming( url: String, headers: MutableMap<String, MutableList<String>>?, localization: Localization?, timeoutMs: Long- ): StreamingResponse = getStreaming(url, headers, localization)+ ): StreamingResponse {+ val bounded = timeoutMs.coerceAtLeast(1)+ val client = sabrClient.newBuilder()+ .callTimeout(bounded, TimeUnit.MILLISECONDS)+ .connectTimeout(bounded, TimeUnit.MILLISECONDS)+ .readTimeout(bounded, TimeUnit.MILLISECONDS)+ .build()+ return executeStreaming(url, "GET", headers, null, client)+ } override fun postStreaming( url: String, headers: MutableMap<String, MutableList<String>>?, dataToSend: ByteArray?, localization: Localization?- ): StreamingResponse = runBlocking {- val (status, respHeaders, bytes) = NetworkClient.performRequestBytesFull(- url = url,- method = "POST",- headers = headers ?: emptyMap<String, List<String>>(),- body = dataToSend- )- StreamingResponse(status, respHeaders, ByteArrayInputStream(bytes))+ ): StreamingResponse = executeStreaming(url, "POST", headers, dataToSend, sabrClient)++ private fun executeStreaming(+ url: String,+ method: String,+ headers: Map<String, List<String>>?,+ data: ByteArray?,+ client: OkHttpClient+ ): StreamingResponse {+ // Null media type => OkHttp sends no Content-Type header (matches PipePipe). An empty POST+ // still needs a body so OkHttp allows the method.+ val requestBody = when {+ data != null -> data.toRequestBody(null)+ method == "POST" -> ByteArray(0).toRequestBody(null)+ else -> null+ }+ val builder = OkRequest.Builder().method(method, requestBody).url(url)+ val hasUserAgent = headers?.keys?.any { it.equals("User-Agent", ignoreCase = true) } == true+ if (!hasUserAgent) {+ builder.header("User-Agent", DEFAULT_USER_AGENT)+ }+ headers?.forEach { (name, values) ->+ when {+ values.size > 1 -> {+ builder.removeHeader(name)+ values.forEach { builder.addHeader(name, it) }+ }+ values.size == 1 -> builder.header(name, values[0])+ }+ }+ val response = client.newCall(builder.build()).execute()+ val bodyStream = response.body?.byteStream()+ ?: java.io.ByteArrayInputStream(ByteArray(0))+ // StreamingResponse.close() closes this stream, which closes the OkHttp body + connection.+ return StreamingResponse(response.code, response.headers.toMultimap(), bodyStream)+ }++ // Inject a default browser User-Agent when the caller didn't set one (matches PipePipe's+ // DownloaderImpl). YouTube/googlevideo rejects UA-less requests with HTTP 403.+ private fun withDefaultHeaders(+ headers: Map<String, List<String>>?+ ): Map<String, List<String>> {+ val result = LinkedHashMap<String, List<String>>()+ if (headers != null) {+ result.putAll(headers)+ }+ if (result.keys.none { it.equals("User-Agent", ignoreCase = true) }) {+ result["User-Agent"] = listOf(DEFAULT_USER_AGENT)+ }+ return result+ }++ companion object {+ private const val DEFAULT_USER_AGENT =+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:128.0) Gecko/20100101 Firefox/128.0"++ // Dedicated OkHttp client for SABR binary transfers: no content negotiation, follows+ // redirects (default), no forced Content-Type. Reused across requests for connection pooling.+ private val sabrClient: OkHttpClient by lazy {+ OkHttpClient.Builder()+ .connectTimeout(30, TimeUnit.SECONDS)+ .readTimeout(60, TimeUnit.SECONDS)+ .build()+ } } }
youpipe/src/main/java/com/vayunmathur/youpipe/util/YouPipeViewModel.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/util/YouPipeViewModel.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/util/YouPipeViewModel.ktindex aba11ed1c3..cc104b5d16 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/util/YouPipeViewModel.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/util/YouPipeViewModel.kt@@ -682,45 +682,61 @@ class YouPipeViewModel( val sabrMethod = org.schabi.newpipe.extractor.stream.DeliveryMethod.SABR- // Progressive/adaptive URL streams are preferred over SABR when both are- // present; SABR is only used when the video is SABR-only. val progVideoOnly = rawVideoOnly.filter { it.deliveryMethod != sabrMethod } val progAudio = rawAudio.filter { it.deliveryMethod != sabrMethod } val sabrVideoOnly = rawVideoOnly.filter { it.deliveryMethod == sabrMethod } val sabrAudio = rawAudio.filter { it.deliveryMethod == sabrMethod }+ val videoId = ex.id - val useSabr = progVideoOnly.isEmpty() && sabrVideoOnly.isNotEmpty()+ android.util.Log.d(+ "YouPipeSabr",+ "video $videoId streams prog(v=${progVideoOnly.size}," ++ "a=${progAudio.size}) sabr(v=${sabrVideoOnly.size}," ++ "a=${sabrAudio.size})"+ ) - if (useSabr && sabrAudio.isNotEmpty()) {- val videoId = ex.id- // Hand the extractor-derived SABR metadata to the playback service.+ // Register SABR session metadata for the playback service if present.+ // NOTE: do NOT prewarm the content PoToken here — doing so regressed SABR+ // bootstrap (403 on init range / "no exact indexes"). The token is minted+ // at play time by createSourceSpec, which is the known-working ordering.+ if (sabrVideoOnly.isNotEmpty()) { sabrVideoOnly.firstOrNull { it.deliveryMethodInfo is org.schabi.newpipe.extractor.services.youtube.sabr.YoutubeSabrInfo }?.let {+ val sabrInfo = it.deliveryMethodInfo as+ org.schabi.newpipe.extractor.services.youtube.sabr.YoutubeSabrInfo com.vayunmathur.youpipe.util.sabr.SabrSessionStore.putExtractorInfo(- videoId,- it.deliveryMethodInfo as- org.schabi.newpipe.extractor.services.youtube.sabr.YoutubeSabrInfo+ videoId, sabrInfo ) }- videoStreams = sabrVideoOnly.map { it.toSabrDomain(videoId) }.sortedWith(- compareByDescending<VideoStream> { it.height }- .thenByDescending { codecPriority(it.codec) }- )- audioStreams = sabrAudio.map { it.toSabrDomain(videoId) }.sortedWith(- compareByDescending<AudioStream> { it.bitrate }- .thenByDescending { audioCodecPriority(it.codec) }- )- } else if (progVideoOnly.isNotEmpty() && progAudio.isNotEmpty()) {- videoStreams = progVideoOnly.map { it.toDomain() }.sortedWith(- compareByDescending<VideoStream> { it.height }- .thenByDescending { codecPriority(it.codec) }- )- audioStreams = progAudio.map { it.toDomain() }.sortedWith(- compareByDescending<AudioStream> { it.bitrate }- .thenByDescending { audioCodecPriority(it.codec) }- )+ }++ if (progVideoOnly.isNotEmpty() || sabrVideoOnly.isNotEmpty()) {+ // Combine progressive + SABR video-only options, but de-duplicate by+ // (codec, resolution): progressive is listed first and kept for any+ // combo it already offers, so SABR only contributes what's genuinely+ // new — notably AV1 (SABR-only) and any resolutions progressive lacks.+ // Without this, h264/vp9 would appear twice (once per source).+ videoStreams = (+ progVideoOnly.map { it.toDomain() } ++ sabrVideoOnly.map { it.toSabrDomain(videoId) }+ )+ .distinctBy { it.codec to it.height }+ .sortedWith(+ compareByDescending<VideoStream> { it.height }+ .thenByDescending { codecPriority(it.codec) }+ )+ audioStreams = (+ if (progAudio.isNotEmpty()) {+ progAudio.map { it.toDomain() }+ } else {+ sabrAudio.map { it.toSabrDomain(videoId) }+ }+ ).sortedWith(+ compareByDescending<AudioStream> { it.bitrate }+ .thenByDescending { audioCodecPriority(it.codec) }+ ) } else { videoStreams = ex.videoStreams.map { it.toDomain() } .sortedWith(compareByDescending { it.height })
youpipe/src/main/java/com/vayunmathur/youpipe/util/sabr/SabrSessionStore.java
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/util/sabr/SabrSessionStore.java b/youpipe/src/main/java/com/vayunmathur/youpipe/util/sabr/SabrSessionStore.javaindex 28eb39ba70..0cba8c8f36 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/util/sabr/SabrSessionStore.java+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/util/sabr/SabrSessionStore.java@@ -110,6 +110,40 @@ public final class SabrSessionStore { return EXTRACTOR_INFO.get(videoId); } + /**+ * PipePipe-style detail-page prewarm: as soon as a SABR stream is selected, warm BOTH the+ * content PoToken and the SABR bootstrap for the selected video itag, using the same format+ * selection and cache key that {@link #createSourceSpec} will use at play time. This makes the+ * first play effectively instant (the bootstrap is served from the cache / in-flight future+ * rather than being started when the user presses play).+ *+ * <p>Mirrors PipePipe's {@code SabrSessionStore.prewarm(...)} which calls both+ * {@code startTokenWarmup} and {@code startBootstrap}. Warming only the token (without the+ * bootstrap) is NOT enough and previously regressed playback. Non-blocking: the work runs on+ * background executors and is deduplicated per video id / bootstrap key.</p>+ *+ * @param selectedVideoItag the itag of the SABR video stream the user is about to play; must+ * match what {@link #createSourceSpec} is later called with so the+ * bootstrap cache key lines up+ */+ public static void prewarm(@NonNull final Context context,+ @NonNull final String videoId,+ final int selectedVideoItag) {+ final YoutubeSabrInfo info = EXTRACTOR_INFO.get(videoId);+ if (info == null || !isUsableExtractorInfo(info, videoId)) {+ return;+ }+ final YoutubeSabrFormat audioFormat = pickAudioFormat(info, PREFERRED_AUDIO.get(videoId));+ final YoutubeSabrFormat videoFormat = pickVideoFormat(info, selectedVideoItag);+ if (audioFormat == null || videoFormat == null) {+ return;+ }+ final Context appContext = context.getApplicationContext();+ final Localization localization = new Localization("en", "US");+ startTokenWarmup(appContext, info, audioFormat, videoFormat);+ startBootstrap(appContext, info, audioFormat, videoFormat, localization);+ }+ private static final class SessionKey { @NonNull private final String videoId; private final long sourceId;