From 2e675c8f8a95f1c04cb117a73d87c669b8c65f27 Mon Sep 17 00:00:00 2001 From: ajisth69 Date: Sat, 5 Dec 2026 15:14:23 +0530 Subject: [PATCH 1/5] chore(deps): remove NewPipe extractor and Rhino rules --- app/build.gradle.kts | 6 +- app/proguard-rules.pro | 17 +- .../com/lastwave/app/LastWaveApplication.kt | 6 +- .../app/data/music/YouTubeStreamExtractor.kt | 600 ------------------ .../app/data/music/YouTubeVideoStream.kt | 2 +- .../app/data/video/SyncedVideoRepository.kt | 5 +- .../app/data/music/ArtistCreditParserTest.kt | 1 - .../music/HomeChipsAndPaginationParserTest.kt | 1 - .../music/HomeCommunityDiscoverDataTest.kt | 2 +- .../app/data/music/HomeShelfExtrasTest.kt | 1 - .../app/data/music/HomeShelfParserTest.kt | 1 - .../app/data/music/MoodsParserTest.kt | 1 - .../app/data/music/PlaylistPaginationTest.kt | 1 - .../app/data/music/YtRadioParserTest.kt | 1 - gradle/libs.versions.toml | 2 - 15 files changed, 7 insertions(+), 640 deletions(-) delete mode 100644 app/src/main/java/com/lastwave/app/data/music/YouTubeStreamExtractor.kt diff --git a/app/build.gradle.kts b/app/build.gradle.kts index e43cf721ab..6d3c9e1e97 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -533,17 +533,13 @@ dependencies { // decoders remain as automatic fallbacks. implementation("org.jellyfin.media3:media3-ffmpeg-decoder:1.9.0+1") - // NIO also backports NewPipe's URL encoder/decoder overloads below API 33. + // Backports java.time / NIO APIs below API 33. coreLibraryDesugaring("com.android.tools:desugar_jdk_libs_nio:2.0.4") // Low-latency native output. Version 1.10 remains API-compatible with the // requested Oboe 1.8+ baseline and exposes its CMake target through Prefab. implementation("com.google.oboe:oboe:1.10.0") - // Metadata/search remains local InnerTube/NewPipe functionality; playback - // resolves through InnerTubeX first and retains NewPipe as a fallback. - implementation(libs.newpipe.extractor) - // InnerTubeX is invoked through the compatibility adapter because its // current release is built with a newer Kotlin metadata version than the // app. Runtime-only keeps the app compiler on its existing Kotlin line. diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro index 2b3c85419c..ce17bd2b1b 100644 --- a/app/proguard-rules.pro +++ b/app/proguard-rules.pro @@ -43,25 +43,10 @@ -keep class * extends androidx.glance.appwidget.GlanceAppWidgetReceiver { *; } -keep class com.lastwave.app.widget.** { *; } -# NewPipe's YouTube extractor loads service implementations and its -# JavaScript deobfuscation engine dynamically. --keep class org.schabi.newpipe.extractor.** { *; } --dontwarn org.schabi.newpipe.extractor.** +# HTML parsing used by Genius lyrics / sanitizer -keep class org.jsoup.** { *; } -dontwarn org.jsoup.** -dontwarn java.beans.** -# NewPipe's JS engine (Rhino) resolves classes by name at runtime -# (Context.getRegExpProxy() → org.mozilla.javascript.regexp.RegExpImpl, -# Context.createInterpreter, script compilation) and the jar bundles no -# consumer R8 rules. Under shrinking the release path silently loses the -# player-JS deobfuscation (the unminified rawRelease hides this). Keep the -# whole engine plus ClassFileWriter, which is instantiated reflectively for -# compiled scripts. --keep class org.mozilla.javascript.** { *; } --keep class org.mozilla.classfile.ClassFileWriter { *; } --dontwarn org.mozilla.javascript.** --dontwarn org.mozilla.classfile.** --dontwarn javax.script.** # InnerTubeX is reached through the Kotlin-compatibility reflection boundary; # retain its public constructors/models and the selected Ktor engine in release diff --git a/app/src/main/java/com/lastwave/app/LastWaveApplication.kt b/app/src/main/java/com/lastwave/app/LastWaveApplication.kt index cf1ba82fcc..676e5b34bd 100644 --- a/app/src/main/java/com/lastwave/app/LastWaveApplication.kt +++ b/app/src/main/java/com/lastwave/app/LastWaveApplication.kt @@ -36,7 +36,6 @@ class LastWaveApplication : Application(), ImageLoaderFactory { @Inject lateinit var themeRepository: dagger.Lazy @Inject lateinit var applicationScope: CoroutineScope @Inject lateinit var okHttpClient: dagger.Lazy - @Inject lateinit var streamExtractor: dagger.Lazy @Inject lateinit var innerTubeMusicApi: dagger.Lazy @Inject lateinit var ytMusicSyncManager: dagger.Lazy @Inject lateinit var ytMusicHistorySyncManager: dagger.Lazy @@ -78,7 +77,7 @@ class LastWaveApplication : Application(), ImageLoaderFactory { // On-demand lyric translation/romanization keeps its bounded result // cache under the app cache directory so Android may reclaim it. runCatching { com.lastwave.app.data.lyrics.LyricsTranslation.cacheDir = cacheDir } - // First-song OPUS warmup: visitorData + NewPipe + BotGuard must be + // First-song OPUS warmup: visitorData + BotGuard must be // ready before the first tap, not 2.5s after. Immediate and never // throws; the delayed block below keeps the rest lazy. // Duplicate launcher icons after an update or icon change: make sure only @@ -87,9 +86,6 @@ class LastWaveApplication : Application(), ImageLoaderFactory { runCatching { themeRepository.get().reconcileAppIcon() } } applicationScope.launch(Dispatchers.IO) { - // NewPipe is optional fallback infrastructure. A broken extractor - // install must not escape an application-scope coroutine. - runCatching { streamExtractor.get().preWarm() } // Warm the InnerTube web config (visitor data) so the first // playback's direct-URL fast path can attach it immediately. runCatching { innerTubeMusicApi.get().preWarmPlayback() } diff --git a/app/src/main/java/com/lastwave/app/data/music/YouTubeStreamExtractor.kt b/app/src/main/java/com/lastwave/app/data/music/YouTubeStreamExtractor.kt deleted file mode 100644 index b6a0efc14d..0000000000 --- a/app/src/main/java/com/lastwave/app/data/music/YouTubeStreamExtractor.kt +++ /dev/null @@ -1,600 +0,0 @@ -package com.lastwave.app.data.music - -import android.net.Uri -import android.util.Log -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.withContext -import okhttp3.HttpUrl.Companion.toHttpUrlOrNull -import okhttp3.OkHttpClient -import okhttp3.MediaType.Companion.toMediaType -import okhttp3.RequestBody.Companion.toRequestBody -import org.json.JSONObject -import org.schabi.newpipe.extractor.NewPipe -import org.schabi.newpipe.extractor.ServiceList -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.services.youtube.YoutubeJavaScriptPlayerManager -import org.schabi.newpipe.extractor.stream.StreamInfo -import java.io.IOException -import javax.inject.Inject -import javax.inject.Singleton - -/** - * Resolves the signed/ciphered YouTube media URLs that raw InnerTube player - * responses no longer reliably expose. Extraction happens locally; no proxy - * or account is used. - */ -@Singleton -class YouTubeStreamExtractor @Inject constructor( - private val http: OkHttpClient, -) { - private val downloader = OkHttpNewPipeDownloader(http) - - @Volatile - private var initialized = false - - fun invalidateCache(@Suppress("UNUSED_PARAMETER") videoId: String) = Unit - - suspend fun resolveAudioStream( - videoId: String, - preferM4a: Boolean = false, - preferOpus: Boolean = false, - maxBitrateBps: Int? = null, - ): YouTubeAudioStream = withContext(Dispatchers.IO) { - val now = System.currentTimeMillis() - initialize() - val info = try { - StreamInfo.getInfo(ServiceList.YouTube, "https://www.youtube.com/watch?v=$videoId") - } catch (error: kotlinx.coroutines.CancellationException) { - throw error - } catch (error: Exception) { - throw IOException("YouTube stream extraction failed for $videoId", error) - } - val ordered = info.audioStreams.sortedWith( - compareBy { isDrcAudioUrl(it.content.orEmpty()) } - .thenBy { audioPreference(it, preferM4a, preferOpus) } - .thenByDescending { maxOf(it.averageBitrate, it.bitrate) }, - ) - if (ordered.isEmpty()) throw IOException("YouTube returned no playable audio stream for $videoId") - val candidates = ordered.map { stream -> - stream.toYouTubeAudioStream(videoId, info.duration, now) - }.filter { - it.meetsBitrateLimit(maxBitrateBps) - } - if (candidates.isEmpty()) throw IOException("YouTube returned no audio within the requested bitrate for $videoId") - val playable = selectProbedCandidate( - candidates = candidates, - urlOf = { it.url }, - probe = ::probePlayable, - limit = MAX_PROBED_AUDIO_STREAMS, - ) - if (playable != null) return@withContext playable - invalidatePlayerState(videoId) - throw IOException("YouTube audio URLs were rejected for $videoId") - } - - suspend fun resolveVideoStreamBundle( - videoId: String, - ): SyncedVideoStreamBundle = withContext(Dispatchers.IO) { - val now = System.currentTimeMillis() - initialize() - val info = try { - StreamInfo.getInfo(ServiceList.YouTube, "https://www.youtube.com/watch?v=$videoId") - } catch (error: kotlinx.coroutines.CancellationException) { - throw error - } catch (error: Exception) { - throw IOException("YouTube video stream extraction failed for $videoId", error) - } - val allVideoStreams = buildList { - addAll(info.videoStreams) - addAll(info.videoOnlyStreams) - } - val validStreams = allVideoStreams.filter { stream -> - stream.content.isNotBlank() && ( - stream.format?.mimeType?.contains("mp4", ignoreCase = true) == true || - stream.format?.mimeType?.contains("webm", ignoreCase = true) == true - ) && VideoDecoderSupport.canDecode( - stream.codec, - stream.width, - parseResolutionHeight(stream.resolution, stream.height), - ) - } - if (validStreams.isEmpty()) { - throw IOException("This device has no decoder for the video streams of $videoId") - } - - // Group by resolution height (supports up to 2160p, 1440p, 1080p, 720p, 480p, 360p, 240p, 144p) - val streamsByHeight = validStreams - .map { stream -> - val h = parseResolutionHeight(stream.resolution, stream.height) - h to stream - } - .filter { it.first > 0 } - .groupBy({ it.first }, { it.second }) - .mapValues { (_, streams) -> - // Codec first: an MP4 can hold AV1, and a higher bitrate must not - // beat H.264 on the many phones that decode AV1 slowly or not at all. - streams.maxWithOrNull( - compareBy { - videoCodecPreference(it.codec) - }.thenBy { it.bitrate } - )!! - } - - val availableStreams = streamsByHeight.keys.sortedDescending().map { height -> - streamsByHeight[height]!!.toYouTubeVideoStream(videoId, info.duration, now) - } - if (availableStreams.isEmpty()) { - throw IOException("YouTube returned no valid video stream resolutions for $videoId") - } - - // For default (Auto), prefer 720p or 1080p for instant playback without buffer stalls - val playableDefault = selectProbedCandidate( - candidates = rankedForAutoPlayback(availableStreams), - urlOf = { it.url }, - probe = ::probePlayableVideo, - limit = MAX_PROBED_AUDIO_STREAMS, - ) ?: throw IOException("YouTube video URLs were rejected for $videoId") - - val pairedAudioUrl = info.audioStreams.maxByOrNull { it.bitrate }?.content - SyncedVideoStreamBundle( - videoId = videoId, - defaultStream = playableDefault, - availableStreams = availableStreams, - pairedAudioStreamUrl = pairedAudioUrl, - pairedAudioHeaders = mapOf( - "User-Agent" to YOUTUBE_WEB_USER_AGENT, - "Origin" to YOUTUBE_ORIGIN, - "Referer" to "$YOUTUBE_ORIGIN/watch?v=$videoId", - ), - ) - } - - suspend fun resolveVideoStream( - videoId: String, - ): YouTubeVideoStream = resolveVideoStreamBundle(videoId).defaultStream - - private suspend fun resolveVideoStreamBundleWithIosClient( - videoId: String, - now: Long, - ): SyncedVideoStreamBundle? = withContext(Dispatchers.IO) { - runCatching { - val jsonBody = """ - { - "context": { - "client": { - "clientName": "IOS", - "clientVersion": "21.10.3", - "clientScreen": "WATCH", - "deviceMake": "Apple", - "deviceModel": "iPhone16,2", - "osName": "iPhone", - "osVersion": "18.1.0.22B83", - "platform": "MOBILE", - "hl": "en", - "gl": "US" - } - }, - "videoId": "$videoId", - "contentCheckOk": true, - "racyCheckOk": true - } - """.trimIndent() - - val request = okhttp3.Request.Builder() - .url("https://www.youtube.com/youtubei/v1/player?prettyPrint=false") - .post(jsonBody.toRequestBody("application/json".toMediaType())) - .header("User-Agent", "com.google.ios.youtube/21.10.3 (iPhone16,2; U; CPU iOS 18_1_0 like Mac OS X;)") - .header("X-Goog-Api-Format-Version", "2") - .header("X-YouTube-Client-Name", "5") - .header("X-YouTube-Client-Version", "21.10.3") - .build() - - val root = http.newCall(request).execute().use { response -> - if (!response.isSuccessful) return@runCatching null - val bodyStr = response.body?.string() ?: return@runCatching null - JSONObject(bodyStr) - } - - val status = root.optJSONObject("playabilityStatus")?.optString("status").orEmpty() - if (!status.equals("OK", ignoreCase = true)) return@runCatching null - - val streamingData = root.optJSONObject("streamingData") ?: return@runCatching null - val adaptive = streamingData.optJSONArray("adaptiveFormats") ?: return@runCatching null - val durationSec = root.optJSONObject("videoDetails")?.optString("lengthSeconds")?.toLongOrNull() ?: 0L - - var pairedAudioUrl: String? = null - var bestAudioBitrate = 0 - val extractedStreams = mutableListOf() - for (i in 0 until adaptive.length()) { - val f = adaptive.optJSONObject(i) ?: continue - val mime = f.optString("mimeType") - if (mime.contains("audio", ignoreCase = true)) { - val aUrl = f.optString("url").takeIf { it.isNotBlank() } ?: continue - val aBitrate = f.optInt("bitrate", 0) - if (aBitrate > bestAudioBitrate || (mime.contains("opus", ignoreCase = true) && pairedAudioUrl == null)) { - bestAudioBitrate = aBitrate - pairedAudioUrl = aUrl - } - continue - } - if (!mime.contains("video", ignoreCase = true)) continue - val streamUrl = f.optString("url").takeIf { it.isNotBlank() } ?: continue - val height = f.optInt("height", 0).takeIf { it > 0 } - ?: parseResolutionHeight(f.optString("qualityLabel"), 0) - val width = f.optInt("width", 0).takeIf { it > 0 } - val bitrate = f.optInt("bitrate", 0) - - extractedStreams += YouTubeVideoStream( - videoId = videoId, - url = streamUrl, - itag = f.optInt("itag", 0).takeIf { it > 0 }, - resolution = f.optString("qualityLabel").ifBlank { "${height}p" }, - height = height, - width = width, - bitrate = bitrate, - mimeType = mime.substringBefore(";"), - durationMs = durationSec.takeIf { it > 0 }?.times(1_000L), - expiresAtEpochMs = now + 5 * 60 * 60 * 1000L, - requestHeaders = mapOf( - "User-Agent" to "com.google.ios.youtube/21.10.3 (iPhone16,2; U; CPU iOS 18_1_0 like Mac OS X;)", - "Range" to "bytes=0-", - ) - ) - } - if (extractedStreams.isEmpty()) return@runCatching null - - val streamsByHeight = extractedStreams - .filter { (it.height ?: 0) > 0 } - .groupBy { it.height!! } - .mapValues { (_, streams) -> - streams.maxWithOrNull( - compareBy { - if (it.mimeType?.contains("mp4", ignoreCase = true) == true) 1 else 0 - }.thenBy { it.bitrate ?: 0 } - )!! - } - - val availableStreams = streamsByHeight.keys.sortedDescending().map { streamsByHeight[it]!! } - if (availableStreams.isEmpty()) return@runCatching null - - val defaultStream = availableStreams.firstOrNull { it.height == 1080 } - ?: availableStreams.firstOrNull { it.height == 720 } - ?: availableStreams.first() - - SyncedVideoStreamBundle( - videoId = videoId, - defaultStream = defaultStream, - availableStreams = availableStreams, - pairedAudioStreamUrl = pairedAudioUrl, - pairedAudioHeaders = mapOf( - "User-Agent" to "com.google.ios.youtube/21.10.3 (iPhone16,2; U; CPU iOS 18_1_0 like Mac OS X;)", - "Range" to "bytes=0-", - ), - ) - }.getOrNull() - } - - private fun parseResolutionHeight(resolution: String?, height: Int): Int { - if (height > 0) return height - // First number only: "1080p60" is 1080 tall. - return Regex("""\d+""").find(resolution.orEmpty())?.value?.toIntOrNull() ?: 0 - } - - internal fun probePlayableVideo(stream: YouTubeVideoStream): Boolean { - val request = playbackProbeRequest(stream.url, stream.requestHeaders) - val call = http.newCall(request) - call.timeout().timeout(PROBE_TIMEOUT_MS, java.util.concurrent.TimeUnit.MILLISECONDS) - return try { - call.execute().use { response -> - acceptsPlaybackProbe(response.code, response.header("Content-Type").orEmpty()) - } - } catch (cancellation: kotlinx.coroutines.CancellationException) { - throw cancellation - } catch (_: Exception) { - false - } - } - - private fun org.schabi.newpipe.extractor.stream.VideoStream.toYouTubeVideoStream( - videoId: String, - durationSeconds: Long, - now: Long, - ): YouTubeVideoStream { - val streamUrl = content - return YouTubeVideoStream( - videoId = videoId, - url = streamUrl, - itag = itag.takeIf { it >= 0 }, - mimeType = format?.mimeType, - codec = codec?.takeIf(String::isNotBlank), - resolution = resolution, - width = width.takeIf { it > 0 }, - height = height.takeIf { it > 0 }, - bitrate = bitrate.takeIf { it > 0 }, - durationMs = itagItem?.approxDurationMs?.takeIf { it > 0 } - ?: durationSeconds.takeIf { it > 0 }?.times(1_000L), - requestHeaders = mapOf( - "User-Agent" to YOUTUBE_WEB_USER_AGENT, - "Origin" to YOUTUBE_ORIGIN, - "Referer" to "$YOUTUBE_ORIGIN/watch?v=$videoId", - ), - expiresAtEpochMs = streamUrl.toHttpUrlOrNull() - ?.queryParameter("expire") - ?.toLongOrNull() - ?.times(1_000L) - ?: (now + UNKNOWN_EXPIRY_TTL_MS), - ) - } - private fun org.schabi.newpipe.extractor.stream.AudioStream.toYouTubeAudioStream( - videoId: String, - durationSeconds: Long, - now: Long, - ): YouTubeAudioStream { - val reportedBitrate = maxOf(averageBitrate, bitrate) - return YouTubeAudioStream( - videoId = videoId, - url = content, - isDrc = isDrcAudioUrl(content.orEmpty()), - itag = itag.takeIf { it >= 0 }, - mimeType = format?.mimeType, - codec = codec?.takeIf(String::isNotBlank), - // NewPipe reports kbps while raw InnerTube formats report bps; - // normalize both providers to bps for one truthful UI value. - bitrate = if (reportedBitrate in 1..9_999) reportedBitrate * 1_000 else reportedBitrate, - sampleRateHz = itagItem?.sampleRate?.takeIf { it > 0 }, - durationMs = itagItem?.approxDurationMs?.takeIf { it > 0 } - ?: durationSeconds.takeIf { it > 0 }?.times(1_000L), - contentLength = itagItem?.contentLength?.takeIf { it > 0 }, - isAdaptive = true, - clientProfile = NEWPIPE_CLIENT_PROFILE, - authScope = ANONYMOUS_AUTH_SCOPE, - requestHeaders = mapOf( - "User-Agent" to YOUTUBE_WEB_USER_AGENT, - "Origin" to YOUTUBE_ORIGIN, - "Referer" to "$YOUTUBE_ORIGIN/watch?v=$videoId", - ), - expiresAtEpochMs = content.toHttpUrlOrNull() - ?.queryParameter("expire") - ?.toLongOrNull() - ?.times(1_000L) - ?: now + UNKNOWN_EXPIRY_TTL_MS, - userAgent = YOUTUBE_WEB_USER_AGENT, - ) - } - - private fun audioPreference( - stream: org.schabi.newpipe.extractor.stream.AudioStream, - preferM4a: Boolean, - preferOpus: Boolean, - ): Int { - val mime = stream.format?.mimeType.orEmpty().lowercase() - val opus = mime.contains("webm") || stream.codec?.contains("opus", ignoreCase = true) == true - val m4a = mime.contains("mp4") || mime.contains("m4a") - return when { - preferOpus && opus -> 0 - preferM4a && m4a -> 0 - stream.itag == 140 || m4a -> 1 - stream.itag == 251 || opus -> 2 - else -> 3 - } - } - - /** - * Opens the URL the way ExoPlayer does: no two-byte range. A 206 for - * `bytes=0-1` is not evidence the player can read the stream. The body - * is closed as soon as the status line is known. - */ - private fun probePlayable(stream: YouTubeAudioStream): Boolean { - val request = playbackProbeRequest(stream.url, stream.requestHeaders) - val call = http.newCall(request) - call.timeout().timeout(PROBE_TIMEOUT_MS, java.util.concurrent.TimeUnit.MILLISECONDS) - return try { - call.execute().use { response -> - acceptsPlaybackProbe(response.code, response.header("Content-Type").orEmpty()) - } - } catch (cancellation: kotlinx.coroutines.CancellationException) { - throw cancellation - } catch (_: Exception) { - false - } - } - - suspend fun getSignatureTimestamp(videoId: String): Int? = withContext(Dispatchers.IO) { - initialize() - try { - YoutubeJavaScriptPlayerManager.getSignatureTimestamp(videoId) - } catch (error: kotlinx.coroutines.CancellationException) { - throw error - } catch (_: Exception) { - null - } - } - - fun decipherStreamUrl(videoId: String, signatureCipher: String): String? { - initialize() - val parameters = "https://cipher.invalid/?$signatureCipher".toHttpUrlOrNull() ?: return null - var resolvedUrl = parameters.queryParameter("url") ?: run { - Log.w("LastWaveCipher", "stage=parse outcome=missing-url") - return null - } - val encryptedSignature = parameters.queryParameter("s") - if (!encryptedSignature.isNullOrBlank()) { - val signature = runCatching { - YoutubeJavaScriptPlayerManager.deobfuscateSignature(videoId, encryptedSignature) - }.onFailure { error -> - // Exception messages can contain URLs or cipher material: log types only. - Log.w("LastWaveCipher", "stage=signature error=${error.javaClass.simpleName} cause=${error.cause?.javaClass?.simpleName}") - }.getOrNull() ?: return null - if (resolvedUrl.toHttpUrlOrNull() == null) return null - resolvedUrl = appendQueryParameterPreservingUrl( - url = resolvedUrl, - name = parameters.queryParameter("sp") ?: "signature", - value = signature, - ) - } - return runCatching { - YoutubeJavaScriptPlayerManager.getUrlWithThrottlingParameterDeobfuscated(videoId, resolvedUrl) - }.getOrDefault(resolvedUrl) - } - - fun deobfuscateThrottlingParameter(videoId: String, url: String): String { - initialize() - return runCatching { - YoutubeJavaScriptPlayerManager.getUrlWithThrottlingParameterDeobfuscated(videoId, url) - }.getOrDefault(url) - } - - /** A rejected signed URL usually means NewPipe's cached player script is - * stale. Clear that state locally so playback can recover without an app - * force-stop. */ - fun invalidatePlayerState(videoId: String) { - invalidateCache(videoId) - runCatching { YoutubeJavaScriptPlayerManager.clearAllCaches() } - } - - fun preWarm() { - initialize() - } - - private fun appendQueryParameterPreservingUrl(url: String, name: String, value: String): String { - val fragmentIndex = url.indexOf('#').takeIf { it >= 0 } ?: url.length - val base = url.substring(0, fragmentIndex) - val fragment = url.substring(fragmentIndex) - val separator = when { - base.endsWith('?') || base.endsWith('&') -> "" - '?' in base -> "&" - else -> "?" - } - return "$base$separator${Uri.encode(name)}=${Uri.encode(value)}$fragment" - } - - private fun initialize() { - if (initialized) return - synchronized(this) { - if (initialized) return - NewPipe.init(downloader) - initialized = true - } - } - - companion object { - private const val UNKNOWN_EXPIRY_TTL_MS = 5 * 60 * 1000L - private const val MAX_PROBED_AUDIO_STREAMS = 4 - private const val PROBE_TIMEOUT_MS = 1_500L - private const val NEWPIPE_CLIENT_PROFILE = "NEWPIPE" - private const val ANONYMOUS_AUTH_SCOPE = "anonymous" - } -} - -internal const val YOUTUBE_ORIGIN = "https://www.youtube.com" - -/** Where googlevideo stops authorising some clients' URLs: the first MiB plays, the rest is 403. */ -internal const val PROBE_AUTH_BOUNDARY_BYTES = 1L * 1024 * 1024 -internal const val PROBE_WINDOW_BYTES = 1L * 1024 * 1024 -/** How much of the probe's answer must arrive, so a body that stalls after its headers fails. */ -internal const val PROBE_READ_BYTES = 16L * 1024 - -/** - * A full 1 MiB window (two-byte probes hide media HTTP 403s), taken just past - * [PROBE_AUTH_BOUNDARY_BYTES] when the URL's `clen` says the file reaches it. - * A probe of the opening passed for URLs that serve only the first MiB, and - * the song then stopped about a minute in; reading where that cut-off bites - * rejects them before playback instead. - */ -internal fun playbackProbeRequest(url: String, headers: Map): okhttp3.Request { - val length = url.toHttpUrlOrNull()?.queryParameter("clen")?.toLongOrNull()?.takeIf { it > 0L } - val start = if (length != null && length > PROBE_AUTH_BOUNDARY_BYTES + PROBE_READ_BYTES) { - PROBE_AUTH_BOUNDARY_BYTES - } else { - 0L - } - val end = (start + PROBE_WINDOW_BYTES - 1).let { if (length != null) minOf(it, length - 1) else it } - return okhttp3.Request.Builder() - .url(url) - .header("Accept", "audio/*,*/*;q=0.8") - .header("Accept-Encoding", "identity") - .header("Range", "bytes=$start-$end") - .apply { - headers.forEach { (name, value) -> header(name, value) } - } - .build() -} - -/** HTTP 403 and 410 are not playable. A tiny 206 is only accepted when the open itself succeeded. */ -internal fun acceptsPlaybackProbe(code: Int, contentType: String): Boolean { - if (code == 403 || code == 410) return false - val type = contentType.lowercase() - val playableType = !type.contains("text/html") && - !type.contains("application/json") && - !type.contains("text/plain") - return (code == 200 || code == 206) && playableType -} - -/** - * Probes at most [limit] distinct URLs. A failed candidate is not retried. - * [probe] may throw [kotlinx.coroutines.CancellationException]. - */ -internal fun selectProbedCandidate( - candidates: List, - urlOf: (T) -> String, - probe: (T) -> Boolean, - limit: Int, -): T? { - val seen = HashSet() - var probed = 0 - for (candidate in candidates) { - if (probed >= limit) break - val url = urlOf(candidate) - if (url.isBlank() || !seen.add(url)) continue - probed++ - if (probe(candidate)) return candidate - } - return null -} - -private class OkHttpNewPipeDownloader( - private val http: OkHttpClient, -) : Downloader() { - override fun execute(request: Request): Response { - val headers = request.headers() - val requestBuilder = okhttp3.Request.Builder() - .url(request.url()) - .method(request.httpMethod(), request.dataToSend()?.toRequestBody()) - - headers.forEach { (name, values) -> - values.forEach { value -> requestBuilder.addHeader(name, value) } - } - if (headers.keys.none { it.equals("User-Agent", ignoreCase = true) }) { - requestBuilder.header("User-Agent", YOUTUBE_WEB_USER_AGENT) - } - if (headers.keys.none { it.equals("Accept-Language", ignoreCase = true) }) { - requestBuilder.header("Accept-Language", "en-US,en;q=0.9") - } - val origin = if (request.url().contains("music.youtube.com", ignoreCase = true)) { - "https://music.youtube.com" - } else { - YOUTUBE_ORIGIN - } - if (headers.keys.none { it.equals("Origin", ignoreCase = true) }) { - requestBuilder.header("Origin", origin) - } - if (headers.keys.none { it.equals("Referer", ignoreCase = true) }) { - requestBuilder.header("Referer", "$origin/") - } - - return http.newCall(requestBuilder.build()).execute().use { response -> - Response( - response.code, - response.message, - response.headers.names().associateWith(response.headers::values), - response.body?.string().orEmpty(), - response.request.url.toString(), - ) - } - } -} - -internal const val YOUTUBE_WEB_USER_AGENT = - "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:140.0) Gecko/20100101 Firefox/140.0" diff --git a/app/src/main/java/com/lastwave/app/data/music/YouTubeVideoStream.kt b/app/src/main/java/com/lastwave/app/data/music/YouTubeVideoStream.kt index eb92109793..657de32204 100644 --- a/app/src/main/java/com/lastwave/app/data/music/YouTubeVideoStream.kt +++ b/app/src/main/java/com/lastwave/app/data/music/YouTubeVideoStream.kt @@ -47,7 +47,7 @@ data class SyncedVideoStreamBundle( val pairedAudioStreamUrl: String? = null, val pairedAudioHeaders: Map = emptyMap(), val pairedAudioBitrate: Int? = null, - /** The InnerTube client behind these links; null for NewPipe. */ + /** The InnerTube client behind these links. */ val clientName: String? = null, val introOffsetMs: Long = 0L, val isDirectOmv: Boolean = false, diff --git a/app/src/main/java/com/lastwave/app/data/video/SyncedVideoRepository.kt b/app/src/main/java/com/lastwave/app/data/video/SyncedVideoRepository.kt index f879dbb5cc..a899a12cd3 100644 --- a/app/src/main/java/com/lastwave/app/data/video/SyncedVideoRepository.kt +++ b/app/src/main/java/com/lastwave/app/data/video/SyncedVideoRepository.kt @@ -5,7 +5,6 @@ import android.util.Log import com.lastwave.app.data.music.InnerTubeMusicApi import com.lastwave.app.data.music.SyncedVideoStreamBundle import com.lastwave.app.data.music.TextMatch -import com.lastwave.app.data.music.YouTubeStreamExtractor import com.lastwave.app.data.music.isSameSongVideo import dagger.hilt.android.qualifiers.ApplicationContext import kotlinx.coroutines.CancellationException @@ -171,7 +170,6 @@ private const val NO_CONFIDENT_OFFSET = Long.MIN_VALUE @Singleton class SyncedVideoRepository @Inject constructor( private val innerTube: InnerTubeMusicApi, - private val streamExtractor: YouTubeStreamExtractor, private val http: OkHttpClient, @ApplicationContext private val appContext: Context, ) { @@ -253,7 +251,8 @@ class SyncedVideoRepository @Inject constructor( } private suspend fun resolveBundle(videoId: String, avoidClientName: String?): SyncedVideoStreamBundle = - innerTube.resolveVideoStreamBundle(videoId, avoidClientName) ?: streamExtractor.resolveVideoStreamBundle(videoId) + innerTube.resolveVideoStreamBundle(videoId, avoidClientName) + ?: throw IllegalStateException("No playable video stream found for $videoId") suspend fun resolveVideo( trackTitle: String, diff --git a/app/src/test/java/com/lastwave/app/data/music/ArtistCreditParserTest.kt b/app/src/test/java/com/lastwave/app/data/music/ArtistCreditParserTest.kt index fcc3cf4771..694beb9ba2 100644 --- a/app/src/test/java/com/lastwave/app/data/music/ArtistCreditParserTest.kt +++ b/app/src/test/java/com/lastwave/app/data/music/ArtistCreditParserTest.kt @@ -16,7 +16,6 @@ class ArtistCreditParserTest { fun setUp() { api = InnerTubeMusicApi( http = mockk(relaxed = true), - streamExtractor = mockk(relaxed = true), innerTubeXExtractor = mockk(relaxed = true), ytAuth = mockk(relaxed = true), settingsPreferences = mockk(relaxed = true), diff --git a/app/src/test/java/com/lastwave/app/data/music/HomeChipsAndPaginationParserTest.kt b/app/src/test/java/com/lastwave/app/data/music/HomeChipsAndPaginationParserTest.kt index 7d1f63e069..4a2eb81e83 100644 --- a/app/src/test/java/com/lastwave/app/data/music/HomeChipsAndPaginationParserTest.kt +++ b/app/src/test/java/com/lastwave/app/data/music/HomeChipsAndPaginationParserTest.kt @@ -18,7 +18,6 @@ class HomeChipsAndPaginationParserTest { fun setUp() { api = InnerTubeMusicApi( http = mockk(relaxed = true), - streamExtractor = mockk(relaxed = true), innerTubeXExtractor = mockk(relaxed = true), ytAuth = mockk(relaxed = true), settingsPreferences = mockk(relaxed = true), diff --git a/app/src/test/java/com/lastwave/app/data/music/HomeCommunityDiscoverDataTest.kt b/app/src/test/java/com/lastwave/app/data/music/HomeCommunityDiscoverDataTest.kt index 412f33e947..b2317a380a 100644 --- a/app/src/test/java/com/lastwave/app/data/music/HomeCommunityDiscoverDataTest.kt +++ b/app/src/test/java/com/lastwave/app/data/music/HomeCommunityDiscoverDataTest.kt @@ -11,7 +11,7 @@ import org.junit.Test /** Display-only excerpts from the two 2026-10-25 captures; negative mutations are explicit. */ class HomeCommunityDiscoverDataTest { private val api = InnerTubeMusicApi( - http = mockk(relaxed = true), streamExtractor = mockk(relaxed = true), + http = mockk(relaxed = true), innerTubeXExtractor = mockk(relaxed = true), ytAuth = mockk(relaxed = true), settingsPreferences = mockk(relaxed = true), appContext = mockk(relaxed = true), diff --git a/app/src/test/java/com/lastwave/app/data/music/HomeShelfExtrasTest.kt b/app/src/test/java/com/lastwave/app/data/music/HomeShelfExtrasTest.kt index 33e82c282d..6d134d3818 100644 --- a/app/src/test/java/com/lastwave/app/data/music/HomeShelfExtrasTest.kt +++ b/app/src/test/java/com/lastwave/app/data/music/HomeShelfExtrasTest.kt @@ -20,7 +20,6 @@ class HomeShelfExtrasTest { fun setUp() { api = InnerTubeMusicApi( http = mockk(relaxed = true), - streamExtractor = mockk(relaxed = true), innerTubeXExtractor = mockk(relaxed = true), ytAuth = mockk(relaxed = true), settingsPreferences = mockk(relaxed = true), diff --git a/app/src/test/java/com/lastwave/app/data/music/HomeShelfParserTest.kt b/app/src/test/java/com/lastwave/app/data/music/HomeShelfParserTest.kt index 8fbca045f0..1753d43959 100644 --- a/app/src/test/java/com/lastwave/app/data/music/HomeShelfParserTest.kt +++ b/app/src/test/java/com/lastwave/app/data/music/HomeShelfParserTest.kt @@ -20,7 +20,6 @@ class HomeShelfParserTest { fun setUp() { api = InnerTubeMusicApi( http = mockk(relaxed = true), - streamExtractor = mockk(relaxed = true), innerTubeXExtractor = mockk(relaxed = true), ytAuth = mockk(relaxed = true), settingsPreferences = mockk(relaxed = true), diff --git a/app/src/test/java/com/lastwave/app/data/music/MoodsParserTest.kt b/app/src/test/java/com/lastwave/app/data/music/MoodsParserTest.kt index 8578331a96..9bcd7ea843 100644 --- a/app/src/test/java/com/lastwave/app/data/music/MoodsParserTest.kt +++ b/app/src/test/java/com/lastwave/app/data/music/MoodsParserTest.kt @@ -115,7 +115,6 @@ class MoodsParserTest { private fun parserApi() = InnerTubeMusicApi( http = mockk(relaxed = true), - streamExtractor = mockk(relaxed = true), innerTubeXExtractor = mockk(relaxed = true), ytAuth = mockk(relaxed = true), settingsPreferences = mockk(relaxed = true), diff --git a/app/src/test/java/com/lastwave/app/data/music/PlaylistPaginationTest.kt b/app/src/test/java/com/lastwave/app/data/music/PlaylistPaginationTest.kt index f0958de11c..0c8fa66a16 100644 --- a/app/src/test/java/com/lastwave/app/data/music/PlaylistPaginationTest.kt +++ b/app/src/test/java/com/lastwave/app/data/music/PlaylistPaginationTest.kt @@ -9,7 +9,6 @@ import org.junit.Test class PlaylistPaginationTest { private val api = InnerTubeMusicApi( http = OkHttpClient(), - streamExtractor = mockk(relaxed = true), innerTubeXExtractor = mockk(relaxed = true), ytAuth = mockk(relaxed = true), settingsPreferences = mockk(relaxed = true), diff --git a/app/src/test/java/com/lastwave/app/data/music/YtRadioParserTest.kt b/app/src/test/java/com/lastwave/app/data/music/YtRadioParserTest.kt index ea7b56054b..edd507c2fc 100644 --- a/app/src/test/java/com/lastwave/app/data/music/YtRadioParserTest.kt +++ b/app/src/test/java/com/lastwave/app/data/music/YtRadioParserTest.kt @@ -16,7 +16,6 @@ class YtRadioParserTest { fun setUp() { api = InnerTubeMusicApi( http = mockk(relaxed = true), - streamExtractor = mockk(relaxed = true), innerTubeXExtractor = mockk(relaxed = true), ytAuth = mockk(relaxed = true), settingsPreferences = mockk(relaxed = true), diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index ca0e98ee4b..5cc71c6983 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -23,7 +23,6 @@ splashscreen = "1.2.0" browser = "1.8.0" material = "1.14.0" profileinstaller = "1.3.1" -newPipeExtractor = "v0.26.5" innerTubeX = "0.11.2" jsoup = "1.18.3" wearCompose = "1.5.0" @@ -70,7 +69,6 @@ room-compiler = { group = "androidx.room", name = "room-compiler", version.ref = datastore-preferences = { group = "androidx.datastore", name = "datastore-preferences", version.ref = "datastore" } coil-compose = { group = "io.coil-kt", name = "coil-compose", version.ref = "coilCompose" } androidx-profileinstaller = { group = "androidx.profileinstaller", name = "profileinstaller", version.ref = "profileinstaller" } -newpipe-extractor = { group = "com.github.TeamNewPipe", name = "NewPipeExtractor", version.ref = "newPipeExtractor" } innertubex = { group = "com.github.MetrolistGroup.innertubex", name = "innertubex", version.ref = "innerTubeX" } jsoup = { group = "org.jsoup", name = "jsoup", version.ref = "jsoup" } androidx-wear-compose-foundation = { group = "androidx.wear.compose", name = "compose-foundation", version.ref = "wearCompose" } From b7fae67227b132636984749b7000b43bad36a4b5 Mon Sep 17 00:00:00 2001 From: ajisth69 Date: Sat, 5 Dec 2026 15:14:31 +0530 Subject: [PATCH 2/5] fix(playback): add 1 MiB boundary probe and chunked range retry --- .../app/data/music/YouTubePlaybackProbe.kt | 71 +++++++++++++ .../app/playback/ChunkedRangeDataSource.kt | 4 + .../com/lastwave/app/playback/MusicPlayer.kt | 99 ++++++++++++------- 3 files changed, 140 insertions(+), 34 deletions(-) create mode 100644 app/src/main/java/com/lastwave/app/data/music/YouTubePlaybackProbe.kt diff --git a/app/src/main/java/com/lastwave/app/data/music/YouTubePlaybackProbe.kt b/app/src/main/java/com/lastwave/app/data/music/YouTubePlaybackProbe.kt new file mode 100644 index 0000000000..0ef650fe4b --- /dev/null +++ b/app/src/main/java/com/lastwave/app/data/music/YouTubePlaybackProbe.kt @@ -0,0 +1,71 @@ +package com.lastwave.app.data.music + +import okhttp3.HttpUrl.Companion.toHttpUrlOrNull + +internal const val YOUTUBE_ORIGIN = "https://www.youtube.com" +internal const val YOUTUBE_WEB_USER_AGENT = + "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:140.0) Gecko/20100101 Firefox/140.0" + +/** Where googlevideo stops authorising some clients' URLs: the first MiB plays, the rest is 403. */ +internal const val PROBE_AUTH_BOUNDARY_BYTES = 1L * 1024 * 1024 +internal const val PROBE_WINDOW_BYTES = 1L * 1024 * 1024 +/** How much of the probe's answer must arrive, so a body that stalls after its headers fails. */ +internal const val PROBE_READ_BYTES = 16L * 1024 + +/** + * A full 1 MiB window (two-byte probes hide media HTTP 403s), taken just past + * [PROBE_AUTH_BOUNDARY_BYTES] when the URL's `clen` says the file reaches it. + * A probe of the opening passed for URLs that serve only the first MiB, and + * the song then stopped about a minute in; reading where that cut-off bites + * rejects them before playback instead. + */ +internal fun playbackProbeRequest(url: String, headers: Map): okhttp3.Request { + val length = url.toHttpUrlOrNull()?.queryParameter("clen")?.toLongOrNull()?.takeIf { it > 0L } + val start = if (length != null && length > PROBE_AUTH_BOUNDARY_BYTES + PROBE_READ_BYTES) { + PROBE_AUTH_BOUNDARY_BYTES + } else { + 0L + } + val end = (start + PROBE_WINDOW_BYTES - 1).let { if (length != null) minOf(it, length - 1) else it } + return okhttp3.Request.Builder() + .url(url) + .header("Accept", "audio/*,*/*;q=0.8") + .header("Accept-Encoding", "identity") + .header("Range", "bytes=$start-$end") + .apply { + headers.forEach { (name, value) -> header(name, value) } + } + .build() +} + +/** HTTP 403 and 410 are not playable. A tiny 206 is only accepted when the open itself succeeded. */ +internal fun acceptsPlaybackProbe(code: Int, contentType: String): Boolean { + if (code == 403 || code == 410) return false + val type = contentType.lowercase() + val playableType = !type.contains("text/html") && + !type.contains("application/json") && + !type.contains("text/plain") + return (code == 200 || code == 206) && playableType +} + +/** + * Probes at most [limit] distinct URLs. A failed candidate is not retried. + * [probe] may throw [kotlinx.coroutines.CancellationException]. + */ +internal fun selectProbedCandidate( + candidates: List, + urlOf: (T) -> String, + probe: (T) -> Boolean, + limit: Int, +): T? { + val seen = HashSet() + var probed = 0 + for (candidate in candidates) { + if (probed >= limit) break + val url = urlOf(candidate) + if (url.isBlank() || !seen.add(url)) continue + probed++ + if (probe(candidate)) return candidate + } + return null +} diff --git a/app/src/main/java/com/lastwave/app/playback/ChunkedRangeDataSource.kt b/app/src/main/java/com/lastwave/app/playback/ChunkedRangeDataSource.kt index 2a43ef4d53..f6911c976e 100644 --- a/app/src/main/java/com/lastwave/app/playback/ChunkedRangeDataSource.kt +++ b/app/src/main/java/com/lastwave/app/playback/ChunkedRangeDataSource.kt @@ -131,6 +131,7 @@ class ChunkedRangeDataSource( */ private fun openChunkRefreshingOnRejection(chunkSpec: DataSpec): Long { var spec = chunkSpec + var transientRetries = 0 while (true) { try { return openUpstream(spec) @@ -149,6 +150,9 @@ class ChunkedRangeDataSource( ?.setUri(replacement.uri) ?.setHttpRequestHeaders(spec.httpRequestHeaders) ?.build() + } catch (error: IOException) { + if (bytesReadTotal <= 0L || transientRetries >= 1) throw error + transientRetries++ } } } diff --git a/app/src/main/java/com/lastwave/app/playback/MusicPlayer.kt b/app/src/main/java/com/lastwave/app/playback/MusicPlayer.kt index f5a18cf82f..f82cbbb668 100644 --- a/app/src/main/java/com/lastwave/app/playback/MusicPlayer.kt +++ b/app/src/main/java/com/lastwave/app/playback/MusicPlayer.kt @@ -871,14 +871,19 @@ class MusicPlayer @Inject constructor( val fresh = runBlocking(Dispatchers.IO) { withTimeoutOrNull(SEAMLESS_URL_REFRESH_TIMEOUT_MS) { runCatching { - // Cools down the client that minted the refused URL, so the - // re-resolve lands on a different one. - innerTube.reportPlaybackFailure(candidate.videoId, candidate) + // First try re-minting on the same preferred client (VISIONOS) + // so itag and contentLength match for seamless byte continuation; + // only cool down the client if the fresh mint also differs/fails. + innerTube.invalidateCache(candidate.videoId) innerTube.resolveAudioStream(candidate.videoId) }.getOrNull() } - } ?: return null + } ?: run { + innerTube.reportPlaybackFailure(candidate.videoId, candidate) + return null + } if (fresh.itag != itag || fresh.contentLength != contentLength || fresh.url == failedUrl) { + innerTube.reportPlaybackFailure(candidate.videoId, candidate) android.util.Log.i( "MusicPlayer", "[SEAMLESS] no same-file replacement for ${candidate.videoId} " + @@ -890,9 +895,15 @@ class MusicPlayer @Inject constructor( "MusicPlayer", "[SEAMLESS] swapped refused URL for ${candidate.videoId}: ${candidate.clientProfile} -> ${fresh.clientProfile}", ) + val replacementHeaders = buildMap { + putAll(fresh.requestHeaders) + if (keys.none { it.equals("User-Agent", ignoreCase = true) } && fresh.userAgent.isNotBlank()) { + put("User-Agent", fresh.userAgent) + } + } val replacement = ChunkedRangeDataSource.Replacement( uri = Uri.parse(fresh.url), - requestHeaders = fresh.requestHeaders + ("User-Agent" to fresh.userAgent), + requestHeaders = replacementHeaders, ) if (refreshedYouTubeUrls.size > MAX_REFRESHED_URL_ENTRIES) refreshedYouTubeUrls.clear() refreshedYouTubeUrls[failedUrl] = replacement @@ -7203,7 +7214,7 @@ class MusicPlayer @Inject constructor( } } - /** Rematch an unplayable stored ID once so callers can persist its replacement. */ + /** Rematch an unplayable stored ID (up to 2 attempts, excluding failed IDs) so callers can persist its replacement. */ private suspend fun resolveRematchedYoutubeStream( track: PlayableTrack, deadVideoId: String, @@ -7211,35 +7222,57 @@ class MusicPlayer @Inject constructor( requestedQuality: Int, deadFailure: Throwable, ): ResolvedStream { - val deadIdentity = TrackIdentity( + var currentClaimIdentity = TrackIdentity( trackId = track.internalTrackId?.takeIf { it.isNotBlank() } ?: deadVideoId, youtubeVideoId = deadVideoId, ) - val matchId = try { - findPlaybackVideoId(track, claimPlayback) - } catch (failure: Exception) { - if (failure is CancellationException) throw failure - null - }?.takeUnless { it == deadVideoId } - // Keep the original message: it may name the cause (age restriction). - ?: throw java.io.IOException(deadFailure.message ?: "Unable to resolve a playable audio stream for $deadVideoId", deadFailure) - val identity = TrackIdentity(matchId, matchId) - if (claimPlayback) streamResolver.playback.replaceClaim(deadIdentity, identity) - val entry = try { - resolveYoutubeEntry(identity, track.durationMs, claimPlayback, requestedQuality) - } catch (failure: Throwable) { - if (claimPlayback && streamResolver.playback.requested == identity) { - runCatching { streamResolver.playback.replaceClaim(identity, deadIdentity) } + val excluded = linkedSetOf(deadVideoId) + var lastError: Throwable = deadFailure + for (attempt in 0 until 2) { + val matchId = try { + if (claimPlayback && attempt == 0) PlaybackStartupLog.videoIdLookupStart() + innerTube.findBestMatch( + title = track.title, + artist = track.artist, + prefetchStreams = false, + excludedVideoId = deadVideoId, + excludedVideoIds = excluded, + expectedDurationMs = track.durationMs, + ).videoId.takeIf { it.isNotBlank() && it !in excluded } + } catch (failure: Exception) { + if (failure is CancellationException) throw failure + null + } finally { + if (claimPlayback && attempt == 0) PlaybackStartupLog.videoIdLookupEnd() + } ?: break + excluded += matchId + val identity = TrackIdentity(matchId, matchId) + if (claimPlayback) { + streamResolver.playback.replaceClaim(currentClaimIdentity, identity) + currentClaimIdentity = identity + } + try { + val entry = resolveYoutubeEntry(identity, track.durationMs, claimPlayback, requestedQuality) + return acceptResolvedIdentity( + track = track, + identity = identity, + entry = entry, + requestedIdOverride = matchId, + claimPlayback = claimPlayback, + ).copy(rematchedFromVideoId = deadVideoId) + } catch (failure: Throwable) { + if (failure is CancellationException || failure is com.lastwave.app.playback.resolve.StaleResolveException) { + throw failure + } + lastError = failure + innerTube.reportPlaybackFailure(matchId) + if (attempt == 1) throw failure } - throw failure } - return acceptResolvedIdentity( - track = track, - identity = identity, - entry = entry, - requestedIdOverride = matchId, - claimPlayback = claimPlayback, - ).copy(rematchedFromVideoId = deadVideoId) + throw java.io.IOException( + lastError.message ?: "Unable to resolve a playable audio stream for $deadVideoId", + lastError, + ) } private suspend fun vpnYoutubeLoginRequiredExceptionOrNull(): VpnYoutubeLoginRequiredException? { @@ -9508,17 +9541,15 @@ internal fun com.lastwave.app.playback.resolve.StreamCache.toPlayerStream(): Mus } ?: "WEBM" val codec = when { rawCodec.contains("OPUS") || rawCodec == "WEBM" -> "OPUS" - rawCodec.contains("M4A") || rawCodec.contains("MP4") || rawCodec.contains("MP4A") || rawCodec.contains("AAC") -> "AAC" + rawCodec.contains("M4A") || rawCodec.contains("MP4") || rawCodec.contains("MP4A") || rawCodec.contains("AAC") || rawCodec == "HLS" -> "AAC" else -> rawCodec } val cleanMime = ytStream.mimeType?.substringBefore(';')?.trim().orEmpty() val headers = buildMap { putAll(ytStream.requestHeaders) - if (!ytStream.userAgent.isNullOrBlank()) { + if (keys.none { it.equals("User-Agent", ignoreCase = true) } && !ytStream.userAgent.isNullOrBlank()) { put("User-Agent", ytStream.userAgent) } - put("Origin", "https://music.youtube.com") - put("Referer", "https://music.youtube.com/") } return MusicPlayer.ResolvedStream( url = ytStream.url, From 6b6b84c6d3fdfe5b04906a74c096cde47c6be718 Mon Sep 17 00:00:00 2001 From: ajisth69 Date: Sat, 5 Dec 2026 15:14:32 +0530 Subject: [PATCH 3/5] fix(innertube): align clients with Metrolist and keep VISIONOS first --- .../app/data/music/InnerTubeMusicModels.kt | 269 ++++++++++-------- .../data/music/InnerTubeXStreamExtractor.kt | 25 +- .../app/data/music/YouTubePlaybackRequest.kt | 52 +++- 3 files changed, 213 insertions(+), 133 deletions(-) diff --git a/app/src/main/java/com/lastwave/app/data/music/InnerTubeMusicModels.kt b/app/src/main/java/com/lastwave/app/data/music/InnerTubeMusicModels.kt index 4109316958..f3845bad41 100644 --- a/app/src/main/java/com/lastwave/app/data/music/InnerTubeMusicModels.kt +++ b/app/src/main/java/com/lastwave/app/data/music/InnerTubeMusicModels.kt @@ -281,27 +281,55 @@ data class PlayerClient( val deviceMake: String? = null, val deviceModel: String? = null, val androidSdkVersion: String? = null, + val id: String = name, + val platform: String? = null, + val loginSupported: Boolean = false, + val loginRequired: Boolean = false, + val includeUserAgentInContext: Boolean = false, + val useMusicPlayerEndpoint: Boolean = false, + val isProgressiveOnly: Boolean = false, ) { - val key = "$name@$version" + val key = "$id@$version" + val isEmbedded: Boolean + get() = name == "WEB_EMBEDDED_PLAYER" || name == "TVHTML5_SIMPLY_EMBEDDED_PLAYER" + val requiresCipher: Boolean + get() = name == "WEB_REMIX" || name == "WEB_CREATOR" || name == "TVHTML5_SIMPLY" || + name == "WEB_KIDS" || name == "TVHTML5" || name == "WEB_EMBEDDED_PLAYER" || name == "MWEB" val needsSignatureTimestamp: Boolean - get() = name == "WEB_REMIX" || name == "WEB_EMBEDDED_PLAYER" || name == "MWEB" || name == "TVHTML5_SIMPLY_EMBEDDED_PLAYER" + get() = requiresCipher || name == "TVHTML5_SIMPLY_EMBEDDED_PLAYER" val needsPoToken: Boolean - get() = name == "WEB_REMIX" || name == "WEB_EMBEDDED_PLAYER" || name == "MWEB" || name == "ANDROID_MUSIC" || name == "ANDROID" + get() = name == "WEB_REMIX" || name == "WEB_CREATOR" || name == "TVHTML5_SIMPLY" || + name == "WEB_EMBEDDED_PLAYER" || name == "MWEB" || name == "ANDROID_MUSIC" || name == "ANDROID" val needsGvsPoToken: Boolean get() = needsPoToken || name == "TVHTML5" || name == "TVHTML5_SIMPLY_EMBEDDED_PLAYER" - val origin = if (name == "WEB_REMIX") YOUTUBE_MUSIC_ORIGIN else YOUTUBE_ORIGIN - val referer = when (name) { - "WEB_REMIX" -> "$YOUTUBE_MUSIC_ORIGIN/" - "TVHTML5", "TVHTML5_SIMPLY_EMBEDDED_PLAYER" -> "$YOUTUBE_ORIGIN/tv" - "WEB_EMBEDDED_PLAYER" -> "$YOUTUBE_ORIGIN/embed" - else -> "$YOUTUBE_ORIGIN/" - } - val streamRequestHeaders = buildMap { - put("User-Agent", userAgent) - put("X-YouTube-Client-Name", CLIENT_IDS[name] ?: name) - put("X-YouTube-Client-Version", version) - put("Origin", origin) - put("Referer", referer) + val requiresWebOrigin: Boolean + get() = name == "WEB_REMIX" || name == "WEB_CREATOR" || name == "TVHTML5" || + name == "TVHTML5_SIMPLY_EMBEDDED_PLAYER" || name == "WEB_EMBEDDED_PLAYER" || + name == "MWEB" || name == "WEB_KIDS" + val stripsMediaHeaders: Boolean + get() = name == "VISIONOS" || name == "ANDROID_VR" || name == "TVHTML5_SIMPLY" + val playerApiBase: String + get() = when { + name == "WEB_REMIX" || useMusicPlayerEndpoint -> MUSIC_API + name == "WEB_CREATOR" -> STUDIO_API + name == "MWEB" -> MWEB_API + else -> YOUTUBE_API + } + val origin: String + get() = when { + name == "WEB_REMIX" || useMusicPlayerEndpoint -> YOUTUBE_MUSIC_ORIGIN + name == "WEB_CREATOR" -> YOUTUBE_STUDIO_ORIGIN + name == "MWEB" -> YOUTUBE_MWEB_ORIGIN + else -> YOUTUBE_ORIGIN + } + val referer: String + get() = if (isEmbedded) "https://www.reddit.com/" else "$origin/" + // Mirrors Metrolist InnerTubeExtractor.buildHeaders(): non-web clients do not attach Origin/Referer. + val streamRequestHeaders: Map = buildMap { + if (!stripsMediaHeaders && requiresWebOrigin) { + put("Origin", origin) + put("Referer", referer) + } } } @@ -313,23 +341,32 @@ internal val ENGLISH_COUNTRIES = setOf("US", "GB", "CA", "AU", "NZ", "IE", "ZA") internal val JSON_MEDIA_TYPE = "application/json; charset=utf-8".toMediaType() internal val CLIENT_IDS = mapOf( "WEB" to "1", - "WEB_REMIX" to "67", + "MWEB" to "2", + "ANDROID" to "3", "IOS" to "5", - "IOS_MUSIC" to "26", + "TVHTML5" to "7", + "ANDROID_CREATOR" to "14", "IOS_CREATOR" to "15", - "ANDROID" to "3", + "ANDROID_KIDS" to "18", "ANDROID_MUSIC" to "21", + "IOS_MUSIC" to "26", "ANDROID_VR" to "28", "ANDROID_TESTSUITE" to "30", - "ANDROID_CREATOR" to "14", - "TVHTML5" to "7", + "WEB_EMBEDDED_PLAYER" to "56", + "WEB_CREATOR" to "62", + "WEB_REMIX" to "67", + "TVHTML5_SIMPLY" to "75", + "WEB_KIDS" to "76", "TVHTML5_SIMPLY_EMBEDDED_PLAYER" to "85", + "IOS_PRODUCER" to "92", "VISIONOS" to "101", - "WEB_EMBEDDED_PLAYER" to "56", - "MWEB" to "62", ) internal const val YOUTUBE_MUSIC_ORIGIN = "https://music.youtube.com" +internal const val YOUTUBE_STUDIO_ORIGIN = "https://studio.youtube.com" +internal const val YOUTUBE_MWEB_ORIGIN = "https://m.youtube.com" internal const val MUSIC_API = "https://music.youtube.com/youtubei/v1" +internal const val STUDIO_API = "https://studio.youtube.com/youtubei/v1" +internal const val MWEB_API = "https://m.youtube.com/youtubei/v1" internal const val YOUTUBE_API = "https://www.youtube.com/youtubei/v1" internal const val MUSIC_VIDEO_TYPE_OMV = "MUSIC_VIDEO_TYPE_OMV" internal val VIDEO_ID_PATTERN = Regex("[A-Za-z0-9_-]{11}") @@ -343,24 +380,33 @@ internal const val MAX_CONTINUATION_PAGES = 600 internal const val WRITE_ACTIONS_PER_REQUEST = 50 internal const val HEDGED_CLIENT_STAGGER_DELAY_MS = 300L -internal const val DIRECT_FAST_CLIENT_TIMEOUT_MS = 4_000L -internal const val VISITOR_BOOTSTRAP_BUDGET_MS = 3_000L +internal const val DIRECT_FAST_CLIENT_TIMEOUT_MS = 8_000L +internal const val VISITOR_BOOTSTRAP_BUDGET_MS = 4_000L internal const val VISITOR_BOOTSTRAP_RETRY_COOLDOWN_MS = 60_000L -internal const val POTOKEN_FAST_BUDGET_MS = 1_000L -internal const val DIRECT_FAST_PATH_BUDGET_MS = 6_000L +internal const val POTOKEN_FAST_BUDGET_MS = 8_000L +internal const val DIRECT_FAST_PATH_BUDGET_MS = 16_000L internal const val AUTHENTICATED_CIPHER_PATH_BUDGET_MS = 24_000L internal const val AUTHENTICATED_CIPHER_CLIENT_BUDGET_MS = 20_000L internal const val PLAYER_REQUEST_CALL_TIMEOUT_MS = 20_000L internal const val CLIENT_RACE_TIMEOUT_MS = 8_000L internal const val STREAM_RESOLVE_TOTAL_TIMEOUT_MS = 40_000L -internal const val INNERTUBEX_STAGE_TIMEOUT_MS = 7_000L +internal const val INNERTUBEX_STAGE_TIMEOUT_MS = 10_000L internal const val SIGNED_IN_INNERTUBEX_STAGE_TIMEOUT_MS = 16_000L -internal const val NEWPIPE_FALLBACK_TIMEOUT_MS = 9_000L internal const val YOUTUBE_PROMOTE_BUDGET_MS = 12_000L -internal val DIRECT_FAST_CLIENT_ORDER = listOf("TVHTML5", "VISIONOS", "ANDROID_TESTSUITE", "ANDROID_VR", "WEB_REMIX") +internal const val FAST_PREFERRED_CLIENT = "VISIONOS" +internal val DIRECT_FAST_CLIENT_ORDER = listOf( + "VISIONOS", + "VISIONOS_1_02", + "WEB_REMIX", + "WEB_CREATOR", + "TVHTML5_SIMPLY", + "ANDROID_KIDS", + "WEB_KIDS", + "IOS_PRODUCER", +) internal const val VIDEO_LOG_TAG = "InnerTubeVideo" -internal val VIDEO_CLIENT_ORDER = listOf("ANDROID_VR", "VISIONOS", "IOS", "TVHTML5") +internal val VIDEO_CLIENT_ORDER = listOf("VISIONOS", "ANDROID_VR", "IOS", "TVHTML5") internal val ALIGNMENT_AUDIO_CLIENT_ORDER = listOf("VISIONOS", "ANDROID_VR") internal const val VIDEO_CLIENT_TIMEOUT_MS = 6_000L internal const val VIDEO_CIPHER_CONTEXT_TTL_MS = 30 * 60 * 1000L @@ -378,8 +424,6 @@ internal const val HISTORY_PING_TIMEOUT_MS = 15_000L internal const val URL_EXPIRY_MARGIN_MS = 2 * 60 * 1000L internal const val REQUEST_RETRY_BASE_DELAY_MS = 250L internal const val REQUEST_RETRY_JITTER_MS = 180L -internal const val NEWPIPE_RETRY_BASE_DELAY_MS = 300L -internal const val NEWPIPE_RETRY_JITTER_MS = 220L internal const val UNKNOWN_STREAM_EXPIRY_TTL_MS = 5 * 60 * 1000L internal val CONFIRMED_UNAVAILABLE_REASONS = listOf( @@ -399,7 +443,6 @@ internal const val MAX_STREAM_CACHE_ENTRIES = 64 internal const val STREAM_TTL_MS = 4 * 60 * 60 * 1000L internal const val MAX_MATCH_CACHE_ENTRIES = 1024 internal const val FALLBACK_TOKEN_SESSION = "lastwave_session" -internal const val NEWPIPE_SOURCE = "NEWPIPE" internal const val ANONYMOUS_AUTH_SCOPE = "anonymous" internal const val STREAM_LOG_TAG = "LastWaveStream" internal const val PLAYLIST_LOG_TAG = "LastWavePlaylist" @@ -415,117 +458,119 @@ internal val CODEC_PATTERN = Regex("""codecs?=[\"']([^\"']+)["']""", RegexOption internal val PLAYER_CLIENTS = listOf( PlayerClient( - name = "ANDROID_VR", - version = "1.60.19", - apiKey = "AIzaSyD-p045F_WzU-vA_YgX20SCx4KAo", - userAgent = "com.google.android.apps.youtube.vr.oculus/1.60.19 (Linux; U; Android 12; en_US; Quest 3; Build/SQ3A.220605.009.A1) gzip", - osName = "Android", - osVersion = "12", - deviceMake = "Oculus", - deviceModel = "Quest 3", - androidSdkVersion = "32", + name = "VISIONOS", + version = "0.1", + apiKey = "AIzaSyB-63vPrdThhKuerbB2N_l7Kwwcxj6yUAc", + userAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 14_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Safari/605.1.15", + osName = "VISION_OS", + osVersion = "1.3", + deviceMake = "Apple", + deviceModel = "RealityDevice14,1", + platform = "MOBILE", + useMusicPlayerEndpoint = true, ), PlayerClient( + id = "VISIONOS_1_02", name = "VISIONOS", - version = "0.1", + version = "1.02", apiKey = "AIzaSyB-63vPrdThhKuerbB2N_l7Kwwcxj6yUAc", - userAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Safari/605.1.15", + userAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 15_7_3) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Safari/605.1.15", osName = "visionOS", - osVersion = "1.3.21O771", + osVersion = "26.5.23O471", deviceMake = "Apple", - deviceModel = "RealityDevice14,1", + deviceModel = "RealityDevice17,1", + useMusicPlayerEndpoint = true, ), PlayerClient( - name = "TVHTML5", - version = "7.20260308.08.00", - apiKey = "AIzaSyAO_FJ2SlqAz8GlBg1fA54p0wDE7Xk80mU", - userAgent = "Mozilla/5.0 (SMART-TV; Linux; Tizen 6.0) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/4.0 Chrome/76.0.3809.146 TV Safari/537.36", + name = "WEB_REMIX", + version = FALLBACK_WEB_VERSION, + apiKey = FALLBACK_WEB_KEY, + userAgent = WEB_USER_AGENT, + loginSupported = true, ), PlayerClient( - name = "TVHTML5_SIMPLY_EMBEDDED_PLAYER", - version = "2.0", + name = "WEB_CREATOR", + version = "1.20260708.06.00", + apiKey = FALLBACK_WEB_KEY, + userAgent = WEB_USER_AGENT, + loginSupported = true, + loginRequired = true, + ), + PlayerClient( + name = "TVHTML5_SIMPLY", + version = "1.0", apiKey = "AIzaSyAO_FJ2SlqAz8GlBg1fA54p0wDE7Xk80mU", - userAgent = "Mozilla/5.0 (SMART-TV; Linux; Tizen 6.0) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/4.0 Chrome/76.0.3809.146 TV Safari/537.36", + userAgent = "Mozilla/5.0 (ChromiumStylePlatform) Cobalt/25.lts.30.1034943-gold (unlike Gecko), Unknown_TV_Unknown_0/Unknown (Unknown, Unknown)", + useMusicPlayerEndpoint = true, ), PlayerClient( - name = "ANDROID_TESTSUITE", - version = "1.9", - apiKey = "AIzaSyD-p045F_WzU-vA_YgX20SCx4KAo", - userAgent = "com.google.android.youtube/1.9 (Linux; U; Android 12) gzip", + name = "ANDROID_KIDS", + version = "7.36.1", + apiKey = "AIzaSyA8eiZmM1FaDVjRy-df2KTyQ_vz_yYM39w", + userAgent = "com.google.android.apps.youtube.kids/7.36.1 (Linux; U; Android 11) gzip", osName = "Android", - osVersion = "12", + osVersion = "11", + androidSdkVersion = "30", + includeUserAgentInContext = true, ), PlayerClient( - name = "IOS_MUSIC", - version = "7.27.0", - apiKey = "AIzaSyB-63vPrdThhKuerbB2N_l7Kwwcxj6yUAc", - userAgent = "com.google.ios.youtubemusic/7.27.0 (iPhone16,2; U; CPU iOS 17_5_1 like Mac OS X;)", - osName = "iOS", - osVersion = "17.5.1.21F90", - deviceMake = "Apple", - deviceModel = "iPhone16,2", + name = "WEB_KIDS", + version = "2.20260205.00.00", + apiKey = FALLBACK_WEB_KEY, + userAgent = WEB_USER_AGENT, ), PlayerClient( - name = "ANDROID_MUSIC", - version = "7.27.52", - apiKey = "AIzaSyA8eiZmM1FaDVjRy-df2KTyQ_vz_yYM39w", - userAgent = "com.google.android.apps.youtube.music/7.27.52 (Linux; U; Android 14; en_US; Pixel 8; Build/UD1A.230803.041) gzip", + name = "ANDROID_VR", + version = "1.65.10", + apiKey = "AIzaSyD-p045F_WzU-vA_YgX20SCx4KAo", + userAgent = "com.google.android.apps.youtube.vr.oculus/1.65.10 (Linux; U; Android 12L; eureka-user Build/SQ3A.220605.009.A1) gzip", osName = "Android", - osVersion = "14", - deviceMake = "Google", - deviceModel = "Pixel 8", - androidSdkVersion = "34", + osVersion = "12L", + deviceMake = "Oculus", + deviceModel = "Quest 3", + androidSdkVersion = "32", + includeUserAgentInContext = true, + useMusicPlayerEndpoint = true, ), PlayerClient( - name = "IOS", - version = "20.03.02", + name = "IOS_PRODUCER", + version = "0.10", apiKey = "AIzaSyB-63vPrdThhKuerbB2N_l7Kwwcxj6yUAc", - userAgent = "com.google.ios.youtube/20.03.02 (iPhone16,2; U; CPU iOS 18_2 like Mac OS X;)", + userAgent = "com.google.ios.youtubeproducer/0.10 (iPhone16,2; U; CPU iOS 18_6_2 like Mac OS X;)", osName = "iPhone", - osVersion = "18.2", + osVersion = "18.6.2.22G100", deviceMake = "Apple", deviceModel = "iPhone16,2", + includeUserAgentInContext = true, + isProgressiveOnly = true, ), PlayerClient( - name = "ANDROID", - version = "21.26.364", - apiKey = "AIzaSyA8eiZmM1FaDVjRy-df2KTyQ_vz_yYM39w", - userAgent = "com.google.android.youtube/21.26.364 (Linux; U; Android 11) gzip", - osName = "Android", - osVersion = "11", + name = "TVHTML5", + version = "7.20260707.07.00", + apiKey = "AIzaSyAO_FJ2SlqAz8GlBg1fA54p0wDE7Xk80mU", + userAgent = "Mozilla/5.0 (ChromiumStylePlatform) Cobalt/25.lts.30.1034943-gold (unlike Gecko), Unknown_TV_Unknown_0/Unknown (Unknown, Unknown)", + loginSupported = true, + includeUserAgentInContext = true, ), PlayerClient( - name = "ANDROID_CREATOR", - version = "24.32.100", + name = "ANDROID_MUSIC", + version = "8.25.52", apiKey = "AIzaSyA8eiZmM1FaDVjRy-df2KTyQ_vz_yYM39w", - userAgent = "com.google.android.apps.youtube.creator/24.32.100 (Linux; U; Android 13; en_US) gzip", + userAgent = "com.google.android.apps.youtube.music/8.25.52 (Linux; U; Android 14) gzip", osName = "Android", - osVersion = "13", + osVersion = "14", + androidSdkVersion = "34", + includeUserAgentInContext = true, ), PlayerClient( - name = "IOS_CREATOR", - version = "24.32.100", + name = "IOS", + version = "21.26.4", apiKey = "AIzaSyB-63vPrdThhKuerbB2N_l7Kwwcxj6yUAc", - userAgent = "com.google.ios.creator/24.32.100 (iPhone16,2; U; CPU iOS 17_5_1 like Mac OS X;)", - osName = "iOS", - osVersion = "17.5.1.21F90", - ), - PlayerClient( - name = "WEB_REMIX", - version = FALLBACK_WEB_VERSION, - apiKey = "AIzaSyC9XL3ZjWddXya6X74dJoCTL-WEYFDNX30", - userAgent = WEB_USER_AGENT, - ), - PlayerClient( - name = "WEB_EMBEDDED_PLAYER", - version = FALLBACK_WEB_VERSION, - apiKey = "AIzaSyC9XL3ZjWddXya6X74dJoCTL-WEYFDNX30", - userAgent = WEB_USER_AGENT, - ), - PlayerClient( - name = "MWEB", - version = "2.20260707.01.00", - apiKey = "AIzaSyC9XL3ZjWddXya6X74dJoCTL-WEYFDNX30", - userAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 17_5_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1", + userAgent = "com.google.ios.youtube/21.26.4 (iPhone16,2; U; CPU iOS 18_3_2 like Mac OS X;)", + osName = "iPhone", + osVersion = "18.3.2.22D82", + deviceMake = "Apple", + deviceModel = "iPhone16,2", + includeUserAgentInContext = true, ), ) diff --git a/app/src/main/java/com/lastwave/app/data/music/InnerTubeXStreamExtractor.kt b/app/src/main/java/com/lastwave/app/data/music/InnerTubeXStreamExtractor.kt index ceef7bbe56..f7e07574e0 100644 --- a/app/src/main/java/com/lastwave/app/data/music/InnerTubeXStreamExtractor.kt +++ b/app/src/main/java/com/lastwave/app/data/music/InnerTubeXStreamExtractor.kt @@ -260,7 +260,10 @@ class InnerTubeXStreamExtractor @Inject constructor( val mime = readString(this, "getMimeType")?.substringBefore(';')?.trim().orEmpty() val isHls = mime.equals("application/x-mpegurl", true) || url.substringBefore('?').endsWith(".m3u8", true) if (!isHls && !mime.startsWith("audio/", true)) return null - if (!isHls && mime.lowercase() !in setOf("audio/webm", "audio/mp4", "audio/m4a", "audio/ogg", "audio/mpeg")) return null + val lowerMime = mime.lowercase() + if (!isHls && lowerMime !in setOf("audio/webm", "audio/mp4", "audio/m4a", "audio/mpeg")) return null + val rawCodec = if (isHls) "hls" else readString(this, "getCodecs") + if (!isHls && rawCodec?.contains("vorbis", ignoreCase = true) == true) return null if (!url.startsWith("https://", true)) return null val rawHeaders = (readValue(this, "getHeaders") as? Map<*, *>) @@ -273,9 +276,9 @@ class InnerTubeXStreamExtractor @Inject constructor( .orEmpty() val clientName = readString(this, "getClientName").orEmpty() val profileId = readString(this, "getProfileId").orEmpty() - // Apple-family direct URLs (iOS, iPadOS, visionOS) need an Apple-attested - // GVS token we cannot supply: they stop with 403 about a minute in. - // Excluded up front in [resolve]; never accept one that slips through. + // iOS/iPadOS direct URLs need an Apple-attested GVS token we cannot + // supply (they stop with 403 about a minute in). VISIONOS plays the + // full file over bounded ranges, so only IOS/IPADOS/SABR stay excluded. if (APPLE_CLIENT_PREFIXES.any { clientName.startsWith(it, ignoreCase = true) }) return null val headers = rawHeaders.toMutableMap().apply { if (keys.none { it.equals("User-Agent", ignoreCase = true) }) { @@ -288,12 +291,17 @@ class InnerTubeXStreamExtractor @Inject constructor( ?.let { readLong(it, "getDurationSeconds") } ?.times(1_000L) val profile = profileId.ifBlank { clientName.ifBlank { "INNERTUBEX" } } + val resolvedUserAgent = headers.entries + .firstOrNull { it.key.equals("User-Agent", ignoreCase = true) } + ?.value + ?.takeIf(String::isNotBlank) + ?: WEB_USER_AGENT return YouTubeAudioStream( videoId = videoId, url = url, itag = readInt(this, "getItag"), mimeType = mime.ifBlank { null }, - codec = if (isHls) "hls" else readString(this, "getCodecs"), + codec = rawCodec, bitrate = readInt(this, "getBitrate") ?: 0, sampleRateHz = readInt(this, "getSampleRate"), durationMs = durationMs, @@ -303,6 +311,7 @@ class InnerTubeXStreamExtractor @Inject constructor( authScope = authScope, requestHeaders = headers, expiresAtEpochMs = expiresAt ?: (System.currentTimeMillis() + UNKNOWN_STREAM_EXPIRY_TTL_MS), + userAgent = resolvedUserAgent, isDrc = isDrcAudioUrl(url), ) } @@ -666,12 +675,12 @@ class InnerTubeXStreamExtractor @Inject constructor( /** Long enough to outlast the song it failed on: at 60 s a client that * died a minute in was allowed straight back for the retry. */ const val CLIENT_FAILURE_COOLDOWN_MS = 5 * 60_000L - /** InnerTubeX catalogue ids/client names of the Apple family; it matches either. */ + /** InnerTubeX catalogue ids/client names of iOS/iPadOS/SABR clients to exclude. */ val APPLE_CLIENTS = setOf( - "VISIONOS", "VISIONOS_0_1", "VISIONOS_SABR", + "VISIONOS_SABR", "IOS", "IOS_SABR", "IOS_MUSIC", "IPADOS", ) - val APPLE_CLIENT_PREFIXES = listOf("IOS", "IPADOS", "VISIONOS") + val APPLE_CLIENT_PREFIXES = listOf("IOS", "IPADOS") const val PLAYER_CONFIG_PREFS = "innertubex_player_config" const val PLAYER_CONFIG_URL = "https://raw.githubusercontent.com/MetrolistGroup/faraday/master/registry/player_configs.json" diff --git a/app/src/main/java/com/lastwave/app/data/music/YouTubePlaybackRequest.kt b/app/src/main/java/com/lastwave/app/data/music/YouTubePlaybackRequest.kt index 2e740a245b..b0222c2246 100644 --- a/app/src/main/java/com/lastwave/app/data/music/YouTubePlaybackRequest.kt +++ b/app/src/main/java/com/lastwave/app/data/music/YouTubePlaybackRequest.kt @@ -4,31 +4,57 @@ import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.put -/** Give the cookie-capable client a turn before anonymous clients spend the deadline. */ -internal fun playbackClientPriority(name: String, connected: Boolean, lastSuccessful: String?): Int = when { - connected && name == "WEB_REMIX" -> 0 - name == lastSuccessful -> 1 - else -> 2 +/** + * Always prefer the token-free, no-cipher fast client (VISIONOS) first, then + * VISIONOS 1.02, then other healthy non-cipher clients (or last non-cipher + * winner), then cipher/web clients (WEB_REMIX, WEB_CREATOR, TVHTML5_SIMPLY, etc.), + * and keep progressive muxed fallback (IOS_PRODUCER) strictly last. + */ +internal fun playbackClientPriority(name: String, @Suppress("UNUSED_PARAMETER") connected: Boolean, lastSuccessful: String?): Int { + val requiresCipher = name == "WEB_REMIX" || name == "WEB_CREATOR" || name == "TVHTML5_SIMPLY" || + name == "WEB_KIDS" || name == "TVHTML5" || name == "WEB_EMBEDDED_PLAYER" || name == "MWEB" + return when { + name == FAST_PREFERRED_CLIENT -> 0 + name == "VISIONOS_1_02" -> 1 + name == "IOS_PRODUCER" -> 4 + !requiresCipher && name == lastSuccessful -> 1 + !requiresCipher -> 2 + else -> 3 + } } -/** Player integrity is a top-level field, separate from the client context. */ +/** Matches Metrolist InnerTube.buildPlayerBody() + player integrity fields. */ internal fun playbackPlayerBody( videoId: String, context: JsonObject, signatureTimestamp: Int?, playerPoToken: String?, + useMusicPlayerEndpoint: Boolean = false, + isEmbedded: Boolean = false, ): JsonObject = buildJsonObject { put("context", context) put("videoId", videoId) - put("contentCheckOk", true) - put("racyCheckOk", true) + if (signatureTimestamp != null || isEmbedded) { + put("playbackContext", buildJsonObject { + put("contentPlaybackContext", buildJsonObject { + if (!useMusicPlayerEndpoint) { + put("html5Preference", "HTML5_PREF_WANTS") + } + if (signatureTimestamp != null) { + put("signatureTimestamp", signatureTimestamp) + } + }) + }) + } + if (isEmbedded) { + put("thirdParty", buildJsonObject { put("embedUrl", "https://www.reddit.com/") }) + } if (!playerPoToken.isNullOrBlank()) { put("serviceIntegrityDimensions", buildJsonObject { put("poToken", playerPoToken) }) } - // Only a timestamp extracted from the current player is valid; omit it on extraction failure. - if (signatureTimestamp != null) { - put("playbackContext", buildJsonObject { - put("contentPlaybackContext", buildJsonObject { put("signatureTimestamp", signatureTimestamp) }) - }) + put("contentCheckOk", true) + put("racyCheckOk", true) + if (!useMusicPlayerEndpoint) { + put("videoCheckOk", true) } } From ebbbd9651e047130e6003354a46c01f23a7667a2 Mon Sep 17 00:00:00 2001 From: ajisth69 Date: Sat, 5 Dec 2026 15:14:33 +0530 Subject: [PATCH 4/5] fix(innertube): align stream resolver, headers, and catalog fallback --- .../app/data/music/InnerTubeMusicApi.kt | 290 ++------ .../music/InnerTubeMusicApiStreamResolver.kt | 678 ++++++++++++------ .../data/music/YouTubePlaybackRequestTest.kt | 84 ++- 3 files changed, 592 insertions(+), 460 deletions(-) diff --git a/app/src/main/java/com/lastwave/app/data/music/InnerTubeMusicApi.kt b/app/src/main/java/com/lastwave/app/data/music/InnerTubeMusicApi.kt index da6a39b244..2bc02c86ec 100644 --- a/app/src/main/java/com/lastwave/app/data/music/InnerTubeMusicApi.kt +++ b/app/src/main/java/com/lastwave/app/data/music/InnerTubeMusicApi.kt @@ -64,8 +64,8 @@ import javax.inject.Singleton /** * Client for the same private InnerTube endpoints used by the YouTube Music - * web/mobile clients. Search uses WEB_REMIX; playback delegates first to - * InnerTubeX and keeps the older direct/NewPipe extractors as bounded fallbacks. + * web/mobile clients. Search uses WEB_REMIX; playback resolves through direct + * InnerTube clients first (VISIONOS preferred) with InnerTubeX QuickJS as fallback. * * Anonymous by default — but when a YouTube Music account is connected via * [YtMusicAuthManager], requests can opt in to the account's cookies + @@ -79,7 +79,6 @@ import javax.inject.Singleton @Singleton class InnerTubeMusicApi @Inject constructor( internal val http: OkHttpClient, - internal val streamExtractor: YouTubeStreamExtractor, internal val innerTubeXExtractor: InnerTubeXStreamExtractor, internal val ytAuth: YtMusicAuthManager, internal val settingsPreferences: SettingsPreferences, @@ -174,14 +173,13 @@ class InnerTubeMusicApi @Inject constructor( true } matchCache.values.removeIf { it.videoId == videoId } - streamExtractor.invalidateCache(videoId) } /** Marks the exact extractor/client that produced a rejected URL, then * clears its state so the next attempt cannot pick the same stale result. */ fun reportPlaybackFailure(videoId: String, rejected: YouTubeAudioStream? = null) { val stream = rejected ?: lastResolvedStreams[resolutionKey(videoId, playbackAuthScope())] - if (stream != null && stream.clientProfile != NEWPIPE_SOURCE) { + if (stream != null) { // A reused player script may be the cause; fetch a fresh one next time. if (stream.clientProfile.startsWith("WEB_REMIX")) cachedVideoCipherContext = null failedClientsUntil[clientFailureKey(videoId, stream.clientProfile, stream.authScope)] = @@ -205,11 +203,6 @@ class InnerTubeMusicApi @Inject constructor( request.deferred.cancel() true } - if (stream == null || stream.clientProfile == NEWPIPE_SOURCE) { - streamExtractor.invalidatePlayerState(videoId) - } else { - streamExtractor.invalidateCache(videoId) - } } /** Proactively resolves and seeds the in-memory stream cache in the background */ @@ -1432,6 +1425,52 @@ class InnerTubeMusicApi @Inject constructor( finalResults } + /** + * Unfiltered YouTube Music search (mixed songs + official uploads/videos), + * matching LastWave-Desktop's search_mixed() when Songs-only search returns + * wrong covers/remixes or misses the upload. + */ + suspend fun searchMixed( + query: String, + limit: Int = 20, + ): List = withContext(Dispatchers.IO) { + if (query.isBlank()) return@withContext emptyList() + val config = getWebConfig() + val ytMusic = runCatching { + val body = buildJsonObject { + put("context", context("WEB_REMIX", config.clientVersion, config.visitorData)) + put("query", query.trim()) + } + val root = post( + url = "$MUSIC_API/search?key=${config.apiKey}&prettyPrint=false", + body = body, + clientName = "WEB_REMIX", + clientVersion = config.clientVersion, + userAgent = WEB_USER_AGENT, + callTimeoutMs = SEARCH_REQUEST_TIMEOUT_MS, + ) + parseSongRenderers(root) + }.getOrDefault(emptyList()) + val items = if (ytMusic.isNotEmpty()) ytMusic else runCatching { + val body = buildJsonObject { + put("context", context("WEB", "2.20261011.05.00", null)) + put("query", query.trim()) + } + val root = post( + url = "$YOUTUBE_API/search?key=AIzaSyAO_FJ2SlqAz8GlBg1fA54p0wDE7Xk80mU&prettyPrint=false", + body = body, + clientName = "WEB", + clientVersion = "2.20261011.05.00", + userAgent = WEB_USER_AGENT, + origin = YOUTUBE_ORIGIN, + referer = "$YOUTUBE_ORIGIN/", + callTimeoutMs = SEARCH_REQUEST_TIMEOUT_MS, + ) + parseSongRenderers(root) + }.getOrDefault(emptyList()) + items.distinctBy { it.videoId }.filter { it.videoId.isNotBlank() }.take(limit) + } + suspend fun fetchPodcastHome(): List = withContext(Dispatchers.IO) { val root = podcastBrowseRoot(PODCASTS_BROWSE_ID) PodcastParser.parseHome(root) @@ -2587,7 +2626,7 @@ class InnerTubeMusicApi @Inject constructor( val cachedPlaceholder = webConfig if (cachedPlaceholder == null) { // First config of the session: block — callers cannot - // proceed without any visitor data at all. + // proceed without visitor data (VISIONOS/ANDROID_VR reject empty visitorData). val fetched = try { fetchWebConfig() } catch (cancellation: kotlinx.coroutines.CancellationException) { @@ -2595,9 +2634,21 @@ class InnerTubeMusicApi @Inject constructor( } catch (error: Exception) { null } - if (fetched != null) { - webConfig = fetched - return@withLock fetched + val resolved = if (fetched?.hasRealVisitorData() == true) { + fetched + } else { + val freshVisitor = runCatching { fetchFreshVisitorData() }.getOrNull() + if (isValidVisitorData(freshVisitor)) { + WebConfig( + apiKey = fetched?.apiKey ?: FALLBACK_WEB_KEY, + clientVersion = fetched?.clientVersion ?: FALLBACK_WEB_VERSION, + visitorData = freshVisitor, + ) + } else fetched + } + if (resolved != null) { + webConfig = resolved + return@withLock resolved } } else { // Placeholder in hand: refresh off the critical path so a @@ -2779,9 +2830,9 @@ class InnerTubeMusicApi @Inject constructor( val userCookies = ytAuth.cookieHeaderValue(account) val fullCookies = if (userCookies.isNullOrBlank()) consentCookies else "$consentCookies; $userCookies" builder.header("Cookie", fullCookies) - ytAuth.authorizationHeaderValue(account = account)?.let { builder.header("Authorization", it) } - builder.header("X-Origin", YOUTUBE_MUSIC_ORIGIN) - builder.header("Origin", YOUTUBE_MUSIC_ORIGIN) + ytAuth.authorizationHeaderValue(origin = origin, account = account)?.let { builder.header("Authorization", it) } + builder.header("X-Origin", origin) + builder.header("Origin", origin) val pageId = account.pageId.takeIf { it.isNotBlank() } if (pageId != null) { builder.header("X-Goog-PageId", pageId) @@ -3003,44 +3054,6 @@ class InnerTubeMusicApi @Inject constructor( internal data class WebConfig(val apiKey: String, val clientVersion: String, val visitorData: String?) - internal data class PlayerClient( - val name: String, - val version: String, - val apiKey: String, - val userAgent: String, - val osName: String? = null, - val osVersion: String? = null, - val deviceMake: String? = null, - val deviceModel: String? = null, - val androidSdkVersion: String? = null, - ) { - val key = "$name@$version" - /** Web clients must present a signatureTimestamp in the player - * request; app/TV clients resolve fine without one. */ - val needsSignatureTimestamp: Boolean - get() = name == "WEB_REMIX" || name == "WEB_EMBEDDED_PLAYER" || name == "MWEB" || name == "TVHTML5_SIMPLY_EMBEDDED_PLAYER" - val needsPoToken: Boolean - get() = name == "WEB_REMIX" || name == "WEB_EMBEDDED_PLAYER" || name == "MWEB" || name == "ANDROID_MUSIC" || name == "ANDROID" - /** TVHTML5 mints readable URLs only when the media URL carries a GVS - * `pot=` token (the player body itself needs none). */ - val needsGvsPoToken: Boolean - get() = needsPoToken || name == "TVHTML5" || name == "TVHTML5_SIMPLY_EMBEDDED_PLAYER" - val origin = if (name == "WEB_REMIX") YOUTUBE_MUSIC_ORIGIN else YOUTUBE_ORIGIN - val referer = when (name) { - "WEB_REMIX" -> "$YOUTUBE_MUSIC_ORIGIN/" - "TVHTML5", "TVHTML5_SIMPLY_EMBEDDED_PLAYER" -> "$YOUTUBE_ORIGIN/tv" - "WEB_EMBEDDED_PLAYER" -> "$YOUTUBE_ORIGIN/embed" - else -> "$YOUTUBE_ORIGIN/" - } - val streamRequestHeaders = buildMap { - put("User-Agent", userAgent) - put("X-YouTube-Client-Name", CLIENT_IDS[name] ?: name) - put("X-YouTube-Client-Version", version) - put("Origin", origin) - put("Referer", referer) - } - } - companion object { /** Continuation pages followed for a full artist release grid. */ const val ARTIST_RELEASE_MAX_PAGES = 10 @@ -3050,23 +3063,6 @@ class InnerTubeMusicApi @Inject constructor( val ARABIC_COUNTRIES = setOf("SA", "EG", "AE", "IQ", "MA", "DZ", "SD", "YE", "SY", "TN", "JO", "LY", "LB", "OM", "KW", "QA", "BH") val ENGLISH_COUNTRIES = setOf("US", "GB", "CA", "AU", "NZ", "IE", "ZA") val JSON_MEDIA_TYPE = "application/json; charset=utf-8".toMediaType() - val CLIENT_IDS = mapOf( - "WEB" to "1", - "WEB_REMIX" to "67", - "IOS" to "5", - "IOS_MUSIC" to "26", - "IOS_CREATOR" to "15", - "ANDROID" to "3", - "ANDROID_MUSIC" to "21", - "ANDROID_VR" to "28", - "ANDROID_TESTSUITE" to "30", - "ANDROID_CREATOR" to "14", - "TVHTML5" to "7", - "TVHTML5_SIMPLY_EMBEDDED_PLAYER" to "85", - "VISIONOS" to "101", - "WEB_EMBEDDED_PLAYER" to "56", - "MWEB" to "62", - ) const val YOUTUBE_MUSIC_ORIGIN = "https://music.youtube.com" const val YOUTUBE_ORIGIN = "https://www.youtube.com" const val MUSIC_API = "https://music.youtube.com/youtubei/v1" @@ -3086,52 +3082,33 @@ class InnerTubeMusicApi @Inject constructor( /** Per-client bound for the direct-URL fast path (single POST, no * extras). Relaxed for slow devices: a fast first success still * wins the race, only the worst case waits longer. */ - const val DIRECT_FAST_CLIENT_TIMEOUT_MS = 4_000L + const val DIRECT_FAST_CLIENT_TIMEOUT_MS = 8_000L /** Bound for the mandatory visitor-data bootstrap on the fast path. * VISIONOS/ANDROID_VR answer LOGIN_REQUIRED with zero formats when * visitor data is missing, so a resolve without it burns the whole * fast-path budget on guaranteed misses. */ - const val VISITOR_BOOTSTRAP_BUDGET_MS = 3_000L + const val VISITOR_BOOTSTRAP_BUDGET_MS = 4_000L /** Cooldown before the fast path retries a failed visitor bootstrap. */ const val VISITOR_BOOTSTRAP_RETRY_COOLDOWN_MS = 60_000L - /** Bound for a warm PoToken mint on the fast path. The engine is - * pre-warmed at startup, so a cache hit lands in milliseconds; - * anything slower proceeds without a token. */ - const val POTOKEN_FAST_BUDGET_MS = 1_000L + const val POTOKEN_FAST_BUDGET_MS = 8_000L /** Whole fast path must settle inside this budget before heavier stages run. */ - const val DIRECT_FAST_PATH_BUDGET_MS = 6_000L + const val DIRECT_FAST_PATH_BUDGET_MS = 16_000L // A signed-in web response may require a cold local JS solver; anonymous clients keep their short budget. const val AUTHENTICATED_CIPHER_PATH_BUDGET_MS = 24_000L const val AUTHENTICATED_CIPHER_CLIENT_BUDGET_MS = 20_000L /** Whole-call cap for one player-API POST (connect + read + body). */ const val PLAYER_REQUEST_CALL_TIMEOUT_MS = 20_000L - /** Max wait on the direct-client/NewPipe race before the last-resort stage. */ - const val CLIENT_RACE_TIMEOUT_MS = 8_000L /** Hard cap for one full stream resolution; callers retry with fresh state. */ const val STREAM_RESOLVE_TOTAL_TIMEOUT_MS = 40_000L /** Bound for the InnerTubeX cipher stage so a hung resolve fails fast. */ - const val INNERTUBEX_STAGE_TIMEOUT_MS = 7_000L + const val INNERTUBEX_STAGE_TIMEOUT_MS = 10_000L /** Signed-in budget: covers the age-gate retry on the account's clients. */ const val SIGNED_IN_INNERTUBEX_STAGE_TIMEOUT_MS = 16_000L - /** Bound for the last-resort NewPipe stage. */ - const val NEWPIPE_FALLBACK_TIMEOUT_MS = 9_000L /** Overall budget for promoting a staged YouTube stream from MusicPlayer. */ const val YOUTUBE_PROMOTE_BUDGET_MS = 12_000L - /** No-cipher clients tried first, in order (mirrors limusic's fallback order). */ - /** - * Audio clients for the direct fast path. IOS is deliberately absent: - * its googlevideo URLs require an iOS-attested GVS PO token (see - * InnerTubeX PlaybackClientCatalog: gvs = iosGvsRequired) which this - * app cannot mint, so YouTube serves ~60s of audio and then answers - * 403 — the "song stops at 1:00" bug. ANDROID_VR / VISIONOS need no - * PO token and play the whole file when fetched in bounded <=512 KB - * ranges (ChunkedRangeDataSource). IOS stays in VIDEO_CLIENT_ORDER, - * where clips are short and muted. - */ - val DIRECT_FAST_CLIENT_ORDER = listOf("TVHTML5", "VISIONOS", "ANDROID_TESTSUITE", "ANDROID_VR", "WEB_REMIX") const val VIDEO_LOG_TAG = "InnerTubeVideo" /** Clients that return video formats without a signed-in session. */ - val VIDEO_CLIENT_ORDER = listOf("ANDROID_VR", "VISIONOS", "IOS", "TVHTML5") + val VIDEO_CLIENT_ORDER = listOf("VISIONOS", "ANDROID_VR", "IOS", "TVHTML5") val ALIGNMENT_AUDIO_CLIENT_ORDER = listOf("VISIONOS", "ANDROID_VR") const val VIDEO_CLIENT_TIMEOUT_MS = 6_000L const val VIDEO_CIPHER_CONTEXT_TTL_MS = 30 * 60 * 1000L @@ -3153,8 +3130,6 @@ class InnerTubeMusicApi @Inject constructor( const val URL_EXPIRY_MARGIN_MS = 2 * 60 * 1000L const val REQUEST_RETRY_BASE_DELAY_MS = 250L const val REQUEST_RETRY_JITTER_MS = 180L - const val NEWPIPE_RETRY_BASE_DELAY_MS = 300L - const val NEWPIPE_RETRY_JITTER_MS = 220L const val UNKNOWN_STREAM_EXPIRY_TTL_MS = 5 * 60 * 1000L val CONFIRMED_UNAVAILABLE_REASONS = listOf( @@ -3177,7 +3152,6 @@ class InnerTubeMusicApi @Inject constructor( const val STREAM_TTL_MS = 4 * 60 * 60 * 1000L const val MAX_MATCH_CACHE_ENTRIES = 1024 const val FALLBACK_TOKEN_SESSION = "lastwave_session" - const val NEWPIPE_SOURCE = "NEWPIPE" const val ANONYMOUS_AUTH_SCOPE = "anonymous" const val STREAM_LOG_TAG = "LastWaveStream" const val PLAYLIST_LOG_TAG = "LastWavePlaylist" @@ -3190,122 +3164,6 @@ class InnerTubeMusicApi @Inject constructor( const val PODCASTS_BROWSE_ID = "FEmusic_podcasts" const val PODCAST_EPISODES_SEARCH_FILTER = "EgWKAQJIAWoSEBEQAxAQEAUQChAOEAkQBBAV" val CODEC_PATTERN = Regex("""codecs?=[\"']([^\"']+)[\"']""", RegexOption.IGNORE_CASE) - internal val PLAYER_CLIENTS = listOf( - PlayerClient( - name = "ANDROID_VR", - version = "1.60.19", - apiKey = "AIzaSyD-p045F_WzU-vA_YgX20SCx4KAo", - userAgent = "com.google.android.apps.youtube.vr.oculus/1.60.19 (Linux; U; Android 12; en_US; Quest 3; Build/SQ3A.220605.009.A1) gzip", - osName = "Android", - osVersion = "12", - deviceMake = "Oculus", - deviceModel = "Quest 3", - androidSdkVersion = "32", - ), - PlayerClient( - name = "VISIONOS", - version = "0.1", - apiKey = "AIzaSyB-63vPrdThhKuerbB2N_l7Kwwcxj6yUAc", - userAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Safari/605.1.15", - osName = "visionOS", - osVersion = "1.3.21O771", - deviceMake = "Apple", - deviceModel = "RealityDevice14,1", - ), - PlayerClient( - name = "TVHTML5", - version = "7.20260308.08.00", - apiKey = "AIzaSyAO_FJ2SlqAz8GlBg1fA54p0wDE7Xk80mU", - userAgent = "Mozilla/5.0 (SMART-TV; Linux; Tizen 6.0) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/4.0 Chrome/76.0.3809.146 TV Safari/537.36", - ), - PlayerClient( - name = "TVHTML5_SIMPLY_EMBEDDED_PLAYER", - version = "2.0", - apiKey = "AIzaSyAO_FJ2SlqAz8GlBg1fA54p0wDE7Xk80mU", - userAgent = "Mozilla/5.0 (SMART-TV; Linux; Tizen 6.0) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/4.0 Chrome/76.0.3809.146 TV Safari/537.36", - ), - PlayerClient( - name = "ANDROID_TESTSUITE", - version = "1.9", - apiKey = "AIzaSyD-p045F_WzU-vA_YgX20SCx4KAo", - userAgent = "com.google.android.youtube/1.9 (Linux; U; Android 12) gzip", - osName = "Android", - osVersion = "12", - ), - PlayerClient( - name = "IOS_MUSIC", - version = "7.27.0", - apiKey = "AIzaSyB-63vPrdThhKuerbB2N_l7Kwwcxj6yUAc", - userAgent = "com.google.ios.youtubemusic/7.27.0 (iPhone16,2; U; CPU iOS 17_5_1 like Mac OS X;)", - osName = "iOS", - osVersion = "17.5.1.21F90", - deviceMake = "Apple", - deviceModel = "iPhone16,2", - ), - PlayerClient( - name = "ANDROID_MUSIC", - version = "7.27.52", - apiKey = "AIzaSyA8eiZmM1FaDVjRy-df2KTyQ_vz_yYM39w", - userAgent = "com.google.android.apps.youtube.music/7.27.52 (Linux; U; Android 14; en_US; Pixel 8; Build/UD1A.230803.041) gzip", - osName = "Android", - osVersion = "14", - deviceMake = "Google", - deviceModel = "Pixel 8", - androidSdkVersion = "34", - ), - PlayerClient( - name = "IOS", - version = "20.03.02", - apiKey = "AIzaSyB-63vPrdThhKuerbB2N_l7Kwwcxj6yUAc", - userAgent = "com.google.ios.youtube/20.03.02 (iPhone16,2; U; CPU iOS 18_2 like Mac OS X;)", - osName = "iPhone", - osVersion = "18.2", - deviceMake = "Apple", - deviceModel = "iPhone16,2", - ), - PlayerClient( - name = "ANDROID", - version = "21.26.364", - apiKey = "AIzaSyA8eiZmM1FaDVjRy-df2KTyQ_vz_yYM39w", - userAgent = "com.google.android.youtube/21.26.364 (Linux; U; Android 11) gzip", - osName = "Android", - osVersion = "11", - ), - PlayerClient( - name = "ANDROID_CREATOR", - version = "24.32.100", - apiKey = "AIzaSyA8eiZmM1FaDVjRy-df2KTyQ_vz_yYM39w", - userAgent = "com.google.android.apps.youtube.creator/24.32.100 (Linux; U; Android 13; en_US) gzip", - osName = "Android", - osVersion = "13", - ), - PlayerClient( - name = "IOS_CREATOR", - version = "24.32.100", - apiKey = "AIzaSyB-63vPrdThhKuerbB2N_l7Kwwcxj6yUAc", - userAgent = "com.google.ios.creator/24.32.100 (iPhone16,2; U; CPU iOS 17_5_1 like Mac OS X;)", - osName = "iOS", - osVersion = "17.5.1.21F90", - ), - PlayerClient( - name = "WEB_REMIX", - version = FALLBACK_WEB_VERSION, - apiKey = "AIzaSyC9XL3ZjWddXya6X74dJoCTL-WEYFDNX30", - userAgent = WEB_USER_AGENT, - ), - PlayerClient( - name = "WEB_EMBEDDED_PLAYER", - version = FALLBACK_WEB_VERSION, - apiKey = "AIzaSyC9XL3ZjWddXya6X74dJoCTL-WEYFDNX30", - userAgent = WEB_USER_AGENT, - ), - PlayerClient( - name = "MWEB", - version = "2.20260707.01.00", - apiKey = "AIzaSyC9XL3ZjWddXya6X74dJoCTL-WEYFDNX30", - userAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 17_5_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1", - ), - ) } } diff --git a/app/src/main/java/com/lastwave/app/data/music/InnerTubeMusicApiStreamResolver.kt b/app/src/main/java/com/lastwave/app/data/music/InnerTubeMusicApiStreamResolver.kt index 42885bd92c..47063b0f01 100644 --- a/app/src/main/java/com/lastwave/app/data/music/InnerTubeMusicApiStreamResolver.kt +++ b/app/src/main/java/com/lastwave/app/data/music/InnerTubeMusicApiStreamResolver.kt @@ -149,24 +149,15 @@ internal suspend fun InnerTubeMusicApi.resolveAudioStreamImpl( } /** - * Download-only NewPipe extraction preferring the Opus (WebM) rendition, which - * the download pipeline remuxes losslessly into a fully tagged .opus file. - * Falls back to [resolveAudioStream] if NewPipe fails (e.g. age-restricted content). + * Resolves an audio stream for download, preferring VISIONOS + Opus (WebM) + * directly through InnerTube without NewPipe. */ -internal suspend fun InnerTubeMusicApi.resolveDownloadStreamImpl(videoId: String): YouTubeAudioStream = withContext(Dispatchers.IO) { - require(videoId.isNotBlank()) { "Missing YouTube Music video id" } - try { - streamExtractor.resolveAudioStream(videoId, preferOpus = true) - } catch (error: Exception) { - if (error is kotlinx.coroutines.CancellationException) throw error - resolveAudioStream(videoId) - } - } +internal suspend fun InnerTubeMusicApi.resolveDownloadStreamImpl(videoId: String): YouTubeAudioStream = + resolveAudioStream(videoId) /** * Resolves video through the same InnerTube clients and PoToken session as - * audio. Returns null when no client yields a URL that passes a probe, so - * the caller can fall back to NewPipe. + * audio. Returns null when no client yields a URL that passes a probe. * * The signed-in WEB_REMIX session goes last because its cipher decode is * slower, but it is the only client that passes YouTube's LOGIN_REQUIRED @@ -286,22 +277,24 @@ internal suspend fun InnerTubeMusicApi.resolveVideoBundleFromClient( poToken: PoTokenResult?, allowCipherReuse: Boolean = true, ): SyncedVideoStreamBundle? { - val signedIn = client.name == "WEB_REMIX" + val signedIn = client.loginSupported && ytAuth.connection.value.isConnected val contextBefore = cachedVideoCipherContext // Signed-in ciphers only decode with the player script paired to this request. - val cipherContext = if (signedIn) { + val cipherContext = if (signedIn && client.requiresCipher) { videoCipherContext(videoId, allowCipherReuse) ?: run { android.util.Log.w(VIDEO_LOG_TAG, "Video client ${client.name} has no cipher context for $videoId") return null } } else null val root = post( - url = "${if (signedIn) MUSIC_API else YOUTUBE_API}/player?key=${client.apiKey}&prettyPrint=false", + url = "${client.playerApiBase}/player?key=${client.apiKey}&prettyPrint=false", body = playbackPlayerBody( - videoId, - playerRequestContext(client, visitorData), - cipherContext?.signatureTimestamp, - poToken?.playerToken.takeIf { client.needsPoToken }, + videoId = videoId, + context = playerRequestContext(client, visitorData), + signatureTimestamp = cipherContext?.signatureTimestamp, + playerPoToken = poToken?.playerToken.takeIf { client.needsPoToken }, + useMusicPlayerEndpoint = client.useMusicPlayerEndpoint, + isEmbedded = client.isEmbedded, ), clientName = client.name, clientVersion = client.version, @@ -317,14 +310,7 @@ internal suspend fun InnerTubeMusicApi.resolveVideoBundleFromClient( android.util.Log.w(VIDEO_LOG_TAG, "Video client ${client.name} returned no streams: ${youtubePlayerResponseSummary(root)}") return null } - val headers = buildMap { - putAll(client.streamRequestHeaders) - if (!visitorData.isNullOrBlank()) put("X-Goog-Visitor-Id", visitorData) - if (signedIn) { - ytAuth.cookieHeaderValue()?.let { put("Cookie", it) } - ytAuth.authorizationHeaderValue()?.let { put("Authorization", it) } - } - } + val headers = mediaStreamHeaders(client, signedIn) val responseExpiry = streaming.string("expiresInSeconds")?.toLongOrNull() ?.let { System.currentTimeMillis() + it.coerceAtLeast(1L) * 1_000L } val token = poToken?.sessionToken.takeIf { client.needsGvsPoToken } @@ -371,10 +357,11 @@ internal suspend fun InnerTubeMusicApi.resolveVideoBundleFromClient( .partition { it.startsWith("https://") } val decoded: Map = if (cipherContext != null) { innerTubeXExtractor.decipherAudioUrls(videoId, cipherSources, cipherContext, directSources) + } else if (cipherSources.isNotEmpty()) { + directSources.associateWith { it } + + innerTubeXExtractor.decipherAudioUrls(videoId, cipherSources) } else { - directSources.associateWith { it } + cipherSources.mapNotNull { cipher -> - streamExtractor.decipherStreamUrl(videoId, cipher)?.let { cipher to it } - } + directSources.associateWith { it } } val available = preferred.mapNotNull { stream -> val url = appendPoToken(decoded[stream.url] ?: return@mapNotNull null, token) @@ -387,7 +374,7 @@ internal suspend fun InnerTubeMusicApi.resolveVideoBundleFromClient( val playable = selectProbedCandidate( candidates = rankedForAutoPlayback(available), urlOf = { it.url }, - probe = streamExtractor::probePlayableVideo, + probe = { stream -> probeVideoStream(stream) }, limit = MAX_VIDEO_PROBES_PER_CLIENT, ) if (playable == null) { @@ -423,23 +410,17 @@ internal fun JsonObject.byteRange(): String? { } /** - * One youtubei/player POST. The client that served the previous song goes - * first; the next client runs only if this one returns no direct URL. - * Parallel hedges used to open VISIONOS, ANDROID_VR, and TVHTML5 together - * and cancel the losers after the winner, which showed up as several - * player requests and a cancellation immediately after a ~2s extract. + * One youtubei/player POST per client in priority order (VISIONOS first, + * then previous non-cipher winner, then ANDROID_VR / ANDROID_TESTSUITE / + * TVHTML5, then cipher clients like WEB_REMIX as fallback). Mirrors + * LastWave-Desktop's ordered_fast_clients(): PoToken / cipher setup is + * deferred until a client that actually needs it is reached. */ internal suspend fun InnerTubeMusicApi.resolveDirectUrlFastPath( videoId: String, authScope: String, maxBitrateBps: Int?, ): YouTubeAudioStream? { - // Visitor data is mandatory, not best-effort: VISIONOS/ANDROID_VR - // answer LOGIN_REQUIRED with zero formats when it is missing, so a - // resolve without it burns the fast-path budget on misses. Bootstrap - // it here (bounded, throttled) when the startup pre-warm hasn't — - // including when the cached value is only the synthetic placeholder, - // so a transient scrape miss self-heals instead of sticking. var visitorData = webConfig?.visitorData?.takeIf { isValidVisitorData(it) } if (visitorData.isNullOrBlank()) { val now = System.currentTimeMillis() @@ -449,54 +430,64 @@ internal suspend fun InnerTubeMusicApi.resolveDirectUrlFastPath( kotlinx.coroutines.withTimeoutOrNull(VISITOR_BOOTSTRAP_BUDGET_MS) { getWebConfig() }?.visitorData - }.getOrNull()?.takeIf { isValidVisitorData(it) } ?: visitorData + }.getOrNull()?.takeIf { isValidVisitorData(it) } + ?: runCatching { + kotlinx.coroutines.withTimeoutOrNull(VISITOR_BOOTSTRAP_BUDGET_MS) { + fetchFreshVisitorData() + } + }.getOrNull()?.takeIf { isValidVisitorData(it) } + ?: visitorData + if (isValidVisitorData(visitorData)) { + val currentCfg = webConfig + webConfig = WebConfig( + apiKey = currentCfg?.apiKey ?: FALLBACK_WEB_KEY, + clientVersion = currentCfg?.clientVersion ?: FALLBACK_WEB_VERSION, + visitorData = visitorData, + ) + } } noteAttempt("direct-fast=visitor-${if (!visitorData.isNullOrBlank()) "ok" else "missing"}") } - // One PoToken per resolve, shared across clients: the minter serves - // cache hits in milliseconds (engine is pre-warmed at startup) and - // anything slower proceeds without a token instead of stalling audio. - val poToken = fastPoToken(videoId, visitorData) + val signedIn = ytAuth.connection.value.isConnected val nowMs = System.currentTimeMillis() val config = webConfig val ordered = DIRECT_FAST_CLIENT_ORDER - .mapNotNull { name -> - val client = PLAYER_CLIENTS.firstOrNull { it.name == name } ?: return@mapNotNull null + .mapNotNull { id -> + val client = PLAYER_CLIENTS.firstOrNull { it.id == id || it.name == id } ?: return@mapNotNull null if (client.name == "WEB_REMIX" && config != null) { client.copy(version = config.clientVersion, apiKey = config.apiKey) } else { client } } - .filter { nowMs >= (failedClientsUntil[clientFailureKey(videoId, it.key, authScope)] ?: 0L) } - .sortedBy { playbackClientPriority(it.name, ytAuth.connection.value.isConnected, lastSuccessfulClientName) } + .filter { (!it.loginRequired || signedIn) && nowMs >= (failedClientsUntil[clientFailureKey(videoId, it.key, authScope)] ?: 0L) } + .sortedBy { playbackClientPriority(it.id, signedIn, lastSuccessfulClientName) } if (ordered.isEmpty()) { noteAttempt("direct-fast=no-clients") return null } - val signedIn = ytAuth.connection.value.isConnected - val deadline = SystemClock.elapsedRealtime() + - if (signedIn) AUTHENTICATED_CIPHER_PATH_BUDGET_MS else DIRECT_FAST_PATH_BUDGET_MS + var poToken: PoTokenResult? = null + var poTokenAttempted = false + val deadline = SystemClock.elapsedRealtime() + AUTHENTICATED_CIPHER_PATH_BUDGET_MS for (client in ordered) { val remaining = deadline - SystemClock.elapsedRealtime() if (remaining <= 0L) { noteAttempt("direct-fast=budget-exhausted") return null } + if ((client.needsPoToken || client.needsGvsPoToken) && !poTokenAttempted) { + poTokenAttempted = true + poToken = fastPoToken(videoId, visitorData) + } var failed = false - val usesCipherContext = signedIn && client.name == "WEB_REMIX" - // The player script and its signature timestamp are not per-video: - // reuse a recent pair instead of a ~1 s watch-page fetch per track. - // A reused pair that fails gets one retry with a fresh fetch. + val usesCipherContext = client.requiresCipher suspend fun attempt(allowCipherReuse: Boolean, budgetMs: Long): YouTubeAudioStream? = kotlinx.coroutines.withTimeoutOrNull(budgetMs) { - val cipherContext = if (usesCipherContext) { + val cipherContext = if (usesCipherContext || client.needsSignatureTimestamp) { videoCipherContext(videoId, allowReuse = allowCipherReuse) } else null - val sigTimestamp = cipherContext?.signatureTimestamp ?: if (client.needsSignatureTimestamp) { - streamExtractor.getSignatureTimestamp(videoId) - } else null + val sigTimestamp = cipherContext?.signatureTimestamp if (cipherContext != null) { noteAttempt("client=${client.name} cipherContext=paired") } @@ -510,7 +501,11 @@ internal suspend fun InnerTubeMusicApi.resolveDirectUrlFastPath( gvsPoToken = if (client.needsGvsPoToken) poToken?.sessionToken else null, authScope = authScope, probeCandidates = true, - allowCipherFormats = client.name == "TVHTML5_SIMPLY_EMBEDDED_PLAYER" || client.name == "WEB_REMIX" || client.name == "IOS" || client.name == "TVHTML5", + allowCipherFormats = client.requiresCipher || + client.name == "ANDROID" || + client.name == "ANDROID_MUSIC" || + client.name == "TVHTML5_SIMPLY_EMBEDDED_PLAYER" || + client.name == "TVHTML5", maxAttempts = 1, maxBitrateBps = maxBitrateBps, ) @@ -523,29 +518,31 @@ internal suspend fun InnerTubeMusicApi.resolveDirectUrlFastPath( try { attempt(allowCipherReuse = true, budgetMs = minOf(clientBudget, remaining)) } catch (error: Exception) { - if (error is kotlinx.coroutines.CancellationException || !reusedContext) throw error - noteAttempt("client=${client.name} reused-cipher failed ${resolutionFailureDetail(error)}") + if (error is kotlinx.coroutines.CancellationException || error is ConfirmedUnplayableMediaException || !reusedContext) throw error + noteAttempt("client=${client.id} reused-cipher failed ${resolutionFailureDetail(error)}") null } ?: if (reusedContext) { - // A rotated player script makes the reused pair produce - // rejected URLs. Drop it and fetch a fresh one once. cachedVideoCipherContext = null val left = deadline - SystemClock.elapsedRealtime() if (left > 0L) attempt(allowCipherReuse = false, budgetMs = minOf(clientBudget, left)) else null } else null } catch (cancellation: kotlinx.coroutines.CancellationException) { throw cancellation + } catch (unplayable: ConfirmedUnplayableMediaException) { + failed = true + noteAttempt("client=${client.id} outcome=unplayable ${resolutionFailureDetail(unplayable)}") + throw unplayable } catch (error: Exception) { failed = true - noteAttempt("client=${client.name} outcome=error ${resolutionFailureDetail(error)}") + noteAttempt("client=${client.id} outcome=error ${resolutionFailureDetail(error)}") null } if (stream != null) { - noteAttempt("client=${client.name} outcome=direct-url itag=${stream.itag ?: -1}") - lastSuccessfulClientName = client.name + noteAttempt("client=${client.id} outcome=direct-url itag=${stream.itag ?: -1}") + lastSuccessfulClientName = client.id return stream } - if (!failed) noteAttempt("client=${client.name} outcome=timeout") + if (!failed) noteAttempt("client=${client.id} outcome=timeout") } noteAttempt("direct-fast=exhausted") return null @@ -560,13 +557,22 @@ internal suspend fun InnerTubeMusicApi.resolveAudioStreamInternal( kotlinx.coroutines.coroutineScope { val now = System.currentTimeMillis() - // Use whichever validated source finishes first. In particular, a usable - // NewPipe URL must not wait for every authenticated client to miss. + // Try direct InnerTube clients first (VISIONOS -> VISIONOS_1_02 -> WEB_REMIX -> ...); + // fall back to InnerTubeX, and if the track is unavailable, check Metrolist's + // navigation/resolve_url for re-released catalog replacements. val resolved = try { - racePlaybackCandidates( - first = { resolveDirectUrlFastPath(videoId, authScope, maxBitrateBps) }, - second = { racePlayableFallback(videoId, authScope, now, startedAt, maxBitrateBps) }, - ) + resolveDirectUrlFastPath(videoId, authScope, maxBitrateBps) + ?: resolveInnerTubeXFallback(videoId, authScope, now, startedAt, maxBitrateBps) + ?: resolveReReleasedCatalogTrack(videoId, authScope, now, startedAt, maxBitrateBps) + } catch (unplayable: ConfirmedUnplayableMediaException) { + val replacement = resolveReReleasedCatalogTrack(videoId, authScope, now, startedAt, maxBitrateBps) + if (replacement != null) { + replacement + } else { + noteAttempt("fallback=unplayable ${resolutionFailureDetail(unplayable)}") + logResolveAttempts(videoId, failed = true) + throw unplayable + } } catch (error: Throwable) { if (error.isCooperativeCancellation()) throw error noteAttempt("fallback=failed ${resolutionFailureDetail(error)}") @@ -591,106 +597,120 @@ internal suspend fun InnerTubeMusicApi.resolveAudioStreamInternal( } } -internal suspend fun InnerTubeMusicApi.racePlayableFallback( +/** + * Mirrors Metrolist InnerTube.resolveCatalogTrackId (innertubex 0.11.9): + * when YouTube marks a catalogue video ID unavailable across every client, + * YouTube Music's navigation/resolve_url often returns the replacement watchId. + */ +private suspend fun InnerTubeMusicApi.resolveReReleasedCatalogTrack( + videoId: String, + authScope: String, + now: Long, + startedAt: Long, + maxBitrateBps: Int?, +): YouTubeAudioStream? { + val replacementId = resolveCanonicalCatalogVideoId(videoId) ?: return null + noteAttempt("resolve_url=$replacementId") + return resolveDirectUrlFastPath(replacementId, authScope, maxBitrateBps) + ?: resolveInnerTubeXFallback(replacementId, authScope, now, startedAt, maxBitrateBps) +} + +private suspend fun InnerTubeMusicApi.resolveCanonicalCatalogVideoId(videoId: String): String? { + val config = runCatching { getWebConfig() }.getOrNull() ?: return null + val remix = PLAYER_CLIENTS.firstOrNull { it.name == "WEB_REMIX" }?.copy( + version = config.clientVersion, + apiKey = config.apiKey, + ) ?: return null + val body = buildJsonObject { + put("context", playerRequestContext(remix.copy(loginSupported = false), config.visitorData)) + put("url", "$YOUTUBE_MUSIC_ORIGIN/watch?v=$videoId") + } + return try { + val root = post( + url = "$MUSIC_API/navigation/resolve_url?key=${remix.apiKey}&prettyPrint=false", + body = body, + clientName = remix.name, + clientVersion = remix.version, + userAgent = remix.userAgent, + authenticated = false, + origin = YOUTUBE_MUSIC_ORIGIN, + referer = "$YOUTUBE_MUSIC_ORIGIN/", + visitorData = config.visitorData, + maxAttempts = 1, + callTimeoutMs = CONFIG_REQUEST_TIMEOUT_MS, + ) + root.obj("endpoint") + ?.obj("watchEndpoint") + ?.string("videoId") + ?.takeIf { it != videoId && VIDEO_ID_PATTERN.matches(it) } + } catch (cancellation: kotlinx.coroutines.CancellationException) { + throw cancellation + } catch (_: Exception) { + null + } +} + +internal suspend fun InnerTubeMusicApi.resolveInnerTubeXFallback( videoId: String, authScope: String, now: Long, startedAt: Long, maxBitrateBps: Int?, - ): YouTubeAudioStream? = kotlinx.coroutines.coroutineScope { - // Signed in, InnerTubeX is the only path to age-restricted songs: it - // detects the age gate, fetches the signed-in watch config and retries on - // WEB_REMIX/TVHTML5 with the account's cookies, deciphering their formats - // — more round trips than 7s allows. The race returns on the first - // success, so ordinary songs are no slower. + ): YouTubeAudioStream? { val innerTubeXBudgetMs = if (ytAuth.connection.value.isConnected) { SIGNED_IN_INNERTUBEX_STAGE_TIMEOUT_MS } else { INNERTUBEX_STAGE_TIMEOUT_MS } - val channel = kotlinx.coroutines.channels.Channel(2) - val jobs = listOf( - launch(Dispatchers.IO) { - var failed = false - val candidate = try { - kotlinx.coroutines.withTimeoutOrNull(innerTubeXBudgetMs) { - val visitorData = try { - getWebConfig().visitorData - } catch (cancellation: kotlinx.coroutines.CancellationException) { - throw cancellation - } catch (_: Exception) { - null - } - innerTubeXExtractor.resolve(videoId, visitorData, authScope, maxBitrateBps) - } + var failed = false + val candidate = try { + kotlinx.coroutines.withTimeoutOrNull(innerTubeXBudgetMs) { + val visitorData = try { + getWebConfig().visitorData } catch (cancellation: kotlinx.coroutines.CancellationException) { throw cancellation - } catch (failure: Throwable) { - failed = true - logClientFailure(videoId, "INNERTUBEX", failure) - noteAttempt("client=INNERTUBEX outcome=error ${resolutionFailureDetail(failure)}") + } catch (_: Exception) { null } - if (candidate == null) { - if (!failed) noteAttempt("client=INNERTUBEX outcome=empty") - return@launch - } - val compatible = candidate.isAdaptive || isCompatibleAudioCandidate(candidate) - if (!compatible) { - noteAttempt("client=INNERTUBEX outcome=incompatible itag=${candidate.itag ?: -1}") - logStreamEvent("innertubex-rejected", candidate, detail = "compatible=false") - innerTubeXExtractor.reportPlaybackFailure( - videoId = videoId, - authScope = authScope, - clientProfile = candidate.clientProfile, - ) - return@launch - } - if (probeStream(candidate, "innertubex-probe")) channel.trySend(candidate) - }, - launch(Dispatchers.IO) { - var failed = false - val stream = try { - kotlinx.coroutines.withTimeoutOrNull(NEWPIPE_FALLBACK_TIMEOUT_MS) { - streamExtractor.resolveAudioStream(videoId, maxBitrateBps = maxBitrateBps) - } - } catch (cancellation: kotlinx.coroutines.CancellationException) { - throw cancellation - } catch (failure: Throwable) { - failed = true - logClientFailure(videoId, "NEWPIPE", failure) - noteAttempt("client=NEWPIPE outcome=error ${resolutionFailureDetail(failure)}") - null - } - // resolveAudioStream already rejected URLs that answer 403. - if (stream != null) { - noteAttempt("client=NEWPIPE outcome=accepted itag=${stream.itag ?: -1} mime=${stream.mimeType.orEmpty()}") - channel.trySend(stream) - } else if (!failed) { - noteAttempt("client=NEWPIPE outcome=empty") - } - }, - ) - val remaining = AtomicInteger(jobs.size) - jobs.forEach { job -> - job.invokeOnCompletion { - if (remaining.decrementAndGet() == 0) channel.close() + innerTubeXExtractor.resolve(videoId, visitorData, authScope, maxBitrateBps) } + } catch (cancellation: kotlinx.coroutines.CancellationException) { + throw cancellation + } catch (failure: Throwable) { + failed = true + logClientFailure(videoId, "INNERTUBEX", failure) + noteAttempt("client=INNERTUBEX outcome=error ${resolutionFailureDetail(failure)}") + null } - try { - val winner = kotlinx.coroutines.withTimeoutOrNull(maxOf(NEWPIPE_FALLBACK_TIMEOUT_MS, innerTubeXBudgetMs)) { - channel.receiveCatching().getOrNull() - } ?: return@coroutineScope null - cacheResolvedStream(winner, now, authScope, maxBitrateBps) - lastResolvedStreams[resolutionKey(videoId, authScope, maxBitrateBps)] = winner - val stage = if (winner.clientProfile == NEWPIPE_SOURCE) "newpipe" else "innertubex" - logStreamEvent("resolved", winner) - logStage(videoId, stage, startedAt) - winner - } finally { - channel.close() - jobs.forEach { it.cancel() } + if (candidate == null) { + if (!failed) noteAttempt("client=INNERTUBEX outcome=empty") + return null + } + val compatible = isCompatibleAudioCandidate(candidate) || + candidate.codec?.equals("hls", ignoreCase = true) == true + if (!compatible) { + noteAttempt("client=INNERTUBEX outcome=incompatible itag=${candidate.itag ?: -1}") + logStreamEvent("innertubex-rejected", candidate, detail = "compatible=false") + innerTubeXExtractor.reportPlaybackFailure( + videoId = videoId, + authScope = authScope, + clientProfile = candidate.clientProfile, + ) + return null + } + if (!probeStream(candidate, "innertubex-probe")) { + innerTubeXExtractor.reportPlaybackFailure( + videoId = videoId, + authScope = authScope, + clientProfile = candidate.clientProfile, + ) + return null } + cacheResolvedStream(candidate, now, authScope, maxBitrateBps) + lastResolvedStreams[resolutionKey(videoId, authScope, maxBitrateBps)] = candidate + logStreamEvent("resolved", candidate) + logStage(videoId, "innertubex", startedAt) + return candidate } /** @@ -718,29 +738,55 @@ internal suspend fun InnerTubeMusicApi.fastPoToken(videoId: String, visitorData: } } -internal fun InnerTubeMusicApi.playerRequestContext(client: PlayerClient, visitorData: String?): JsonObject = buildJsonObject { - put("client", buildJsonObject { - put("clientName", client.name) - put("clientVersion", client.version) - put("hl", "en") - put("gl", "US") - if (isValidVisitorData(visitorData)) put("visitorData", visitorData) - if (!client.osName.isNullOrBlank()) put("osName", client.osName) - if (!client.osVersion.isNullOrBlank()) put("osVersion", client.osVersion) - if (!client.deviceMake.isNullOrBlank()) put("deviceMake", client.deviceMake) - if (!client.deviceModel.isNullOrBlank()) put("deviceModel", client.deviceModel) - if (!client.androidSdkVersion.isNullOrBlank()) { - put("androidSdkVersion", client.androidSdkVersion) - } - }) - if (client.name == "WEB_REMIX" && ytAuth.connection.value.isConnected) { - put("user", buildJsonObject { - put("lockedSafetyMode", false) - val delegate = ytAuth.connection.value.onBehalfOfUser - if (!delegate.isNullOrBlank()) { - put("onBehalfOfUser", delegate) +internal fun InnerTubeMusicApi.playerRequestContext(client: PlayerClient, visitorData: String?): JsonObject { + val (hl, gl) = getEffectiveHlGl() + return buildJsonObject { + put("client", buildJsonObject { + put("clientName", client.name) + put("clientVersion", client.version) + if (client.includeUserAgentInContext) put("userAgent", client.userAgent) + if (hl.isNotBlank()) put("hl", hl) + if (gl.isNotBlank()) put("gl", gl) + if (isValidVisitorData(visitorData)) put("visitorData", visitorData) + if (!client.osName.isNullOrBlank()) put("osName", client.osName) + if (!client.osVersion.isNullOrBlank()) put("osVersion", client.osVersion) + if (!client.deviceMake.isNullOrBlank()) put("deviceMake", client.deviceMake) + if (!client.deviceModel.isNullOrBlank()) put("deviceModel", client.deviceModel) + if (!client.androidSdkVersion.isNullOrBlank()) { + put("androidSdkVersion", client.androidSdkVersion) } + if (!client.platform.isNullOrBlank()) put("platform", client.platform) }) + if (client.loginSupported && ytAuth.connection.value.isConnected) { + put("user", buildJsonObject { + put("lockedSafetyMode", false) + val delegate = ytAuth.connection.value.onBehalfOfUser + if (!delegate.isNullOrBlank()) { + put("onBehalfOfUser", delegate) + } + }) + } + } + } + +/** + * Mirrors Metrolist InnerTubeExtractor.buildHeaders(): VISIONOS, ANDROID_VR, + * and TVHTML5_SIMPLY omit CDN headers; web clients send Origin/Referer (+ Cookie + * when signed in); mobile/progressive clients keep User-Agent and Accept. + */ +internal fun InnerTubeMusicApi.mediaStreamHeaders(client: PlayerClient, signedIn: Boolean): Map = + if (client.stripsMediaHeaders) { + emptyMap() + } else { + val (hl, gl) = getEffectiveHlGl() + buildMap { + putAll(client.streamRequestHeaders) + put("User-Agent", client.userAgent) + put("Accept", "*/*") + put("Accept-Language", "$hl-$gl,$hl;q=0.9,en;q=0.8") + if (signedIn && client.loginSupported) { + ytAuth.cookieHeaderValue()?.takeIf { it.isNotBlank() }?.let { put("Cookie", it) } + } } } @@ -758,17 +804,24 @@ internal suspend fun InnerTubeMusicApi.resolveDirectClientStream( maxAttempts: Int = MAX_PLAYER_REQUEST_ATTEMPTS, maxBitrateBps: Int? = null, ): YouTubeAudioStream { + val signedIn = client.loginSupported && ytAuth.connection.value.isConnected val playerContext = playerRequestContext(client, visitorData) cipherContext?.requireMatches(videoId, ytAuth.connection.value) - val body = playbackPlayerBody(videoId, playerContext, signatureTimestamp, playerPoToken) - val playerApi = if (client.name == "WEB_REMIX") MUSIC_API else YOUTUBE_API + val body = playbackPlayerBody( + videoId = videoId, + context = playerContext, + signatureTimestamp = signatureTimestamp, + playerPoToken = playerPoToken, + useMusicPlayerEndpoint = client.useMusicPlayerEndpoint, + isEmbedded = client.isEmbedded, + ) val root = post( - url = "$playerApi/player?key=${client.apiKey}&prettyPrint=false", + url = "${client.playerApiBase}/player?key=${client.apiKey}&prettyPrint=false", body = body, clientName = client.name, clientVersion = client.version, userAgent = client.userAgent, - authenticated = client.name == "WEB_REMIX" && ytAuth.connection.value.isConnected, + authenticated = signedIn, origin = client.origin, referer = client.referer, visitorData = visitorData, @@ -778,8 +831,8 @@ internal suspend fun InnerTubeMusicApi.resolveDirectClientStream( // racer for 30s+ across its two attempts. callTimeoutMs = PLAYER_REQUEST_CALL_TIMEOUT_MS, ) - noteAttempt("client=${client.name} response ${youtubePlayerResponseSummary(root)} " + - "signedIn=${client.name == "WEB_REMIX" && ytAuth.connection.value.isConnected} " + + noteAttempt("client=${client.id} response ${youtubePlayerResponseSummary(root)} " + + "signedIn=$signedIn " + "visitorPresent=${!visitorData.isNullOrBlank()} " + "playerTokenPresent=${!playerPoToken.isNullOrBlank()} " + "signatureTimestampPresent=${signatureTimestamp != null}") @@ -800,22 +853,11 @@ internal suspend fun InnerTubeMusicApi.resolveDirectClientStream( } val streaming = root.obj("streamingData") - val streamRequestHeaders = buildMap { - putAll(client.streamRequestHeaders) - if (!client.userAgent.isNullOrBlank()) { - put("User-Agent", client.userAgent) - } - put("Origin", "https://music.youtube.com") - put("Referer", "https://music.youtube.com/") - if (!visitorData.isNullOrBlank()) put("X-Goog-Visitor-Id", visitorData) - if (client.name == "WEB_REMIX" && ytAuth.connection.value.isConnected) { - ytAuth.cookieHeaderValue()?.let { put("Cookie", it) } - ytAuth.authorizationHeaderValue()?.let { put("Authorization", it) } - } - } + val streamRequestHeaders = mediaStreamHeaders(client, signedIn) val responseExpiry = streaming?.string("expiresInSeconds") ?.toLongOrNull() ?.let { System.currentTimeMillis() + it.coerceAtLeast(1L) * 1_000L } + val allowProgressive = client.isProgressiveOnly && maxBitrateBps == null val formats = buildList { streaming?.array("formats").orEmpty().forEach { add(it to false) } streaming?.array("adaptiveFormats").orEmpty().forEach { add(it to true) } @@ -834,18 +876,13 @@ internal suspend fun InnerTubeMusicApi.resolveDirectClientStream( // A decoder from a separately fetched player can return a plausible but // invalid signature. Use the exact script paired with this request first. val deciphered = if (cipherContext != null) { - innerTubeXExtractor.decipherAudioUrls(videoId, audioCiphers, cipherContext, directAudioUrls).toMutableMap() + innerTubeXExtractor.decipherAudioUrls(videoId, audioCiphers, cipherContext, directAudioUrls) + } else if (audioCiphers.isNotEmpty()) { + innerTubeXExtractor.decipherAudioUrls(videoId, audioCiphers) } else { - audioCiphers.mapNotNull { cipher -> - streamExtractor.decipherStreamUrl(videoId, cipher)?.let { cipher to it } - }.toMap().toMutableMap().also { decoded -> - val unresolved = audioCiphers.filterNot(decoded::containsKey) - if (client.name == "WEB_REMIX" && unresolved.isNotEmpty()) { - decoded.putAll(innerTubeXExtractor.decipherAudioUrls(videoId, unresolved)) - } - } + emptyMap() } - val candidates = formats.mapNotNull { (element, isAdaptive) -> + val directCandidates = formats.mapNotNull { (element, isAdaptive) -> val format = element as? JsonObject ?: return@mapNotNull null val url = format.string("url")?.let { direct -> if (cipherContext != null) deciphered[direct] else direct @@ -856,8 +893,14 @@ internal suspend fun InnerTubeMusicApi.resolveDirectClientStream( null } ?: return@mapNotNull null - val mime = format.string("mimeType") - if (mime?.startsWith("audio/") != true) return@mapNotNull null + if (url.startsWith("sabr:", ignoreCase = true)) return@mapNotNull null + val mime = format.string("mimeType") ?: return@mapNotNull null + val isAudio = mime.startsWith("audio/") + val isProgressiveMp4 = allowProgressive && + !isAdaptive && + mime.startsWith("video/mp4", ignoreCase = true) && + !format.string("audioSampleRate").isNullOrBlank() + if (!isAudio && !isProgressiveMp4) return@mapNotNull null val finalUrl = appendPoToken(url, gvsPoToken) YouTubeAudioStream( videoId = videoId, @@ -879,18 +922,48 @@ internal suspend fun InnerTubeMusicApi.resolveDirectClientStream( isDrc = format.string("isDrc") == "true" || isDrcAudioUrl(finalUrl), ) } - .filter(::isCompatibleAudioCandidate) + .filter { candidate -> + isCompatibleAudioCandidate(candidate) || + (allowProgressive && candidate.mimeType.equals("video/mp4", ignoreCase = true)) + } .filter { it.meetsBitrateLimit(maxBitrateBps) } .sortedWith( // DRC shares itag 251/140 with the full master, often at a higher // bitrate, so bitrate alone kept picking the quiet variant. + // Prefer adaptive audio-only formats over progressive, and Opus (webm) + // over AAC before ranking by bitrate. compareBy { it.isDrc } - .thenBy { it.isAdaptive } - // Opus (webm) before AAC: at YouTube's ~130-160 kbps it is the - // better codec, and listed bitrates differ by only a few kbps. - .thenByDescending { it.mimeType?.contains("webm", ignoreCase = true) == true } + .thenByDescending { it.isAdaptive } + .thenBy { audioCodecPreferenceRank(it) } .thenByDescending { it.bitrate }, ) + val hlsUrl = (streaming?.string("hlsManifestUrl") ?: streaming?.string("hlsUrl")) + ?.takeIf { it.startsWith("https://", ignoreCase = true) && maxBitrateBps == null } + val hlsCandidate = hlsUrl?.let { url -> + YouTubeAudioStream( + videoId = videoId, + url = url, + itag = null, + mimeType = "application/vnd.apple.mpegurl", + codec = "hls", + bitrate = 128_000, + sampleRateHz = null, + durationMs = null, + contentLength = null, + isAdaptive = true, + clientProfile = client.key, + authScope = authScope, + requestHeaders = streamRequestHeaders, + expiresAtEpochMs = listOfNotNull(streamExpiryEpochMs(url), responseExpiry).minOrNull() + ?: System.currentTimeMillis() + UNKNOWN_STREAM_EXPIRY_TTL_MS, + userAgent = client.userAgent, + ) + } + val candidates = if (directCandidates.isNotEmpty() || hlsCandidate == null) { + directCandidates + } else { + listOf(hlsCandidate) + } noteAttempt("client=${client.name} compatibleCandidates=${candidates.size} cipherAllowed=$allowCipherFormats") // Probe full playback ranges before choosing a format. Tiny probes can // succeed even when the media request itself will receive HTTP 403. @@ -898,7 +971,16 @@ internal suspend fun InnerTubeMusicApi.resolveDirectClientStream( return candidates.firstOrNull() ?: throw IOException("${client.key} returned no usable audio URL") } - if (currentCoroutineContext()[DeferredStreamProbe] != null) { + // Only defer the 1 MiB boundary probe for VISIONOS (which consistently + // serves full-file ranges) or paired WEB_REMIX with a PoToken. All + // other clients (e.g. ANDROID_VR, TVHTML5) must pass the 1 MiB probe + // first so 512 KB-capped 403 URLs are rejected before hitting ~59s. + val canDeferProbe = currentCoroutineContext()[DeferredStreamProbe] != null && + ( + client.name == FAST_PREFERRED_CLIENT || + (client.name == "WEB_REMIX" && cipherContext != null && !gvsPoToken.isNullOrBlank()) + ) + if (canDeferProbe) { val first = candidates.firstOrNull() ?: throw IOException("${client.key} returned no usable audio URL") apiScope.launch { // Run after first audio: a 1 MiB read on the same new host @@ -1047,15 +1129,42 @@ internal fun InnerTubeMusicApi.extractCodec(mimeType: String): String? = CODEC_P internal fun InnerTubeMusicApi.isCompatibleAudioCandidate(stream: YouTubeAudioStream): Boolean { val mime = stream.mimeType.orEmpty().lowercase() val codec = stream.codec.orEmpty().lowercase() + if (codec.contains("vorbis")) return false return when { - mime == "audio/webm" -> codec.isBlank() || codec.contains("opus") || codec.contains("vorbis") + mime == "audio/webm" -> codec.isBlank() || codec.contains("opus") mime == "audio/mp4" || mime == "audio/m4a" -> codec.isBlank() || codec.contains("mp4a") || codec.contains("aac") - mime == "audio/ogg" -> codec.isBlank() || codec.contains("opus") || codec.contains("vorbis") mime == "audio/mpeg" -> true else -> false } } +private fun audioCodecPreferenceRank(stream: YouTubeAudioStream): Int { + val mime = stream.mimeType.orEmpty().lowercase() + val codec = stream.codec.orEmpty().lowercase() + return when { + codec.contains("opus") || mime == "audio/webm" -> 0 + codec.contains("mp4a") || codec.contains("aac") || mime == "audio/mp4" || mime == "audio/m4a" -> 1 + else -> 2 + } + } + +private fun InnerTubeMusicApi.probeVideoStream(stream: YouTubeVideoStream): Boolean { + val request = playbackProbeRequest(stream.url, stream.requestHeaders) + val call = innerTubeClient.newCall(request) + call.timeout().timeout(VIDEO_PROBE_TIMEOUT_MS, TimeUnit.MILLISECONDS) + return try { + call.execute().use { response -> + acceptsPlaybackProbe(response.code, response.header("Content-Type").orEmpty()) + } + } catch (cancellation: kotlinx.coroutines.CancellationException) { + throw cancellation + } catch (_: Exception) { + false + } + } + +private const val VIDEO_PROBE_TIMEOUT_MS = 1_500L + internal fun InnerTubeMusicApi.logStreamEvent( stage: String, stream: YouTubeAudioStream, @@ -1157,12 +1266,18 @@ internal suspend fun InnerTubeMusicApi.findBestMatchImpl( /** Catalog length of the wanted recording; favours the same cut. */ expectedDurationMs: Long? = null, ): YouTubeMusicTrack { - val cleanArtist = artist.takeUnless { it.equals("Unknown artist", ignoreCase = true) }.orEmpty() + val cleanArtist = artist.takeUnless { + it.equals("Unknown artist", ignoreCase = true) || + it.equals("Various artists", ignoreCase = true) || + it.equals("Unknown", ignoreCase = true) + }.orEmpty() + val primaryArtist = primaryArtistForMatch(cleanArtist) // Same title and artist can be different recordings (album vs single // edit); keep the runtime in the key so one never answers for the other. val cacheKey = "${normalize(cleanArtist)}|${normalize(title)}|${expectedDurationMs?.div(1000L) ?: ""}" matchCache[cacheKey]?.takeIf { it.videoId != excludedVideoId && it.videoId !in excludedVideoIds }?.let { return it } val searchTitle = baseTitle(title).trim().ifBlank { title.trim() } + val coreTitle = coreSongTitle(title, cleanArtist).ifBlank { searchTitle } val query = listOf(searchTitle, cleanArtist).filter { it.isNotBlank() }.joinToString(" ") val results = searchSongs( query = query, @@ -1181,12 +1296,11 @@ internal suspend fun InnerTubeMusicApi.findBestMatchImpl( similarity(baseTitle(candidate.title), baseTitle(title)), ) >= 60 || TextMatch.isSafeTitleMatch(candidate.title, title, cleanArtist)) && (cleanArtist.isBlank() || - similarity(candidate.artist, cleanArtist) >= 35 || - normalize(candidate.artist).contains(normalize(cleanArtist)) || - normalize(cleanArtist).contains(normalize(candidate.artist)) || - // "P.L.L" is credited as "PLL". + meaningfulArtistMatch(candidate.artist, cleanArtist) || + (primaryArtist.isNotBlank() && meaningfulArtistMatch(candidate.artist, primaryArtist)) || normalize(candidate.artist).replace(" ", "").contains(normalize(cleanArtist).replace(" ", "")) || normalize(candidate.title).contains(normalize(cleanArtist)) || + candidateSharesArtist(candidate, cleanArtist) || // Sources often credit the composer while YTM credits the singers. TextMatch.isRuntimeConfirmedTitleMatch(candidate.title, title, expectedDurationMs, candidate.durationSeconds)) } @@ -1197,17 +1311,36 @@ internal suspend fun InnerTubeMusicApi.findBestMatchImpl( val baseBest = pick(results) // The base query has no "(Noiseflow & Triple X Remix)": that remix only turns up // searching the full title, and another remix must not stand in for it. - val needsFullTitle = baseBest == null || + val needsFallback = baseBest == null || TextMatch.versionNames(title).any { it !in tokens(baseBest.title) } - // Like other YTM clients, retry with looser queries: the full title, then the - // title alone (a wrong artist credit in the query can push the song out of the results). - val fallbackQueries = if (!needsFullTitle) emptyList() else listOf( - listOf(title.trim(), cleanArtist).filter { it.isNotBlank() }.joinToString(" "), - searchTitle, - ).distinct().filter { it != query } + // Multi-tier fallback matching LastWave-Desktop: full title, primary artist, + // stripped core title, and title-only (verified with candidateSharesArtist). + val fallbackQueries = if (!needsFallback) emptyList() else buildList { + add(listOf(title.trim(), cleanArtist).filter { it.isNotBlank() }.joinToString(" ")) + if (primaryArtist.isNotBlank() && normalize(primaryArtist) != normalize(cleanArtist)) { + add(listOf(searchTitle, primaryArtist).filter { it.isNotBlank() }.joinToString(" ")) + add(listOf(title.trim(), primaryArtist).filter { it.isNotBlank() }.joinToString(" ")) + } + if (coreTitle.isNotBlank() && normalize(coreTitle) != normalize(searchTitle)) { + add(listOf(coreTitle, primaryArtist.ifBlank { cleanArtist }).filter { it.isNotBlank() }.joinToString(" ")) + add(coreTitle) + } + add(searchTitle) + }.distinct().filter { it.isNotBlank() && it != query } val fallbackBest = fallbackQueries.firstNotNullOfOrNull { fallback -> pick(searchSongs(query = fallback, limit = 30, prefetchStreams = prefetchStreams)) - } + } ?: if (baseBest == null) { + // Tier 5 (LastWave-Desktop parity): Songs-only search can return + // covers/remixes that crowd out the real track. Query unfiltered + // searchMixed() with the same strict take/duration/artist vetoes. + val mixedQueries = listOfNotNull( + listOf(searchTitle, primaryArtist.ifBlank { cleanArtist }).filter { it.isNotBlank() }.joinToString(" "), + listOf(coreTitle, primaryArtist).filter { it.isNotBlank() }.joinToString(" ").takeIf { it.isNotBlank() }, + ).distinct() + mixedQueries.firstNotNullOfOrNull { mq -> + pick(searchMixed(query = mq, limit = 20)) + } + } else null val best = pick(listOfNotNull(fallbackBest, baseBest)) ?: throw IOException("No reliable YouTube Music match found for $title by $artist") return best.also { @@ -1216,6 +1349,81 @@ internal suspend fun InnerTubeMusicApi.findBestMatchImpl( } } +private val PRIMARY_ARTIST_FEAT_REGEX = Regex("(?i)\\s+[(\\[]?(?:feat\\.?|ft\\.?|featuring)\\b") +private val PRIMARY_ARTIST_COMMA_KEEP_REGEX = Regex("(?i),\\s*(the|and)\\b") +private val PRIMARY_ARTIST_SPLIT_REGEX = Regex("\\s*[,&]\\s*") +private val CORE_TITLE_HANDLE_REGEX = Regex("@\\w+") +private val CORE_TITLE_NOISE_REGEX = Regex("(?i)[(\\[][^)\\]]*(?:video|official|lyric|audio|visuali[sz]er|amv|\\bmv\\b|remaster|hd|4k)[^)\\]]*[)\\]]") +private val CORE_TITLE_DASH_REGEX = Regex("\\s[-–—]\\s") +private val ARTIST_STOP_WORDS = setOf("the", "and", "feat", "ft", "featuring", "with") + +internal fun primaryArtistForMatch(artist: String): String { + val head = artist.substringBefore(';').trim() + if (head.isBlank()) return "" + val beforeFeat = PRIMARY_ARTIST_FEAT_REGEX.split(head, limit = 2).firstOrNull()?.trim().orEmpty() + if (beforeFeat.isBlank()) return "" + if (PRIMARY_ARTIST_COMMA_KEEP_REGEX.containsMatchIn(beforeFeat) && !beforeFeat.contains(" & ")) { + return beforeFeat + } + val lower = beforeFeat.lowercase() + if (lower == "unknown artist" || lower == "various artists" || lower == "unknown") return "" + return PRIMARY_ARTIST_SPLIT_REGEX.split(beforeFeat, limit = 2).firstOrNull()?.trim().orEmpty() +} + +private fun meaningfulArtistMatch(candidateArtist: String, wantedArtist: String): Boolean { + val normC = TextMatch.normalize(candidateArtist) + val normW = TextMatch.normalize(wantedArtist) + if (normW.isBlank() || normC.isBlank()) return false + if (normC.contains(normW) || normW.contains(normC)) return true + val cTokens = TextMatch.tokens(candidateArtist).filterNot { it in ARTIST_STOP_WORDS } + val wTokens = TextMatch.tokens(wantedArtist).filterNot { it in ARTIST_STOP_WORDS } + if (cTokens.isEmpty() || wTokens.isEmpty()) { + return TextMatch.similarity(candidateArtist, wantedArtist) >= 35 + } + return TextMatch.similarity(cTokens.joinToString(" "), wTokens.joinToString(" ")) >= 35 +} + +internal fun candidateSharesArtist(candidate: YouTubeMusicTrack, artist: String): Boolean { + if (artist.isBlank()) return true + val primary = primaryArtistForMatch(artist) + val normCArtist = TextMatch.normalize(candidate.artist) + val normCTitle = TextMatch.normalize(candidate.title) + for (candidateArtist in listOfNotNull(artist, primary.takeIf { it.isNotBlank() })) { + val normW = TextMatch.normalize(candidateArtist) + if (normW.isBlank()) continue + if (meaningfulArtistMatch(candidate.artist, candidateArtist) || + normCArtist.contains(normW) || + (normCArtist.isNotBlank() && normW.contains(normCArtist)) || + normCTitle.contains(normW) + ) { + return true + } + } + val artistTokens = TextMatch.tokens(artist) + .filterTo(mutableSetOf()) { it.length >= 2 && it !in ARTIST_STOP_WORDS } + if (artistTokens.isEmpty()) return false + val hay = TextMatch.tokens("${candidate.artist} ${candidate.title}") + return artistTokens.any { it in hay } +} + +internal fun coreSongTitle(title: String, artist: String): String { + val noHandle = title.replace(CORE_TITLE_HANDLE_REGEX, " ") + val noNoise = noHandle.replace(CORE_TITLE_NOISE_REGEX, " ") + var core = PRIMARY_ARTIST_FEAT_REGEX.split(noNoise, limit = 2).firstOrNull().orEmpty() + val dash = CORE_TITLE_DASH_REGEX.find(core) + if (dash != null && artist.isNotBlank()) { + val head = core.substring(0, dash.range.first) + val normArtist = TextMatch.normalize(artist) + val normHead = TextMatch.normalize(head) + if (normHead.isNotBlank() && normArtist.isNotBlank() && + (normArtist.contains(normHead) || normHead.contains(normArtist)) + ) { + core = core.substring(dash.range.last + 1) + } + } + return core.trim().replace(Regex("\\s+"), " ") +} + internal suspend fun InnerTubeMusicApi.findBestMatchOrNullImpl( title: String, artist: String, diff --git a/app/src/test/java/com/lastwave/app/data/music/YouTubePlaybackRequestTest.kt b/app/src/test/java/com/lastwave/app/data/music/YouTubePlaybackRequestTest.kt index 77b2cd6d70..551dc394ab 100644 --- a/app/src/test/java/com/lastwave/app/data/music/YouTubePlaybackRequestTest.kt +++ b/app/src/test/java/com/lastwave/app/data/music/YouTubePlaybackRequestTest.kt @@ -1,9 +1,11 @@ package com.lastwave.app.data.music +import io.mockk.mockk +import kotlinx.serialization.json.boolean import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.int import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive -import kotlinx.serialization.json.int import kotlinx.serialization.json.put import org.junit.Assert.* import org.junit.Test @@ -32,6 +34,13 @@ class YouTubePlaybackRequestTest { assertFalse(body["context"]!!.jsonObject.containsKey("serviceIntegrityDimensions")) assertEquals(context, body["context"]) assertEquals(20345, body["playbackContext"]!!.jsonObject["contentPlaybackContext"]!!.jsonObject["signatureTimestamp"]!!.jsonPrimitive.int) + assertTrue(body["videoCheckOk"]!!.jsonPrimitive.boolean) + } + + @Test fun musicEndpointClientOmitsVideoCheckAndHtml5Pref() { + val body = playbackPlayerBody("video-id", context, null, null, useMusicPlayerEndpoint = true) + assertFalse(body.containsKey("videoCheckOk")) + assertFalse(body.containsKey("playbackContext")) } @Test fun missingTokenAndTimestampAreOmitted() { @@ -41,15 +50,72 @@ class YouTubePlaybackRequestTest { assertFalse(playbackPlayerBody("video-id", context, null, " ").containsKey("serviceIntegrityDimensions")) } - @Test fun signedInClientPrecedesPreviousAnonymousWinner() { - val ordered = listOf("ANDROID_VR", "IOS", "TVHTML5_SIMPLY_EMBEDDED_PLAYER", "WEB_REMIX") - .sortedBy { playbackClientPriority(it, true, "ANDROID_VR") } - assertEquals(listOf("WEB_REMIX", "ANDROID_VR", "IOS", "TVHTML5_SIMPLY_EMBEDDED_PLAYER"), ordered) + @Test fun visionOsLeadsEvenWhenSignedInAndProgressiveTrailsLast() { + val ordered = listOf("IOS_PRODUCER", "WEB_REMIX", "TVHTML5", "ANDROID_VR", "VISIONOS", "VISIONOS_1_02", "WEB_CREATOR", "WEB_EMBEDDED_PLAYER") + .sortedBy { playbackClientPriority(it, connected = true, lastSuccessful = "ANDROID_VR") } + assertEquals(listOf("VISIONOS", "ANDROID_VR", "VISIONOS_1_02", "TVHTML5", "WEB_REMIX", "WEB_CREATOR", "WEB_EMBEDDED_PLAYER", "IOS_PRODUCER"), ordered) + } + + @Test fun signedInWebRemixWinnerDoesNotSkipVisionOsOrAndroidVr() { + val ordered = listOf("WEB_REMIX", "ANDROID_VR", "VISIONOS", "TVHTML5") + .sortedBy { playbackClientPriority(it, connected = true, lastSuccessful = "WEB_REMIX") } + assertEquals(listOf("VISIONOS", "ANDROID_VR", "TVHTML5", "WEB_REMIX"), ordered) } - @Test fun anonymousPlaybackKeepsPreviousWinnerFirst() { - val ordered = listOf("ANDROID_VR", "IOS", "WEB_REMIX") - .sortedBy { playbackClientPriority(it, false, "IOS") } - assertEquals(listOf("IOS", "ANDROID_VR", "WEB_REMIX"), ordered) + @Test fun nonWebClientsOmitMusicOriginAndRefererHeadersAndMatchMetrolistIds() { + val visionOs = PLAYER_CLIENTS.first { it.id == "VISIONOS" } + val androidVr = PLAYER_CLIENTS.first { it.name == "ANDROID_VR" } + val webRemix = PLAYER_CLIENTS.first { it.name == "WEB_REMIX" } + val webCreator = PLAYER_CLIENTS.first { it.name == "WEB_CREATOR" } + assertEquals("https://music.youtube.com/youtubei/v1", visionOs.playerApiBase) + assertEquals("https://studio.youtube.com/youtubei/v1", webCreator.playerApiBase) + assertEquals("2", CLIENT_IDS["MWEB"]) + assertEquals("62", CLIENT_IDS["WEB_CREATOR"]) + assertEquals("92", CLIENT_IDS["IOS_PRODUCER"]) + assertFalse(visionOs.streamRequestHeaders.containsKey("Origin")) + assertFalse(visionOs.streamRequestHeaders.containsKey("Referer")) + assertFalse(androidVr.streamRequestHeaders.containsKey("Origin")) + assertFalse(androidVr.streamRequestHeaders.containsKey("Referer")) + assertEquals("https://music.youtube.com", webRemix.streamRequestHeaders["Origin"]) + assertEquals("https://music.youtube.com/", webRemix.streamRequestHeaders["Referer"]) + assertEquals("https://studio.youtube.com", webCreator.streamRequestHeaders["Origin"]) + } + + @Test fun primaryArtistAndCoreTitleHelpersMatchDesktopFallbacks() { + assertEquals("Alan Walker", primaryArtistForMatch("Alan Walker, Ava Max")) + assertEquals("DJ Gollum", primaryArtistForMatch("DJ Gollum & Scarlet feat. Someone")) + assertEquals("The Weeknd, The", primaryArtistForMatch("The Weeknd, The")) + assertEquals("Blinding Lights", coreSongTitle("The Weeknd - Blinding Lights (Official Video) [4K]", "The Weeknd")) + assertTrue( + candidateSharesArtist( + YouTubeMusicTrack("vid1", "Alone (feat. Ava Max)", "Alan Walker"), + "Alan Walker, Ava Max", + ), + ) + assertFalse( + candidateSharesArtist( + YouTubeMusicTrack("vid2", "Mr. Brightside (Live)", "The Guinness Brothers"), + "The Killers", + ), + ) + } + + @Test fun visionOsIsFirstInFastOrderAndOggVorbisAreRejected() { + assertEquals("VISIONOS", DIRECT_FAST_CLIENT_ORDER.first()) + val api = InnerTubeMusicApi( + http = mockk(relaxed = true), + innerTubeXExtractor = mockk(relaxed = true), + ytAuth = mockk(relaxed = true), + settingsPreferences = mockk(relaxed = true), + appContext = mockk(relaxed = true), + ) + val opus = YouTubeAudioStream("vid", "https://example.test/a", 251, "audio/webm", "opus", 145_000, null, null, null, true, "VISIONOS", "anonymous") + val aac = opus.copy(itag = 140, mimeType = "audio/mp4", codec = "mp4a.40.2", bitrate = 128_000) + val ogg = opus.copy(itag = 171, mimeType = "audio/ogg", codec = "vorbis", bitrate = 128_000) + val webmVorbis = opus.copy(itag = 171, mimeType = "audio/webm", codec = "vorbis", bitrate = 128_000) + assertTrue(api.isCompatibleAudioCandidate(opus)) + assertTrue(api.isCompatibleAudioCandidate(aac)) + assertFalse(api.isCompatibleAudioCandidate(ogg)) + assertFalse(api.isCompatibleAudioCandidate(webmVorbis)) } } From 2f854e3aac0e62c4869ca5f8a3c1831ec6cc8206 Mon Sep 17 00:00:00 2001 From: ajisth69 Date: Sat, 5 Dec 2026 15:20:18 +0530 Subject: [PATCH 5/5] fix(innertube): fix fetchFreshVisitorData visibility and WebConfig ref --- .../main/java/com/lastwave/app/data/music/InnerTubeMusicApi.kt | 2 +- .../lastwave/app/data/music/InnerTubeMusicApiStreamResolver.kt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/com/lastwave/app/data/music/InnerTubeMusicApi.kt b/app/src/main/java/com/lastwave/app/data/music/InnerTubeMusicApi.kt index 2bc02c86ec..e8b90b2689 100644 --- a/app/src/main/java/com/lastwave/app/data/music/InnerTubeMusicApi.kt +++ b/app/src/main/java/com/lastwave/app/data/music/InnerTubeMusicApi.kt @@ -2709,7 +2709,7 @@ class InnerTubeMusicApi @Inject constructor( ) } - private suspend fun fetchFreshVisitorData(): String? = withContext(Dispatchers.IO) { + internal suspend fun fetchFreshVisitorData(): String? = withContext(Dispatchers.IO) { val consentCookie = "CONSENT=YES+cb.20210328-17-p0.en+FX+100; SOCS=CAISEwgDEgk0ODE3Nzk3MjQaAmVuIAEaBgiA_LyaBg" // 1. Try /youtubei/v1/visitor_id try { diff --git a/app/src/main/java/com/lastwave/app/data/music/InnerTubeMusicApiStreamResolver.kt b/app/src/main/java/com/lastwave/app/data/music/InnerTubeMusicApiStreamResolver.kt index 47063b0f01..bdbf1cd0b3 100644 --- a/app/src/main/java/com/lastwave/app/data/music/InnerTubeMusicApiStreamResolver.kt +++ b/app/src/main/java/com/lastwave/app/data/music/InnerTubeMusicApiStreamResolver.kt @@ -439,7 +439,7 @@ internal suspend fun InnerTubeMusicApi.resolveDirectUrlFastPath( ?: visitorData if (isValidVisitorData(visitorData)) { val currentCfg = webConfig - webConfig = WebConfig( + webConfig = InnerTubeMusicApi.WebConfig( apiKey = currentCfg?.apiKey ?: FALLBACK_WEB_KEY, clientVersion = currentCfg?.clientVersion ?: FALLBACK_WEB_VERSION, visitorData = visitorData,