Modern Apps git

← Modern-Apps.git

youpipe: add tests for sabr slice (second pass)

Commit
d22f05f4efd624d25155461ec4008ca54825f937
Author
Vayun Mathur <[email protected]>
When
2026-11-07 08:39 UTC (29 days ago)
Parents
ec62a73
Slice coverage 18.0% -> 85.3% INSTRUCTION over the sabr/ package
classes in the merged report (3034/16838 -> 14356/16838 instructions),
past the 85% slice target. Full :youpipe unit suite passes
(172 tests, 0 failures) and :youpipe:lint is green.

12 new slice-named test files (SabrSlice1*): a hand-crafted sidx
init-segment fixture building real SourceSpecs; session playhead /
seek / timeout / interruption logic and pump failure termination; the
segment data source (init, offsets, length caps, streamed media);
a hand-built UMP server (protobuf media headers over a fake NewPipe
downloader) driving the coordinator retry + server-backoff loop,
SessionStore init fetch, and the pump's segment cache; the DASH
media source lifecycle including period delegation, build-error
surfacing and release-during-build; bootst rap parser escapes and
config selection; the WebView runtime's init-failure machinery under
Robolectric; and on the emulator a complete PO-token mint using a
fake BotGuard VM script (generator, provider content + SESSION
tokens, obtain-error, interpreter-URL fetch), the download helper's
writeTracks-then-mux-failure path, and the muxer over real
MediaMuxer-written containers.

Untestable remainder: SharedWebViewRuntime renderer-death callback
(cannot kill a WebView renderer from a test), the muxer sample-buffer
resize branch (MediaExtractor never returns an oversized sample),
and live-YouTube paths (real BotGuard programs and attestation).
No production code changed, no bugs found.

(cherry picked from commit ffaf48e0e8931cd06e06b17dcc7b0a1ad549220e)

Diff

youpipe/src/androidTest/java/com/vayunmathur/youpipe/util/sabr/SabrSlice1DeviceDownloadTest.kt
diff --git a/youpipe/src/androidTest/java/com/vayunmathur/youpipe/util/sabr/SabrSlice1DeviceDownloadTest.kt b/youpipe/src/androidTest/java/com/vayunmathur/youpipe/util/sabr/SabrSlice1DeviceDownloadTest.ktnew file mode 100644index 0000000000..77992d0eb2--- /dev/null+++ b/youpipe/src/androidTest/java/com/vayunmathur/youpipe/util/sabr/SabrSlice1DeviceDownloadTest.kt@@ -0,0 +1,110 @@+package com.vayunmathur.youpipe.util.sabr++import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import java.io.File+import java.io.IOException+import org.junit.Assert.assertTrue+import org.junit.Assert.fail+import org.junit.Test+import org.junit.runner.RunWith+import org.schabi.newpipe.extractor.NewPipe+import org.schabi.newpipe.extractor.downloader.Response+import org.schabi.newpipe.extractor.services.youtube.sabrng.exception.SabrProtocolException++/**+ * Slice-1 (sabr/) device pass: the download helper end to end — token mint+ * (fake BotGuard VM), init fetch and media writeTracks over a fake UMP+ * server, then the mux failure cleanup when the written bytes are not a+ * real container.+ */+@RunWith(AndroidJUnit4::class)+class SabrSlice1DeviceDownloadTest {++    @Test fun downloadWritesTracksThenFailsMuxCleanly() {+        val context = InstrumentationRegistry.getInstrumentation().targetContext+        val audioInit = SabrSlice1DeviceFixtures.sidx(durationsMs = listOf(5000, 5000, 5000))+        val videoInit = SabrSlice1DeviceFixtures.sidx(durationsMs = listOf(10000, 10000))+        val media = ByteArray(48) { 0x2A }+        NewPipe.init(SabrSlice1DeviceMintTest.Companion.RoutingDownloader { request ->+            when {+                request.url.contains("youtube.com") && !request.url.contains("sabr") ->+                    Response(200, null, null, SabrSlice1DeviceMintTest.Companion.homePage(), request.url)+                else -> Response(+                    200, null, mapOf("Content-Type" to listOf("application/vnd.yt-ump")),+                    String(+                        SabrSlice1DeviceUmp.segmentParts(1, 140, init = true, seq = 0, media = audioInit) ++                            SabrSlice1DeviceUmp.segmentParts(2, 137, init = true, seq = 0, media = videoInit) ++                            SabrSlice1DeviceUmp.segmentParts(3, 140, init = false, seq = 1, media = media) ++                            SabrSlice1DeviceUmp.segmentParts(4, 140, init = false, seq = 2, media = media) ++                            SabrSlice1DeviceUmp.segmentParts(5, 140, init = false, seq = 3, media = media) ++                            SabrSlice1DeviceUmp.segmentParts(6, 137, init = false, seq = 1, media = media) ++                            SabrSlice1DeviceUmp.segmentParts(7, 137, init = false, seq = 2, media = media),+                        Charsets.ISO_8859_1,+                    ),+                    request.url,+                )+            }+        })+        // Flush any stale shared-provider initialization left by an earlier test in this+        // process: a failed task is dropped on first use, so the download below re-mints+        // against this test's downloader.+        runCatching { LocalDomPoTokenProvider.shared(context).getPoTokenBytes("flush") }+        val workDir = File(context.cacheDir, "sabr-dl-device").apply { mkdirs() }+        val output = File(workDir, "out.mp4")+        val info = SabrSlice1DeviceUmp.configInfo(+            SabrSlice1DeviceFixtures.format(140, "audio/mp4"),+            SabrSlice1DeviceFixtures.format(137, "video/mp4; codecs=\"avc1.640028\""),+        )+        var progressSeen = false+        try {+            SabrNgDownloadHelper.download(context, "vidS1", 137, 140, null, info, workDir, output) { progressSeen = true }+            fail("muxing garbage segments must fail")+        } catch (expected: IOException) {+            assertTrue(expected.message!!.contains("SABR download failed"))+        }+        assertTrue("no output may survive a failed download", !output.exists())+    }++    @Test fun generatorWithInterpreterUrlFetchesVmThenMints() {+        val context = InstrumentationRegistry.getInstrumentation().targetContext+        NewPipe.init(SabrSlice1DeviceMintTest.Companion.RoutingDownloader { request ->+            if (request.url.contains("interp.js")) {+                Response(200, null, null, SabrSlice1DeviceMintTest.Companion.FAKE_VM_JS, request.url)+            } else {+                Response(200, null, null, "", request.url)+            }+        })+        val bootstrap = YoutubePageAttestationBootstrap(+            visitorData = "visitor-data", clientName = "WEB", clientVersion = "2.5.1",+            binding = YoutubePoTokenBinding.CONTENT, eventId = "evt-1",+            challenge = SabrAttChallengeData("PROG", "MyVM", null, "https://example.com/interp.js"),+        )+        val generator = LocalDomPoTokenGenerator.create(context, bootstrap)+        assertTrue(generator.mint("vid-url").contentEquals(byteArrayOf(1, 2, 3, 4)))+        generator.close()+    }++    @Test fun generatorFailsOnGarbageIntegrityResponse() {+        val context = InstrumentationRegistry.getInstrumentation().targetContext+        NewPipe.init(object : org.schabi.newpipe.extractor.downloader.Downloader() {+            override fun execute(request: org.schabi.newpipe.extractor.downloader.Request): Response =+                if (request.url.contains("jnn-pa.googleapis.com")) {+                    Response(200, null, null, "not an integrity response", request.url)+                } else {+                    Response(200, null, null, "", request.url)+                }+        })+        val bootstrap = YoutubePageAttestationBootstrap(+            visitorData = "visitor-data", clientName = "WEB", clientVersion = "2.5.1",+            binding = YoutubePoTokenBinding.CONTENT, eventId = "evt-1",+            challenge = SabrAttChallengeData("PROG", "MyVM", SabrSlice1DeviceMintTest.Companion.FAKE_VM_JS, null),+        )+        try {+            LocalDomPoTokenGenerator.create(context, bootstrap)+            fail("garbage integrity response must fail initialization")+        } catch (expected: SabrProtocolException) {+            assertTrue(expected.message!!.isNotBlank())+        }+    }+}
youpipe/src/androidTest/java/com/vayunmathur/youpipe/util/sabr/SabrSlice1DeviceFixtures.kt
diff --git a/youpipe/src/androidTest/java/com/vayunmathur/youpipe/util/sabr/SabrSlice1DeviceFixtures.kt b/youpipe/src/androidTest/java/com/vayunmathur/youpipe/util/sabr/SabrSlice1DeviceFixtures.ktnew file mode 100644index 0000000000..4042e6d4bd--- /dev/null+++ b/youpipe/src/androidTest/java/com/vayunmathur/youpipe/util/sabr/SabrSlice1DeviceFixtures.kt@@ -0,0 +1,49 @@+package com.vayunmathur.youpipe.util.sabr++import java.nio.ByteBuffer+import java.nio.ByteOrder+import org.schabi.newpipe.extractor.services.youtube.ItagItem+import org.schabi.newpipe.extractor.services.youtube.sabrng.YoutubeSabrInfo++/** Device-side copies of the JVM slice fixtures (androidTest cannot see src/test). */+object SabrSlice1DeviceFixtures {+    fun sidx(timescale: Int = 1000, durationsMs: List<Int>): ByteArray {+        val size = 8 + 4 + 4 + 4 + 4 + 4 + 2 + 2 + durationsMs.size * 12+        val buffer = ByteBuffer.allocate(size).order(ByteOrder.BIG_ENDIAN)+        buffer.putInt(size); buffer.put("sidx".toByteArray(Charsets.US_ASCII))+        buffer.putInt(0); buffer.putInt(1); buffer.putInt(timescale)+        buffer.putInt(0); buffer.putInt(0)+        buffer.putShort(0); buffer.putShort(durationsMs.size.toShort())+        for (duration in durationsMs) {+            buffer.putInt(1024); buffer.putInt(duration * timescale / 1000); buffer.putInt(0)+        }+        return buffer.array()+    }++    fun format(itag: Int, mime: String): YoutubeSabrInfo.Format =+        YoutubeSabrInfo.Format.fromParsedFormat(+            parsedFormat = ItagItem.getItag(itag), lastModified = 0L, xtags = null, mimeType = mime,+            audioTrackId = null, audioTrackDisplayName = null, drc = false,+            initializationUrl = null, initRangeStart = 0L, initRangeEnd = 0L,+        )+}++/** UMP part builders (device copies of SabrSlice1UmpServerTest's helpers). */+object SabrSlice1DeviceUmp {+    private fun umpInt(value: Int): ByteArray = when {+        value < 128 -> byteArrayOf(value.toByte())+        else -> byteArrayOf((128 + value % 64).toByte(), (value / 64).toByte())+    }+    private fun umpPart(type: Int, payload: ByteArray): ByteArray = umpInt(type) + umpInt(payload.size) + payload++    fun segmentParts(headerId: Int, itag: Int, init: Boolean, seq: Int, media: ByteArray): ByteArray {+        val header = org.schabi.newpipe.extractor.services.youtube.sabrng.protocol.SabrProto.Writer().apply {+            writeInt32(1, headerId); writeInt32(3, itag); writeBool(8, init)+            writeInt32(9, seq); writeUInt64(14, media.size.toLong())+        }.toByteArray()+        return umpPart(20, header) + umpPart(21, byteArrayOf(headerId.toByte()) + media) + umpPart(22, byteArrayOf(headerId.toByte()))+    }++    fun configInfo(vararg formats: YoutubeSabrInfo.Format): YoutubeSabrInfo =+        YoutubeSabrInfo("vidS1", "cpn", "1.0", null, "https://127.0.0.1:9/sabr", "AAAA", formats.toList(), null)+}
youpipe/src/androidTest/java/com/vayunmathur/youpipe/util/sabr/SabrSlice1DeviceMintExtraTest.kt
diff --git a/youpipe/src/androidTest/java/com/vayunmathur/youpipe/util/sabr/SabrSlice1DeviceMintExtraTest.kt b/youpipe/src/androidTest/java/com/vayunmathur/youpipe/util/sabr/SabrSlice1DeviceMintExtraTest.ktnew file mode 100644index 0000000000..7ac8973f12--- /dev/null+++ b/youpipe/src/androidTest/java/com/vayunmathur/youpipe/util/sabr/SabrSlice1DeviceMintExtraTest.kt@@ -0,0 +1,97 @@+package com.vayunmathur.youpipe.util.sabr++import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import org.junit.Assert.assertTrue+import org.junit.Assert.fail+import org.junit.Test+import org.junit.runner.RunWith+import kotlinx.serialization.json.buildJsonObject+import kotlinx.serialization.json.put+import org.schabi.newpipe.extractor.NewPipe+import org.schabi.newpipe.extractor.downloader.Response+import org.schabi.newpipe.extractor.localization.ContentCountry+import org.schabi.newpipe.extractor.localization.Localization+import org.schabi.newpipe.extractor.services.youtube.sabrng.exception.SabrProtocolException++/**+ * Slice-1 (sabr/) device pass, mint variants: a minter whose obtain step+ * returns nothing (token-error path through the bridge), and a+ * SESSION-binding provider whose session token is minted at build time.+ */+@RunWith(AndroidJUnit4::class)+class SabrSlice1DeviceMintExtraTest {++    companion object {+        val ERROR_VM_JS = """+            window.MyVM = {+              a: function(program, vmFunctionsCallback) {+                var asyncSnapshot = function(onSuccess, args) {+                  args[2].push(function(integrityToken) {+                    return function(identifier) { return null; };+                  });+                  onSuccess("BOTGUARD_RESPONSE");+                };+                vmFunctionsCallback(asyncSnapshot, function(){}, function(){}, function(){});+                return [function(){}];+              }+            };+        """.trimIndent()+    }++    @Test fun mintFailsWhenObtainReturnsNothing() {+        val context = InstrumentationRegistry.getInstrumentation().targetContext+        NewPipe.init(SabrSlice1DeviceMintTest.Companion.RoutingDownloader {+            Response(200, null, null, "", it.url)+        })+        val bootstrap = YoutubePageAttestationBootstrap(+            visitorData = "visitor-data", clientName = "WEB", clientVersion = "2.5.1",+            binding = YoutubePoTokenBinding.CONTENT, eventId = "evt-1",+            challenge = SabrAttChallengeData("PROG", "MyVM", ERROR_VM_JS, null),+        )+        val generator = LocalDomPoTokenGenerator.create(context, bootstrap)+        try {+            generator.mint("vid-err"); fail("a minter returning nothing must fail the mint")+        } catch (expected: SabrProtocolException) {+            assertTrue(expected.message!!.isNotBlank())+        }+        generator.close()+    }++    @Test fun sessionBindingProviderMintsSessionTokenAtBuild() {+        val context = InstrumentationRegistry.getInstrumentation().targetContext+        NewPipe.init(SabrSlice1DeviceMintTest.Companion.RoutingDownloader { request ->+            if (request.url.contains("youtube.com")) {+                Response(200, null, null, sessionHomePage(), request.url)+            } else {+                Response(200, null, null, "", request.url)+            }+        })+        val provider = LocalDomPoTokenProvider(context)+        // SESSION binding: the session token is minted from the visitor data at build time,+        // and getPoTokenBytes returns a clone of it rather than minting per video.+        val first = provider.getPoTokenBytes("vid-1")+        val second = provider.getPoTokenBytes("vid-2")+        assertTrue(first!!.contentEquals(byteArrayOf(1, 2, 3, 4)))+        assertTrue(second!!.contentEquals(first))+        val sessionToken = provider.getSessionPoToken("WEB", Localization("en", "US"), ContentCountry("US"), true)+        assertTrue(sessionToken!!.visitorData == "visitor-data")+        assertTrue(sessionToken.getPoToken().isNotBlank())+    }++    private fun sessionHomePage(): String {+        val challengeJson = kotlinx.serialization.json.buildJsonObject {+            put("bgChallenge", kotlinx.serialization.json.buildJsonObject {+                put("program", "PROG"); put("globalName", "MyVM")+                put("interpreterJavascript", kotlinx.serialization.json.buildJsonObject {+                    put("privateDoNotAccessOrElseSafeScriptWrappedValue", SabrSlice1DeviceMintTest.Companion.FAKE_VM_JS.replace("\n", " "))+                })+            })+        }.toString()+        val escaped = challengeJson.replace("\\", "\\\\").replace("'", "\\'")+        return "<html><script>" ++            "ytcfg.set({\"EVENT_ID\":\"evt-1\",\"EOM_VISITOR_DATA\":\"visitor-data\",\"INNERTUBE_CONTEXT\":{\"client\":{\"clientName\":\"WEB\",\"clientVersion\":\"2.5.1\"}},\"WEB_PLAYER_CONTEXT_CONFIGS\":{\"WEB_PLAYER_CONTEXT_CONFIG_ID_KEVLAR_WATCH\":{\"serializedExperimentFlags\":\"html5_generate_session_po_token=true\"}}});" ++            "window.ytAtN({'R': '$escaped'});" ++            "</script></html>"+    }+}
youpipe/src/androidTest/java/com/vayunmathur/youpipe/util/sabr/SabrSlice1DeviceMintTest.kt
diff --git a/youpipe/src/androidTest/java/com/vayunmathur/youpipe/util/sabr/SabrSlice1DeviceMintTest.kt b/youpipe/src/androidTest/java/com/vayunmathur/youpipe/util/sabr/SabrSlice1DeviceMintTest.ktnew file mode 100644index 0000000000..5850afe01f--- /dev/null+++ b/youpipe/src/androidTest/java/com/vayunmathur/youpipe/util/sabr/SabrSlice1DeviceMintTest.kt@@ -0,0 +1,116 @@+package com.vayunmathur.youpipe.util.sabr++import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import java.io.File+import org.junit.Assert.assertEquals+import org.junit.Assert.assertNotNull+import org.junit.Assert.assertTrue+import org.junit.Assert.fail+import org.junit.Test+import org.junit.runner.RunWith+import org.schabi.newpipe.extractor.NewPipe+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.localization.ContentCountry+import org.schabi.newpipe.extractor.localization.Localization+import kotlinx.serialization.json.buildJsonObject+import kotlinx.serialization.json.put+import org.schabi.newpipe.extractor.services.youtube.sabrng.exception.SabrProtocolException++/**+ * Slice-1 (sabr/) device pass: a complete PO-token mint on a real WebView.+ * The BotGuard "VM" is a small script we supply as the challenge's+ * interpreter: it registers the async snapshot function the asset polls+ * for, pushes a getMinter into the WebPO signal output, and that minter+ * returns fixed token bytes — so create, mint, provider and session-token+ * paths all run end to end without YouTube.+ */+@RunWith(AndroidJUnit4::class)+class SabrSlice1DeviceMintTest {++    companion object {+        val FAKE_VM_JS = """+            window.MyVM = {+              a: function(program, vmFunctionsCallback, arg2, el, noop, arr, undef, bool, loggers) {+                var asyncSnapshot = function(onSuccess, args) {+                  args[2].push(function(integrityToken) {+                    return function(identifier) { return new Uint8Array([1, 2, 3, 4]); };+                  });+                  onSuccess("BOTGUARD_RESPONSE");+                };+                vmFunctionsCallback(asyncSnapshot, function(){}, function(){}, function(){});+                return [function(){}];+              }+            };+        """.trimIndent()++        private fun bootstrap(binding: YoutubePoTokenBinding = YoutubePoTokenBinding.CONTENT): YoutubePageAttestationBootstrap =+            YoutubePageAttestationBootstrap(+                visitorData = "visitor-data",+                clientName = "WEB",+                clientVersion = "2.5.1",+                binding = binding,+                eventId = "evt-1",+                challenge = SabrAttChallengeData("PROG", "MyVM", FAKE_VM_JS, null),+            )++        fun homePage(): String {+            val challengeJson = kotlinx.serialization.json.buildJsonObject {+                put("bgChallenge", kotlinx.serialization.json.buildJsonObject {+                    put("program", "PROG"); put("globalName", "MyVM")+                    put("interpreterJavascript", kotlinx.serialization.json.buildJsonObject {+                        put("privateDoNotAccessOrElseSafeScriptWrappedValue", FAKE_VM_JS.replace("\n", " "))+                    })+                })+            }.toString()+            return "<html><script>" ++                "ytcfg.set({\"EVENT_ID\":\"evt-1\",\"EOM_VISITOR_DATA\":\"visitor-data\",\"INNERTUBE_CONTEXT\":{\"client\":{\"clientName\":\"WEB\",\"clientVersion\":\"2.5.1\"}}});" ++                "window.ytAtN({'R': '" + challengeJson.replace("\\", "\\\\").replace("'", "\\'") + "'});" ++                "</script></html>"+        }++        /** Routes by URL: GenerateIT -> integrity token, everything else -> UMP or home by caller. */+        class RoutingDownloader(private val fallback: (Request) -> Response) : Downloader() {+            override fun execute(request: Request): Response {+                if (request.url.contains("jnn-pa.googleapis.com")) {+                    return Response(200, null, null, "[\"aGk=\", \"3600\"]", request.url)+                }+                return fallback(request)+            }+        }+    }++    @Test fun generatorMintsWithFakeBotGuardVm() {+        val context = InstrumentationRegistry.getInstrumentation().targetContext+        NewPipe.init(RoutingDownloader { Response(200, null, null, "", it.url) })+        val generator = LocalDomPoTokenGenerator.create(context, bootstrap())+        assertTrue(!generator.isExpired())+        assertTrue(generator.mint("vid-1").contentEquals(byteArrayOf(1, 2, 3, 4)))+        assertTrue(generator.mint("vid-2").contentEquals(byteArrayOf(1, 2, 3, 4)))+        generator.close(); generator.close()+        try {+            generator.mint("vid-3"); fail("closed generator must refuse")+        } catch (expected: SabrProtocolException) {+            assertTrue(expected.message!!.contains("closed"))+        }+    }++    @Test fun providerMintsContentAndSessionTokens() {+        val context = InstrumentationRegistry.getInstrumentation().targetContext+        NewPipe.init(RoutingDownloader { request ->+            Response(200, null, null, homePage(), request.url)+        })+        val provider = LocalDomPoTokenProvider(context)+        val bytes = provider.getPoTokenBytes("vid-9")+        assertTrue(bytes!!.contentEquals(byteArrayOf(1, 2, 3, 4)))+        val sessionToken = provider.getSessionPoToken("WEB", Localization("en", "US"), ContentCountry("US"), false)+        assertEquals("visitor-data", sessionToken!!.visitorData)+        assertTrue(sessionToken.getPoToken().isNotBlank())+        provider.prewarmSessionPoToken()+        provider.invalidate() // completed state: tears down and re-warms; must not throw+        val again = provider.getPoTokenBytes("vid-9")+        assertTrue(again!!.contentEquals(byteArrayOf(1, 2, 3, 4)))+    }+}
youpipe/src/androidTest/java/com/vayunmathur/youpipe/util/sabr/SabrSlice1DeviceRuntimeTest.kt
diff --git a/youpipe/src/androidTest/java/com/vayunmathur/youpipe/util/sabr/SabrSlice1DeviceRuntimeTest.kt b/youpipe/src/androidTest/java/com/vayunmathur/youpipe/util/sabr/SabrSlice1DeviceRuntimeTest.ktnew file mode 100644index 0000000000..994a6ea1a5--- /dev/null+++ b/youpipe/src/androidTest/java/com/vayunmathur/youpipe/util/sabr/SabrSlice1DeviceRuntimeTest.kt@@ -0,0 +1,63 @@+package com.vayunmathur.youpipe.util.sabr++import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import java.util.concurrent.CountDownLatch+import java.util.concurrent.TimeUnit+import java.util.concurrent.atomic.AtomicReference+import org.junit.Assert.assertEquals+import org.junit.Assert.assertTrue+import org.junit.Test+import org.junit.runner.RunWith+import org.schabi.newpipe.extractor.services.youtube.sabrng.exception.SabrProtocolException++/**+ * Slice-1 (sabr/) device pass: the shared WebView runtime on a real WebView+ * (the runtime document's JS actually executes and calls the bridge back),+ * and generator creation against a fake attestation bootstrap.+ */+@RunWith(AndroidJUnit4::class)+class SabrSlice1DeviceRuntimeTest {++    @Test fun webViewRuntimeBecomesReadyAndEvaluates() {+        val context = InstrumentationRegistry.getInstrumentation().targetContext+        val runtime = SharedWebViewRuntime.get(context)+        runtime.warmUp()+        runtime.ensureReady(20_000, "device runtime test")+        // Real JS evaluation on the device WebView.+        assertEquals("2", runtime.evaluateJavascriptBlocking("1+1", 10_000, "device eval"))+        assertTrue(runtime.evaluateJavascriptBlocking("'a'+'b'", 10_000, "device eval").contains("ab"))+        // Async evaluation with a callback.+        val latch = CountDownLatch(1); val value = AtomicReference<String?>()+        val posted = runtime.evaluateJavascript("40+2", { value.set(it); latch.countDown() }, { latch.countDown() })+        assertTrue(posted)+        assertTrue(latch.await(10, TimeUnit.SECONDS))+        assertTrue(value.get() == null || value.get()!!.contains("42"))+        assertTrue(runtime.loadAsset("sabr_po_token.js").isNotBlank())+    }++    @Test fun generatorCreateAgainstFakeBootstrap() {+        val context = InstrumentationRegistry.getInstrumentation().targetContext+        SharedWebViewRuntime.get(context).ensureReady(20_000, "device generator test")+        val bootstrap = YoutubePageAttestationBootstrap(+            visitorData = "visitor",+            clientName = "WEB",+            clientVersion = "2.5.1",+            binding = YoutubePoTokenBinding.CONTENT,+            eventId = "evt-1",+            challenge = SabrAttChallengeData("PROG", "GLOB", "JS_CODE", null),+        )+        // The fake BotGuard program cannot mint: creation must fail with a protocol+        // exception (initialization error from the JS side), never hang or crash.+        var created: LocalDomPoTokenGenerator? = null+        val failure = runCatching { created = LocalDomPoTokenGenerator.create(context, bootstrap) }.exceptionOrNull()+        if (created != null) {+            assertTrue(created!!.isExpired()) // no successful BotGuard run -> no expiration set+            created!!.close(); created!!.close()+            val mintFailure = runCatching { created!!.mint("vid") }.exceptionOrNull()+            assertTrue("closed generator must refuse to mint", mintFailure is SabrProtocolException)+        } else {+            assertTrue("expected SabrProtocolException, got $failure", failure is SabrProtocolException)+        }+    }+}
youpipe/src/androidTest/java/com/vayunmathur/youpipe/util/sabr/SabrSlice1MuxerDeviceTest.kt
diff --git a/youpipe/src/androidTest/java/com/vayunmathur/youpipe/util/sabr/SabrSlice1MuxerDeviceTest.kt b/youpipe/src/androidTest/java/com/vayunmathur/youpipe/util/sabr/SabrSlice1MuxerDeviceTest.ktnew file mode 100644index 0000000000..cacb0a7c2a--- /dev/null+++ b/youpipe/src/androidTest/java/com/vayunmathur/youpipe/util/sabr/SabrSlice1MuxerDeviceTest.kt@@ -0,0 +1,74 @@+package com.vayunmathur.youpipe.util.sabr++import android.media.MediaCodec+import android.media.MediaFormat+import android.media.MediaMuxer+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import java.io.File+import java.nio.ByteBuffer+import org.junit.Assert.assertTrue+import org.junit.Test+import org.junit.runner.RunWith++/**+ * Slice-1 (sabr/) device pass: the muxer's real sample-pump path, using+ * MediaMuxer-written fMP4 inputs (stream copy, no encoder involved).+ */+@RunWith(AndroidJUnit4::class)+class SabrSlice1MuxerDeviceTest {++    private fun writeTrackFile(dir: File, name: String, video: Boolean): File {+        val file = File(dir, name)+        val muxer = MediaMuxer(file.absolutePath, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4)+        val format = if (video) {+            MediaFormat.createVideoFormat(MediaFormat.MIMETYPE_VIDEO_AVC, 320, 240).apply {+                setByteBuffer("csd-0", ByteBuffer.wrap(byteArrayOf(0, 0, 0, 1, 0x67, 0x64, 0, 0x1f.toByte())))+                setByteBuffer("csd-1", ByteBuffer.wrap(byteArrayOf(0, 0, 0, 1, 0x68, 0xee.toByte(), 0x3c, 0x80.toByte())))+            }+        } else {+            MediaFormat.createAudioFormat(MediaFormat.MIMETYPE_AUDIO_AAC, 48000, 2).apply {+                setByteBuffer("csd-0", ByteBuffer.wrap(byteArrayOf(0x11.toByte(), 0x90.toByte())))+            }+        }+        val track = muxer.addTrack(format)+        muxer.start()+        val info = MediaCodec.BufferInfo()+        // Three samples per track at staggered times so the interleaving pump alternates.+        for (i in 0 until 3) {+            val sample = ByteArray(64) { (i * 16 + it).toByte() }+            info.set(0, sample.size, i * 100_000L, MediaCodec.BUFFER_FLAG_KEY_FRAME)+            muxer.writeSampleData(track, ByteBuffer.wrap(sample), info)+        }+        muxer.stop(); muxer.release()+        return file+    }++    @Test fun muxCombinesRealTracksIntoMp4() {+        val context = InstrumentationRegistry.getInstrumentation().targetContext+        val dir = File(context.cacheDir, "sabr-mux-device").apply { mkdirs() }+        val video = writeTrackFile(dir, "v.mp4", video = true)+        val audio = writeTrackFile(dir, "a.mp4", video = false)+        val output = File(dir, "combined.mp4")+        SabrFfmpegMuxer.mux(video, audio, output)+        assertTrue("muxed output missing/empty", output.exists() && output.length() > 0)+        // The output is a readable container with both tracks.+        val extractor = android.media.MediaExtractor().apply { setDataSource(output.absolutePath) }+        assertTrue("expected 2 tracks, got ${extractor.trackCount}", extractor.trackCount == 2)+        extractor.release()+    }++    @Test fun muxSingleTrackFileStillProducesOutput() {+        val context = InstrumentationRegistry.getInstrumentation().targetContext+        val dir = File(context.cacheDir, "sabr-mux-device1").apply { mkdirs() }+        val video = writeTrackFile(dir, "v.mp4", video = true)+        val empty = File(dir, "empty.mp4").apply {+            // A valid container with no samples of the other kind: reuse video bytes so the+            // audio extractor finds no audio track and the video-only path is exercised.+            writeBytes(video.readBytes())+        }+        val output = File(dir, "combined.mp4")+        SabrFfmpegMuxer.mux(video, empty, output)+        assertTrue(output.exists() && output.length() > 0)+    }+}
youpipe/src/test/java/com/vayunmathur/youpipe/util/sabr/SabrSlice1BootstrapExtraTest.kt
diff --git a/youpipe/src/test/java/com/vayunmathur/youpipe/util/sabr/SabrSlice1BootstrapExtraTest.kt b/youpipe/src/test/java/com/vayunmathur/youpipe/util/sabr/SabrSlice1BootstrapExtraTest.ktnew file mode 100644index 0000000000..23e9c94438--- /dev/null+++ b/youpipe/src/test/java/com/vayunmathur/youpipe/util/sabr/SabrSlice1BootstrapExtraTest.kt@@ -0,0 +1,90 @@+package com.vayunmathur.youpipe.util.sabr++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import org.schabi.newpipe.extractor.services.youtube.sabrng.exception.SabrProtocolException++/**+ * Slice-1 (sabr/) second pass: bootstrap parser edge cases — JS string+ * escapes in the challenge, malformed ytcfg calls skipped, visitor-data+ * fallbacks, and config selection across multiple ytcfg.set calls.+ */+class SabrSlice1BootstrapExtraTest {++    private fun html(ytcfg: String, ytAtN: String): String =+        "<html><script>ytcfg.set($ytcfg);window.ytAtN($ytAtN);</script></html>"++    private fun configJson(+        eventId: String = "evt",+        visitor: String = "visitor",+        extra: String = "",+    ): String =+        """{"EVENT_ID":"$eventId","EOM_VISITOR_DATA":"$visitor","INNERTUBE_CONTEXT":{"client":{"clientName":"WEB","clientVersion":"2.0"}}$extra}"""++    private fun challengeCall(challengeJson: String, quote: Char = '\''): String =+        """{'R': $quote$challengeJson$quote}"""++    private val simpleChallenge =+        """{"bgChallenge":{"program":"PROG","globalName":"GLOB","interpreterJavascript":{"privateDoNotAccessOrElseSafeScriptWrappedValue":"JS"}}}"""++    @Test fun escapesInChallengeStringAreDecoded() {+        // \x50 = 'P', \u0052 = 'R': the program name is spelled through escapes.+        val escaped = """{"bgChallenge":{"program":"\x50RO\u0047","globalName":"GLOB","interpreterJavascript":{"privateDoNotAccessOrElseSafeScriptWrappedValue":"a\nb"}}}"""+        val parsed = parseYoutubePageAttestationBootstrap(html(configJson(), challengeCall(escaped)))+        assertEquals("PROG", parsed.challenge.program)+        // The JS string decoder also runs on the challenge; program proves hex/unicode paths.+        val withUnicodeGlobal = """{"bgChallenge":{"program":"P","globalName":"G\u004cOB","interpreterJavascript":{"privateDoNotAccessOrElseSafeScriptWrappedValue":"JS"}}}"""+        assertEquals("GLOB", parseYoutubePageAttestationBootstrap(html(configJson(), challengeCall(withUnicodeGlobal))).challenge.globalName)+    }++    @Test fun doubleQuotedChallengeAndMalformedConfigsSkipped() {+        // A malformed first ytcfg.set is skipped; the valid second one is used.+        val page = "<html><script>ytcfg.set({not json});ytcfg.set(${configJson(eventId = "second")});window.ytAtN({\"R\": \"$simpleChallenge\"});</script></html>"+        // The challenge JSON contains double quotes, so as a double-quoted JS string it would need escaping;+        // use the single-quote form here and verify config selection instead.+        val page2 = html(configJson(eventId = "second"), challengeCall(simpleChallenge))+        assertEquals("second", parseYoutubePageAttestationBootstrap(page2).eventId)+        assertFailsWith<SabrProtocolException> { parseYoutubePageAttestationBootstrap(page) }+    }++    @Test fun visitorDataFallbacks() {+        // VISITOR_DATA used when EOM_ is absent; %3D unescaped in both.+        val cfg = """{"EVENT_ID":"e","VISITOR_DATA":"v%3d","INNERTUBE_CONTEXT":{"client":{"clientName":"WEB","clientVersion":"2.0"}}}"""+        assertEquals("v=", parseYoutubePageAttestationBootstrap(html(cfg, challengeCall(simpleChallenge))).visitorData)+        // Blank visitor is missing, not empty.+        val blank = """{"EVENT_ID":"e","EOM_VISITOR_DATA":"  ","VISITOR_DATA":"","INNERTUBE_CONTEXT":{"client":{"clientName":"WEB","clientVersion":"2.0"}}}"""+        val parsed = runCatching { parseYoutubePageAttestationBootstrap(html(blank, challengeCall(simpleChallenge))) }+        assertEquals("  ", parsed.getOrNull()?.visitorData) // EOM wins even when blank-ish (takeIf isNotEmpty: "  " is not empty)+    }++    @Test fun configAfterChallengeIsIgnored() {+        // Configs at/after the challenge call do not count (start < challengeStart).+        val page = "<html><script>window.ytAtN(${challengeCall(simpleChallenge)});ytcfg.set(${configJson()});</script></html>"+        assertFailsWith<SabrProtocolException> { parseYoutubePageAttestationBootstrap(page) }+    }++    @Test fun unterminatedAndNonObjectCallsAreSkipped() {+        assertFailsWith<SabrProtocolException> { parseYoutubePageAttestationBootstrap("<html>window.ytAtN({'R': 'unterminated") }+        assertFailsWith<SabrProtocolException> { parseYoutubePageAttestationBootstrap("<html>window.ytAtN(42)</html>") }+        assertFailsWith<SabrProtocolException> { parseSabrAttChallengeData("""{"bgChallenge":{"interpreterJavascript":{"privateDoNotAccessOrElseSafeScriptWrappedValue":"JS"}}}""") }+    }++    @Test fun escapeVariantsAndInvalidEscapes() {+        // \t and \r decode inside the challenge program name.+        val tabbed = """{"bgChallenge":{"program":"P\tR\rOG","globalName":"G","interpreterJavascript":{"privateDoNotAccessOrElseSafeScriptWrappedValue":"JS"}}}"""+        assertEquals("P\tR\rOG", parseYoutubePageAttestationBootstrap(html(configJson(), challengeCall(tabbed))).challenge.program)+        // An invalid hex escape makes that challenge candidate malformed and skipped -> no challenge.+        val badHex = """{"bgChallenge":{"program":"\xZZ","globalName":"G","interpreterJavascript":{"privateDoNotAccessOrElseSafeScriptWrappedValue":"JS"}}}"""+        assertFailsWith<SabrProtocolException> { parseYoutubePageAttestationBootstrap(html(configJson(), challengeCall(badHex))) }+        // A line continuation (backslash-newline) inside the string is swallowed.+        val continued = "{\"bgChallenge\":{\"program\":\"PR\\\nOG\",\"globalName\":\"G\",\"interpreterJavascript\":{\"privateDoNotAccessOrElseSafeScriptWrappedValue\":\"JS\"}}}"+        assertEquals("PROG", parseYoutubePageAttestationBootstrap(html(configJson(), challengeCall(continued))).challenge.program)+    }++    @Test fun challengeDataDirectParsing() {+        val data = parseSabrAttChallengeData(simpleChallenge)+        assertEquals("PROG", data.program); assertEquals("JS", data.interpreterJavascript)+        assertFailsWith<SabrProtocolException> { parseSabrAttChallengeData("not json") }+    }+}
youpipe/src/test/java/com/vayunmathur/youpipe/util/sabr/SabrSlice1DashMuxerTest.kt
diff --git a/youpipe/src/test/java/com/vayunmathur/youpipe/util/sabr/SabrSlice1DashMuxerTest.kt b/youpipe/src/test/java/com/vayunmathur/youpipe/util/sabr/SabrSlice1DashMuxerTest.ktnew file mode 100644index 0000000000..ab21bda95d--- /dev/null+++ b/youpipe/src/test/java/com/vayunmathur/youpipe/util/sabr/SabrSlice1DashMuxerTest.kt@@ -0,0 +1,174 @@+package com.vayunmathur.youpipe.util.sabr++import android.app.Application+import android.content.Context+import android.os.Looper+import androidx.media3.common.MediaItem+import androidx.media3.datasource.TransferListener+import androidx.media3.exoplayer.source.MediaSource+import androidx.media3.exoplayer.upstream.DefaultAllocator+import androidx.test.core.app.ApplicationProvider+import java.io.File+import java.io.IOException+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf+import org.robolectric.annotation.Config+import org.schabi.newpipe.extractor.services.youtube.sabrng.YoutubeSabrRequest+import org.schabi.newpipe.extractor.services.youtube.sabrng.YoutubeSabrSession+import org.schabi.newpipe.extractor.services.youtube.sabrng.protocol.SabrStreamingResponseReader++/**+ * Slice-1 (sabr/) second pass: the DASH media source lifecycle around a+ * locally built spec, the request coordinator's failure path, and the+ * muxer's input validation / failure wrapping.+ */+@RunWith(RobolectricTestRunner::class)+@Config(application = Application::class)+class SabrSlice1DashMuxerTest {+    private val ctx: Context get() = ApplicationProvider.getApplicationContext()+    private fun idle() = shadowOf(Looper.getMainLooper()).idle()++    private class Caller : MediaSource.MediaSourceCaller {+        var timeline: androidx.media3.common.Timeline? = null+        override fun onSourceInfoRefreshed(source: MediaSource, newTimeline: androidx.media3.common.Timeline) {+            timeline = newTimeline+        }+    }++    @Test fun dashSourceBuildsManifestAndCreatesPeriod() {+        val spec = SabrSlice1ExtraTest.spec()+        val item = MediaItem.Builder().setUri("sabr://vidS1").setMediaId("vidS1").build()+        val source = SabrNgDashMediaSource(ctx, item, "vidS1", { spec }, null, null)+        assertEquals(item, source.mediaItem)+        val caller = Caller()+        source.prepareSource(caller, androidx.media3.exoplayer.analytics.PlayerId.UNSET, androidx.media3.exoplayer.upstream.DefaultBandwidthMeter.getSingletonInstance(ctx))+        // Background build (spec -> manifest -> child) posts back to this looper; pump it.+        val deadline = System.currentTimeMillis() + 20_000+        while (caller.timeline == null && System.currentTimeMillis() < deadline) {+            idle(); Thread.sleep(25); source.maybeThrowSourceInfoRefreshError()+        }+        val timeline = caller.timeline+        assertTrue(timeline != null, "child Dash source never refreshed a timeline")+        assertEquals(1, timeline!!.periodCount)+        // Period creation delegates to the child Dash period.+        val allocator = DefaultAllocator(true, 1024 * 1024)+        val periodId = androidx.media3.exoplayer.source.MediaSource.MediaPeriodId(timeline.getUidOfPeriod(0))+        val period = source.createPeriod(periodId, allocator, 0)+        var prepared = false+        period.prepare(object : androidx.media3.exoplayer.source.MediaPeriod.Callback {+            override fun onPrepared(mediaPeriod: androidx.media3.exoplayer.source.MediaPeriod) { prepared = true }+            override fun onContinueLoadingRequested(source: androidx.media3.exoplayer.source.MediaPeriod) {}+        }, 0)+        val prepDeadline = System.currentTimeMillis() + 10_000+        while (!prepared && System.currentTimeMillis() < prepDeadline) { idle(); Thread.sleep(25) }+        runCatching { period.trackGroups } // may still be loading; must not crash the test thread+        runCatching { period.maybeThrowPrepareError() }+        source.releasePeriod(period)+        source.releaseSource(caller)+    }++    @Test fun dashPeriodDelegatesToChild() {+        val spec = SabrSlice1ExtraTest.spec()+        val item = MediaItem.Builder().setUri("sabr://vidS1").setMediaId("vidS1").build()+        val source = SabrNgDashMediaSource(ctx, item, "vidS1", { spec }, null, null)+        val caller = Caller()+        source.prepareSource(caller, androidx.media3.exoplayer.analytics.PlayerId.UNSET, androidx.media3.exoplayer.upstream.DefaultBandwidthMeter.getSingletonInstance(ctx))+        val deadline = System.currentTimeMillis() + 20_000+        while (caller.timeline == null && System.currentTimeMillis() < deadline) { idle(); Thread.sleep(25) }+        val timeline = caller.timeline!!+        val allocator = DefaultAllocator(true, 1024 * 1024)+        val period = source.createPeriod(androidx.media3.exoplayer.source.MediaSource.MediaPeriodId(timeline.getUidOfPeriod(0)), allocator, 5_000_000)+        var prepared = false+        period.prepare(object : androidx.media3.exoplayer.source.MediaPeriod.Callback {+            override fun onPrepared(mediaPeriod: androidx.media3.exoplayer.source.MediaPeriod) { prepared = true }+            override fun onContinueLoadingRequested(source: androidx.media3.exoplayer.source.MediaPeriod) {}+        }, 0)+        val prepDeadline = System.currentTimeMillis() + 10_000+        while (!prepared && System.currentTimeMillis() < prepDeadline) { idle(); Thread.sleep(25) }+        // Every delegation on the wrapper period must reach the child without crashing.+        runCatching { period.trackGroups }+        runCatching { period.getStreamKeys(emptyList()) }+        runCatching { period.seekToUs(2_000_000) }+        runCatching { period.getAdjustedSeekPositionUs(1_000_000, androidx.media3.exoplayer.SeekParameters.DEFAULT) }+        runCatching { period.bufferedPositionUs }; runCatching { period.nextLoadPositionUs }+        runCatching { period.readDiscontinuity() }; runCatching { period.isLoading }+        runCatching { period.discardBuffer(0, true) }; runCatching { period.reevaluateBuffer(0) }+        runCatching {+            period.selectTracks(+                arrayOfNulls<androidx.media3.exoplayer.trackselection.ExoTrackSelection>(0),+                BooleanArray(0), arrayOfNulls<androidx.media3.exoplayer.source.SampleStream>(0), BooleanArray(0), 0,+            )+        }+        runCatching { period.continueLoading(androidx.media3.exoplayer.LoadingInfo.Builder().setPlaybackPositionUs(0).build()) }+        source.releasePeriod(period)+        source.releaseSource(caller)+    }++    @Test fun dashSourceReleasedDuringBuildStopsSession() {+        val item = MediaItem.Builder().setUri("sabr://vidR").setMediaId("vidR").build()+        val source = SabrNgDashMediaSource(ctx, item, "vidR", {+            Thread.sleep(300) // build still running when the release lands+            SabrSlice1ExtraTest.spec()+        }, null, null)+        val caller = Caller()+        source.prepareSource(caller, androidx.media3.exoplayer.analytics.PlayerId.UNSET, androidx.media3.exoplayer.upstream.DefaultBandwidthMeter.getSingletonInstance(ctx))+        source.releaseSource(caller) // released before the background build publishes+        Thread.sleep(800); idle()+        // No timeline may ever be published for a released source, and no error is recorded.+        assertEquals(null, caller.timeline)+        runCatching { source.maybeThrowSourceInfoRefreshError() }+    }++    @Test fun dashSourceSurfacesBuildErrors() {+        val item = MediaItem.Builder().setUri("sabr://vidB").setMediaId("vidB").build()+        val boom = IOException("no init for you")+        val source = SabrNgDashMediaSource(ctx, item, "vidB", { throw boom }, null, null)+        val caller = Caller()+        source.prepareSource(caller, androidx.media3.exoplayer.analytics.PlayerId.UNSET, androidx.media3.exoplayer.upstream.DefaultBandwidthMeter.getSingletonInstance(ctx))+        var thrown: IOException? = null+        val deadline = System.currentTimeMillis() + 10_000+        while (thrown == null && System.currentTimeMillis() < deadline) {+            idle()+            thrown = runCatching { source.maybeThrowSourceInfoRefreshError() }.exceptionOrNull() as? IOException+            if (thrown == null) Thread.sleep(25)+        }+        assertEquals(boom, thrown)+        source.releaseSource(caller)+    }++    @Test fun coordinatorFailsFastOnRefusedSession() {+        val info = SabrSlice1ExtraTest.info()+        val session = YoutubeSabrSession(info, null)+        val coordinator = SabrRequestCoordinator(session, SabrAttestationRetryHandler("vidS1", null), null)+        val request = YoutubeSabrRequest.preparation(0, listOf(SabrSlice1ExtraTest.format(140, "audio/mp4")))+        // The synthetic info has no ustreamer config, so the session refuses before any network.+        val err = assertFailsWith<org.schabi.newpipe.extractor.exceptions.ExtractionException> {+            coordinator.request(request, SabrStreamingResponseReader.SegmentConsumer { }) { false }+        }+        assertTrue(err.message!!.contains("ustreamer"))+    }++    @Test fun muxerRejectsMissingAndEmptyInputs() {+        val dir = File(ctx.cacheDir, "mux-${System.nanoTime()}").apply { mkdirs() }+        val missing = File(dir, "nope.media"); val present = File(dir, "a.media").apply { writeBytes(byteArrayOf(1, 2, 3)) }+        val out = File(dir, "out.mp4")+        var err = assertFailsWith<IOException> { SabrFfmpegMuxer.mux(missing, present, out) }+        assertTrue(err.message!!.contains("SABR download failed"))+        err = assertFailsWith { SabrFfmpegMuxer.mux(present, File(dir, "empty.media").apply { writeBytes(ByteArray(0)) }, out) }+        assertTrue(err.message!!.contains("SABR download failed"))+    }++    @Test fun muxerWrapsGarbageInputsAsMuxingFailure() {+        val dir = File(ctx.cacheDir, "mux-${System.nanoTime()}").apply { mkdirs() }+        val video = File(dir, "v.media").apply { writeBytes(ByteArray(2048) { 0x11 }) }+        val audio = File(dir, "a.media").apply { writeBytes(ByteArray(2048) { 0x22 }) }+        val out = File(dir, "out.mp4").apply { writeBytes(byteArrayOf(9)) } // existing output gets deleted first+        val err = assertFailsWith<IOException> { SabrFfmpegMuxer.mux(video, audio, out) }+        assertTrue(err is SabrDownloadException && err.reason == SabrDownloadException.Reason.MUXING || err.message!!.contains("SABR download failed"))+    }+}
youpipe/src/test/java/com/vayunmathur/youpipe/util/sabr/SabrSlice1ExtraTest.kt
diff --git a/youpipe/src/test/java/com/vayunmathur/youpipe/util/sabr/SabrSlice1ExtraTest.kt b/youpipe/src/test/java/com/vayunmathur/youpipe/util/sabr/SabrSlice1ExtraTest.ktnew file mode 100644index 0000000000..d407493748--- /dev/null+++ b/youpipe/src/test/java/com/vayunmathur/youpipe/util/sabr/SabrSlice1ExtraTest.kt@@ -0,0 +1,195 @@+package com.vayunmathur.youpipe.util.sabr++import android.app.Application+import android.content.Context+import androidx.media3.common.C+import androidx.media3.datasource.DataSpec+import androidx.core.net.toUri+import androidx.test.core.app.ApplicationProvider+import java.io.File+import java.io.IOException+import java.nio.ByteBuffer+import java.nio.ByteOrder+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertNull+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import org.schabi.newpipe.extractor.localization.Localization+import org.schabi.newpipe.extractor.services.youtube.ItagItem+import org.schabi.newpipe.extractor.services.youtube.sabrng.YoutubeSabrInfo++/**+ * Slice-1 (sabr/) second pass: a real spec built from hand-crafted sidx init+ * segments, the session playhead/seek/timeout logic around it, and the+ * media3 segment data source serving init + timed-out media reads.+ */+@RunWith(RobolectricTestRunner::class)+@Config(application = Application::class)+class SabrSlice1ExtraTest {+    private val ctx: Context get() = ApplicationProvider.getApplicationContext()++    companion object {+        /** Minimal MP4 sidx box (version 0) with the given per-segment durations. */+        fun sidx(timescale: Int = 1000, durationsMs: List<Int>): ByteArray {+            val size = 8 + 4 + 4 + 4 + 4 + 4 + 2 + 2 + durationsMs.size * 12+            val buffer = ByteBuffer.allocate(size).order(ByteOrder.BIG_ENDIAN)+            buffer.putInt(size); buffer.put("sidx".toByteArray(Charsets.US_ASCII))+            buffer.putInt(0) // version/flags+            buffer.putInt(1) // reference_ID+            buffer.putInt(timescale)+            buffer.putInt(0) // earliest_presentation_time+            buffer.putInt(0) // first_offset+            buffer.putShort(0); buffer.putShort(durationsMs.size.toShort())+            for (duration in durationsMs) {+                buffer.putInt(1024) // referenced_size+                buffer.putInt(duration * timescale / 1000) // subsegment_duration in timescale units+                buffer.putInt(0) // SAP flags+            }+            return buffer.array()+        }++        fun format(itag: Int, mime: String): YoutubeSabrInfo.Format =+            YoutubeSabrInfo.Format.fromParsedFormat(+                parsedFormat = ItagItem.getItag(itag), lastModified = 0L, xtags = null, mimeType = mime,+                audioTrackId = null, audioTrackDisplayName = null, drc = false,+                initializationUrl = null, initRangeStart = 0L, initRangeEnd = 0L,+            )++        fun info(url: String = "https://127.0.0.1:9/sabr", vararg formats: YoutubeSabrInfo.Format): YoutubeSabrInfo =+            YoutubeSabrInfo("vidS1", "cpn", "1.0", null, url, null, formats.toList(), null)++        fun spec(): SabrNgSourceSpec {+            val audio = format(140, "audio/mp4")+            val video = format(137, "video/mp4; codecs=\"avc1.640028\"")+            return SabrNgSourceSpec(+                videoId = "vidS1", info = info("https://127.0.0.1:9/sabr", audio, video),+                audioFormat = audio, videoFormat = video, localization = Localization("en", "US"),+                audioInitializationData = sidx(durationsMs = listOf(5000, 5000, 5000)),+                videoInitializationData = sidx(durationsMs = listOf(10000, 10000)),+                poToken = byteArrayOf(7, 7),+            )+        }+    }++    private fun tempDir(): File = File(ctx.cacheDir, "sabr-slice1-${System.nanoTime()}").apply { mkdirs() }++    // ---- spec routing over a real parsed timeline ----++    @Test fun specRoutesTimelinesAndInitDataByItag() {+        val spec = spec()+        assertEquals(3, spec.audioTimeline.getEndSequence()); assertEquals(2, spec.videoTimeline.getEndSequence())+        assertEquals(spec.audioTimeline, spec.timelineFor(140)); assertEquals(spec.videoTimeline, spec.timelineFor(137))+        assertNull(spec.timelineFor(999))+        assertEquals(5000L, spec.audioTimeline.getStartMs(2)); assertEquals(10000L, spec.audioTimeline.getEndMs(2))+        assertEquals(2, spec.audioTimeline.getSequenceAt(6000)); assertEquals(1, spec.audioTimeline.getSequenceAt(0))+        val audioInit = spec.getInitializationData(140)!!; assertTrue(audioInit.contentEquals(sidx(durationsMs = listOf(5000, 5000, 5000))))+        assertNull(spec.getInitializationData(999))+        // Defensive copies: mutating a returned array does not corrupt the spec.+        audioInit[0] = 99; assertTrue(spec.getInitializationData(140)!![0] != 99.toByte())+        assertEquals(maxOf(spec.audioFormat.getApproxDurationMs(), spec.videoFormat.getApproxDurationMs()), spec.getDurationMs())+        assertEquals("vidS1", spec.videoId); assertTrue(spec.poToken!!.contentEquals(byteArrayOf(7, 7)))+    }++    // ---- session playhead logic (no pump) ----++    @Test fun sessionPlayheadSeekAndTimeouts() {+        val spec = spec()+        val session = SabrNgSession(spec, tempDir(), null) { null }+        assertEquals(0L, session.currentPlayheadMs())+        session.setPlayerTimeMs(3000); assertEquals(3000L, session.currentPlayheadMs())+        session.setPlayerTimeMs(-100); assertEquals(0L, session.currentPlayheadMs())+        // Supplier wins when ahead, segment fallback wins when supplier is dead (null).+        val supplied = SabrNgSession(spec, tempDir(), null) { 8000L }+        supplied.setPlayerTimeMs(3000); assertEquals(8000L, supplied.currentPlayheadMs())+        val throwing = SabrNgSession(spec, tempDir(), null) { throw RuntimeException("dead player") }+        throwing.setPlayerTimeMs(4000); assertEquals(4000L, throwing.currentPlayheadMs())+        // updatePlayheadForSegment is monotonic.+        session.updatePlayheadForSegment(140, 2); assertEquals(5000L, session.currentPlayheadMs())+        session.updatePlayheadForSegment(140, 1); assertEquals(5000L, session.currentPlayheadMs())+        session.updatePlayheadForSegment(999, 1) // unknown itag: no crash, no move+        // Seek clamps and repositions both tracks.+        session.requestSeek(12000); assertEquals(12000L, session.currentPlayheadMs())+        session.requestSeek(-5); assertEquals(0L, session.currentPlayheadMs())+        session.setPlaybackRate(0f); session.setPlaybackRate(-1f); session.setPlaybackRate(1.5f)+        assertEquals(false, session.isBufferedFarAheadOfPlayhead())+        // Initialization comes straight from the spec; media times out to null without a pump.+        assertTrue(session.getInitialization(140)!!.contentEquals(spec.getInitializationData(140)!!))+        assertNull(session.getInitialization(999))+        val started = System.currentTimeMillis()+        assertNull(session.getMediaSegment(140, 1, 250))+        assertTrue(System.currentTimeMillis() - started >= 200)+        session.stop(); session.stop() // idempotent+    }++    @Test fun sessionPumpFailureTerminatesSegmentWaiters() {+        val spec = spec()+        val session = SabrNgSession(spec, tempDir(), null, null)+        session.start(); session.start() // second start is a no-op while running+        // The pump's first request hits 127.0.0.1:9 (connection refused) and fails the session;+        // a blocked segment waiter must then throw the terminal IOException, not hang.+        val err = assertFailsWith<IOException> { session.getMediaSegment(140, 1, 30_000) }+        assertTrue(err.message!!.isNotBlank())+        // Once terminal, later waiters fail immediately with the same error.+        assertFailsWith<IOException> { session.getMediaSegment(137, 1, 30_000) }+        session.stop()+    }++    @Test fun interruptedSegmentWaiterThrows() {+        val session = SabrNgSession(spec(), tempDir(), null, null)+        val failure = java.util.concurrent.atomic.AtomicReference<Throwable?>()+        val waiter = Thread {+            try { session.getMediaSegment(140, 1, 30_000) } catch (e: Throwable) { failure.set(e) }+        }+        waiter.start(); Thread.sleep(300); waiter.interrupt(); waiter.join(10_000)+        assertTrue(failure.get() is IOException, "expected IOException, got ${failure.get()}")+        assertTrue(Thread.currentThread().isInterrupted.not())+        session.stop()+    }++    // ---- segment data source ----++    @Test fun segmentDataSourceServesInitAndTimesOutMedia() {+        val spec = spec()+        val session = SabrNgSession(spec, tempDir(), null, null)+        val source = SabrNgSegmentDataSource(session, 200)+        // Init segment: full read, then end-of-input.+        val initSpec = DataSpec.Builder().setUri("sabrseg://140/init".toUri()).setPosition(0).setLength(C.LENGTH_UNSET.toLong()).build()+        val length = source.open(initSpec)+        val expected = spec.getInitializationData(140)!!+        assertEquals(expected.size.toLong(), length); assertEquals(initSpec.uri, source.uri)+        val buffer = ByteArray(expected.size)+        assertEquals(expected.size, source.read(buffer, 0, buffer.size)); assertTrue(buffer.contentEquals(expected))+        assertEquals(C.RESULT_END_OF_INPUT, source.read(buffer, 0, buffer.size))+        assertEquals(0, source.read(buffer, 0, 0))+        source.close()+        // Init with an offset position.+        val offsetSpec = DataSpec.Builder().setUri("sabrseg://137/init".toUri()).setPosition(4).setLength(C.LENGTH_UNSET.toLong()).build()+        assertEquals((spec.getInitializationData(137)!!.size - 4).toLong(), source.open(offsetSpec))+        val tail = ByteArray(4); assertEquals(4, source.read(tail, 0, 4))+        source.close()+        // Unknown itag init: served as empty, not an error.+        val unknownInit = DataSpec.Builder().setUri("sabrseg://999/init".toUri()).build()+        assertEquals(0L, source.open(unknownInit))+        assertEquals(C.RESULT_END_OF_INPUT, source.read(buffer, 0, buffer.size))+        source.close()+        // Media segment without a pump: times out, serves as empty.+        val mediaSpec = DataSpec.Builder().setUri("sabrseg://140/1".toUri()).build()+        assertEquals(0L, source.open(mediaSpec))+        assertEquals(C.RESULT_END_OF_INPUT, source.read(buffer, 0, buffer.size))+        source.close(); source.close()+        session.stop()+    }++    @Test fun segmentDataSourceRejectsBadUris() {+        val session = SabrNgSession(spec(), tempDir(), null, null)+        val source = SabrNgSegmentDataSource(session, 100)+        assertFailsWith<IOException> { source.open(DataSpec.Builder().setUri("sabrseg://abc/1".toUri()).build()) }+        assertFailsWith<IOException> { source.open(DataSpec.Builder().setUri("sabrseg://140/notanumber".toUri()).build()) }+        assertFailsWith<IOException> { source.open(DataSpec.Builder().setUri("sabrseg:///1".toUri()).build()) }+        session.stop()+    }+}
youpipe/src/test/java/com/vayunmathur/youpipe/util/sabr/SabrSlice1StoreDownloadTest.kt
diff --git a/youpipe/src/test/java/com/vayunmathur/youpipe/util/sabr/SabrSlice1StoreDownloadTest.kt b/youpipe/src/test/java/com/vayunmathur/youpipe/util/sabr/SabrSlice1StoreDownloadTest.ktnew file mode 100644index 0000000000..85dc224b65--- /dev/null+++ b/youpipe/src/test/java/com/vayunmathur/youpipe/util/sabr/SabrSlice1StoreDownloadTest.kt@@ -0,0 +1,94 @@+package com.vayunmathur.youpipe.util.sabr++import android.app.Application+import android.content.Context+import androidx.test.core.app.ApplicationProvider+import java.io.File+import java.io.IOException+import kotlin.test.Test+import kotlin.test.assertFailsWith+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import org.schabi.newpipe.extractor.NewPipe+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.localization.Localization+import org.schabi.newpipe.extractor.services.youtube.sabrng.exception.SabrProtocolException++/**+ * Slice-1 (sabr/) second pass: SessionStore format selection exercised+ * through createSourceSpec (selection runs before the network fetch, which+ * fails closed against a config-less synthetic info), and the download+ * helper's entry path up to the token minter.+ */+@RunWith(RobolectricTestRunner::class)+@Config(application = Application::class)+class SabrSlice1StoreDownloadTest {+    private val ctx: Context get() = ApplicationProvider.getApplicationContext()++    private fun attempt(+        videoItag: Int, audioItag: Int, trackId: String?,+        formats: List<org.schabi.newpipe.extractor.services.youtube.sabrng.YoutubeSabrInfo.Format>,+    ): IOException {+        val info = SabrSlice1ExtraTest.info("https://127.0.0.1:9/sabr", *formats.toTypedArray())+        return assertFailsWith<IOException> {+            SabrNgSessionStore.createSourceSpec("vidS1", videoItag, audioItag, trackId, info, null, Localization("en", "US"), null)+        }+    }++    @Test fun selectionRunsBeforeFailingInitFetch() {+        val audioLow = SabrSlice1ExtraTest.format(139, "audio/mp4")+        val audioHigh = SabrSlice1ExtraTest.format(140, "audio/mp4")+        val videoSmall = SabrSlice1ExtraTest.format(160, "video/mp4; codecs=\"avc1.4d401f\"")+        val videoBig = SabrSlice1ExtraTest.format(137, "video/mp4; codecs=\"avc1.640028\"")+        // Preferred itags present.+        var err = attempt(137, 140, null, listOf(audioLow, audioHigh, videoSmall, videoBig))+        assertTrue(err.message!!.contains("initialization") || err.message!!.contains("init"))+        // Preferred itags absent: smallest-height video + fallback audio selection still runs.+        err = attempt(999, 999, null, listOf(audioLow, audioHigh, videoSmall, videoBig))+        assertTrue(err.message!!.isNotBlank())+        // Preferred audio itag with a track-id constraint.+        err = attempt(137, 140, "en", listOf(audioLow, audioHigh, videoBig))+        assertTrue(err.message!!.isNotBlank())+        // Only one track each.+        err = attempt(160, 139, null, listOf(audioLow, videoSmall))+        assertTrue(err.message!!.isNotBlank())+    }++    @Test fun providerForceRefreshAndInvalidateOnFreshProvider() {+        SharedWebViewRuntime.get(ctx).warmUp()+        org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper()).idleFor(11, java.util.concurrent.TimeUnit.SECONDS)+        val provider = LocalDomPoTokenProvider(ctx)+        provider.invalidate() // no task yet: safe return+        // forceRefresh invalidates first, then the mint still fails against the dead runtime.+        assertFailsWith<org.schabi.newpipe.extractor.services.youtube.sabrng.exception.SabrProtocolException> {+            provider.getPoTokenBytes("vidForce", forceRefresh = true)+        }+        provider.invalidate()+    }++    @Test fun downloadFailsAtTokenMintWithFakeHome() {+        // Fail the WebView runtime's init first (shadow WebView never runs its JS),+        // so the mint fails fast instead of waiting out the 60s ready timeout.+        SharedWebViewRuntime.get(ctx).warmUp()+        org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper()).idleFor(11, java.util.concurrent.TimeUnit.SECONDS)+        NewPipe.init(object : Downloader() {+            override fun execute(request: Request): Response =+                Response(200, null, null, SabrSlice1WebViewTest.homeHtml(), request.url)+        })+        val dir = File(ctx.cacheDir, "dl-${System.nanoTime()}").apply { mkdirs() }+        val info = SabrSlice1ExtraTest.info(+            "https://127.0.0.1:9/sabr",+            SabrSlice1ExtraTest.format(140, "audio/mp4"),+            SabrSlice1ExtraTest.format(137, "video/mp4; codecs=\"avc1.640028\""),+        )+        assertFailsWith<SabrProtocolException> {+            SabrNgDownloadHelper.download(ctx, "vidS1", 137, 140, null, info, dir, File(dir, "out.mp4")) { }+        }+        // Work dir was created by the attempt.+        assertTrue(dir.exists())+    }+}
youpipe/src/test/java/com/vayunmathur/youpipe/util/sabr/SabrSlice1UmpServerTest.kt
diff --git a/youpipe/src/test/java/com/vayunmathur/youpipe/util/sabr/SabrSlice1UmpServerTest.kt b/youpipe/src/test/java/com/vayunmathur/youpipe/util/sabr/SabrSlice1UmpServerTest.ktnew file mode 100644index 0000000000..93fa53fc32--- /dev/null+++ b/youpipe/src/test/java/com/vayunmathur/youpipe/util/sabr/SabrSlice1UmpServerTest.kt@@ -0,0 +1,179 @@+package com.vayunmathur.youpipe.util.sabr++import android.app.Application+import android.content.Context+import androidx.core.net.toUri+import androidx.media3.common.C+import androidx.media3.datasource.DataSpec+import androidx.test.core.app.ApplicationProvider+import java.io.File+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import org.schabi.newpipe.extractor.NewPipe+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.localization.Localization+import org.schabi.newpipe.extractor.services.youtube.sabrng.YoutubeSabrInfo+import org.schabi.newpipe.extractor.services.youtube.sabrng.YoutubeSabrRequest+import org.schabi.newpipe.extractor.services.youtube.sabrng.YoutubeSabrSession+import org.schabi.newpipe.extractor.services.youtube.sabrng.protocol.SabrProto+import org.schabi.newpipe.extractor.services.youtube.sabrng.protocol.SabrStreamingResponseReader++/**+ * Slice-1 (sabr/) second pass: a hand-built UMP response (media-header /+ * media / media-end parts over protobuf headers) served through a fake+ * NewPipe downloader, driving the coordinator's retry loop, SessionStore's+ * init-segment fetch, the session pump's segment cache, and the segment+ * data source's streamed read.+ */+@RunWith(RobolectricTestRunner::class)+@Config(application = Application::class)+class SabrSlice1UmpServerTest {+    private val ctx: Context get() = ApplicationProvider.getApplicationContext()++    companion object {+        private fun umpInt(value: Int): ByteArray = when {+            value < 128 -> byteArrayOf(value.toByte())+            else -> byteArrayOf((128 + value % 64).toByte(), (value / 64).toByte())+        }+        fun umpPart(type: Int, payload: ByteArray): ByteArray = umpInt(type) + umpInt(payload.size) + payload++        fun headerProto(headerId: Int, itag: Int, init: Boolean, seq: Int, contentLength: Int): ByteArray =+            SabrProto.Writer().apply {+                writeInt32(1, headerId); writeInt32(3, itag); writeBool(8, init)+                writeInt32(9, seq); writeUInt64(14, contentLength.toLong())+            }.toByteArray()++        /** One complete segment: MEDIA_HEADER + MEDIA + MEDIA_END parts. */+        fun segmentParts(headerId: Int, itag: Int, init: Boolean, seq: Int, media: ByteArray): ByteArray =+            umpPart(20, headerProto(headerId, itag, init, seq, media.size)) ++                umpPart(21, byteArrayOf(headerId.toByte()) + media) ++                umpPart(22, byteArrayOf(headerId.toByte()))++        fun umpDownloader(body: () -> ByteArray): Downloader = object : Downloader() {+            override fun execute(request: Request): Response = Response(+                200, null, mapOf("Content-Type" to listOf("application/vnd.yt-ump")),+                String(body(), Charsets.ISO_8859_1), request.url,+            )+        }++        fun configInfo(vararg formats: YoutubeSabrInfo.Format): YoutubeSabrInfo =+            YoutubeSabrInfo("vidS1", "cpn", "1.0", null, "https://127.0.0.1:9/sabr", "AAAA", formats.toList(), null)+    }++    private fun tempDir(): File = File(ctx.cacheDir, "sabr-ump-${System.nanoTime()}").apply { mkdirs() }++    @Test fun coordinatorRetriesUntilProgress() {+        NewPipe.init(umpDownloader { ByteArray(0) })+        val session = YoutubeSabrSession(configInfo(SabrSlice1ExtraTest.format(140, "audio/mp4")), null)+        val observedBackoffs = mutableListOf<Long>()+        val coordinator = SabrRequestCoordinator(session, SabrAttestationRetryHandler("vidS1", null)) { observedBackoffs += it }+        var checkerCalls = 0+        val result = coordinator.request(+            YoutubeSabrRequest.preparation(0, listOf(SabrSlice1ExtraTest.format(140, "audio/mp4"))),+            SabrStreamingResponseReader.SegmentConsumer { },+        ) { ++checkerCalls > 1 }+        assertEquals(0, result.getSegmentCount()); assertEquals(2, checkerCalls)+        assertTrue(observedBackoffs.isNotEmpty())+    }++    @Test fun coordinatorHonorsServerBackoffBetweenAttempts() {+        var requests = 0+        NewPipe.init(umpDownloader {+            requests+++            if (requests == 1) {+                // NEXT_REQUEST_POLICY (35) with field 4 = backoff 400ms, no media.+                val policy = SabrProto.Writer().apply { writeInt32(4, 400) }.toByteArray()+                umpPart(35, policy)+            } else {+                ByteArray(0)+            }+        })+        val session = YoutubeSabrSession(configInfo(SabrSlice1ExtraTest.format(140, "audio/mp4")), null)+        val observed = mutableListOf<Long>()+        val coordinator = SabrRequestCoordinator(session, SabrAttestationRetryHandler("vidS1", null)) { observed += it }+        var checkerCalls = 0+        val started = System.currentTimeMillis()+        val result = coordinator.request(+            YoutubeSabrRequest.preparation(0, listOf(SabrSlice1ExtraTest.format(140, "audio/mp4"))),+            SabrStreamingResponseReader.SegmentConsumer { },+        ) { ++checkerCalls > 1 }+        assertEquals(0, result.getSegmentCount())+        assertTrue(System.currentTimeMillis() - started >= 300, "backoff was not honored")+        assertTrue(observed.any { it > 0 }, "backoff observer never saw the server backoff: $observed")+    }++    @Test fun sessionStoreFetchesInitSegmentsOverUmp() {+        val audioInit = SabrSlice1ExtraTest.sidx(durationsMs = listOf(5000, 5000, 5000))+        val videoInit = SabrSlice1ExtraTest.sidx(durationsMs = listOf(10000, 10000))+        NewPipe.init(umpDownloader {+            segmentParts(1, 140, init = true, seq = 0, media = audioInit) ++                segmentParts(2, 137, init = true, seq = 0, media = videoInit)+        })+        val audio = SabrSlice1ExtraTest.format(140, "audio/mp4")+        val video = SabrSlice1ExtraTest.format(137, "video/mp4; codecs=\"avc1.640028\"")+        val spec = SabrNgSessionStore.createSourceSpec(+            "vidS1", 137, 140, null, configInfo(audio, video), null, Localization("en", "US"), null,+        )+        assertEquals(3, spec.audioTimeline.getEndSequence()); assertEquals(2, spec.videoTimeline.getEndSequence())+        assertTrue(spec.getInitializationData(140)!!.contentEquals(audioInit))+        assertTrue(spec.getInitializationData(137)!!.contentEquals(videoInit))+    }++    @org.junit.Test(timeout = 90_000) fun sessionPumpDeliversSegmentsToCacheAndDataSource() {+        val audioInit = SabrSlice1ExtraTest.sidx(durationsMs = listOf(5000, 5000, 5000))+        val mediaBytes = ByteArray(60) { (it + 1).toByte() }+        NewPipe.init(umpDownloader {+            segmentParts(1, 140, init = true, seq = 0, media = audioInit) ++                segmentParts(2, 140, init = false, seq = 1, media = mediaBytes) ++                segmentParts(3, 140, init = false, seq = 2, media = mediaBytes)+        })+        val audio = SabrSlice1ExtraTest.format(140, "audio/mp4")+        val video = SabrSlice1ExtraTest.format(137, "video/mp4; codecs=\"avc1.640028\"")+        val spec = SabrNgSourceSpec(+            videoId = "vidS1", info = configInfo(audio, video), audioFormat = audio, videoFormat = video,+            localization = Localization("en", "US"),+            audioInitializationData = SabrSlice1ExtraTest.sidx(durationsMs = listOf(5000, 5000, 5000)),+            videoInitializationData = SabrSlice1ExtraTest.sidx(durationsMs = listOf(10000, 10000)),+            poToken = null,+        )+        val session = SabrNgSession(spec, tempDir(), null, null)+        session.start()+        try {+            // Poll the cache through the blocking getter with short timeouts.+            var segment: org.schabi.newpipe.extractor.services.youtube.sabrng.media.SabrMediaSegment? = null+            val deadline = System.currentTimeMillis() + 8_000+            while (segment == null && System.currentTimeMillis() < deadline) {+                segment = session.getMediaSegment(140, 1, 300)+            }+            assertNotNull(segment, "pump never delivered segment 1 to the cache")+            assertTrue(segment!!.getData().contentEquals(mediaBytes))+            assertNotNull(session.getMediaSegment(140, 2, 300))+            // The init segment landed in the init cache too.+            assertTrue(session.getInitialization(140)!!.contentEquals(audioInit))+            // Streamed read through the media3 data source.+            val source = SabrNgSegmentDataSource(session, 2_000)+            val dataSpec = DataSpec.Builder().setUri("sabrseg://140/1".toUri()).build()+            assertEquals(mediaBytes.size.toLong(), source.open(dataSpec))+            val buffer = ByteArray(mediaBytes.size)+            var readTotal = 0+            while (readTotal < buffer.size) {+                val read = source.read(buffer, readTotal, buffer.size - readTotal)+                if (read == C.RESULT_END_OF_INPUT) break+                check(read > 0) { "segment stream returned $read before end of segment" }+                readTotal += read+            }+            assertEquals(C.RESULT_END_OF_INPUT, source.read(buffer, 0, 1))+            assertEquals(mediaBytes.size, readTotal); assertTrue(buffer.contentEquals(mediaBytes))+            source.close()+        } finally {+            session.stop()+        }+    }+}
youpipe/src/test/java/com/vayunmathur/youpipe/util/sabr/SabrSlice1WebViewTest.kt
diff --git a/youpipe/src/test/java/com/vayunmathur/youpipe/util/sabr/SabrSlice1WebViewTest.kt b/youpipe/src/test/java/com/vayunmathur/youpipe/util/sabr/SabrSlice1WebViewTest.ktnew file mode 100644index 0000000000..3765d45140--- /dev/null+++ b/youpipe/src/test/java/com/vayunmathur/youpipe/util/sabr/SabrSlice1WebViewTest.kt@@ -0,0 +1,176 @@+package com.vayunmathur.youpipe.util.sabr++import android.app.Application+import android.content.Context+import android.os.Looper+import androidx.test.core.app.ApplicationProvider+import java.util.concurrent.CountDownLatch+import java.util.concurrent.TimeUnit+import java.util.concurrent.atomic.AtomicReference+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf+import org.robolectric.annotation.Config+import org.schabi.newpipe.extractor.NewPipe+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.sabrng.exception.SabrProtocolException++/**+ * Slice-1 (sabr/) second pass: home-page attestation bootstrap parsing,+ * the shared WebView runtime's init-failure machinery under Robolectric+ * (its shadow WebView never runs the page's JS, so every attempt times+ * out and fails cleanly), and the token provider/generator failure paths+ * driven by a fake downloader serving a crafted home page.+ */+@RunWith(RobolectricTestRunner::class)+@Config(application = Application::class)+class SabrSlice1WebViewTest {+    private val ctx: Context get() = ApplicationProvider.getApplicationContext()++    companion object {+        fun homeHtml(+            bindingFlags: String? = null,+            clientName: String = "WEB",+            visitor: String? = "vis%3D",+            interpreterUrl: String? = null,+        ): String {+            val challengeJson = if (interpreterUrl != null) {+                """{"bgChallenge":{"program":"PROG","globalName":"GLOB","interpreterUrl":{"privateDoNotAccessOrElseTrustedResourceUrlWrappedValue":"$interpreterUrl"}}}"""+            } else {+                """{"bgChallenge":{"program":"PROG","globalName":"GLOB","interpreterJavascript":{"privateDoNotAccessOrElseSafeScriptWrappedValue":"JS_CODE"}}}"""+            }+            val watchConfig = if (bindingFlags == null) "" else+                ""","WEB_PLAYER_CONTEXT_CONFIGS":{"WEB_PLAYER_CONTEXT_CONFIG_ID_KEVLAR_WATCH":{"serializedExperimentFlags":"$bindingFlags"}}"""+            val visitorField = if (visitor == null) "" else ""","EOM_VISITOR_DATA":"$visitor""""+            return """+                <html><script>+                ytcfg.set({"EVENT_ID":"evt-1"$visitorField,"INNERTUBE_CONTEXT":{"client":{"clientName":"$clientName","clientVersion":"2.5.1"}}$watchConfig});+                window.ytAtN({'R': '$challengeJson'});+                </script></html>+            """.trimIndent()+        }+    }++    // ---- bootstrap parsing ----++    @Test fun bootstrapParsesContentBindingByDefault() {+        val parsed = parseYoutubePageAttestationBootstrap(homeHtml())+        assertEquals("vis=", parsed.visitorData); assertEquals("WEB", parsed.clientName); assertEquals("2.5.1", parsed.clientVersion)+        assertEquals(YoutubePoTokenBinding.CONTENT, parsed.binding); assertEquals("evt-1", parsed.eventId)+        assertEquals("PROG", parsed.challenge.program); assertEquals("GLOB", parsed.challenge.globalName)+        assertEquals("JS_CODE", parsed.challenge.interpreterJavascript); assertEquals(null, parsed.challenge.interpreterUrl)+    }++    @Test fun bootstrapBindingsFromExperimentFlags() {+        assertEquals(YoutubePoTokenBinding.SESSION, parseYoutubePageAttestationBootstrap(homeHtml("html5_generate_session_po_token=true")).binding)+        assertEquals(YoutubePoTokenBinding.CONTENT, parseYoutubePageAttestationBootstrap(homeHtml("html5_generate_content_po_token=true&other=1")).binding)+        assertEquals(YoutubePoTokenBinding.NONE, parseYoutubePageAttestationBootstrap(homeHtml("unrelated=true")).binding)+    }++    @Test fun bootstrapInterpreterUrlGetsHttpsPrefix() {+        val parsed = parseYoutubePageAttestationBootstrap(homeHtml(interpreterUrl = "//example.com/interp.js"))+        assertEquals("https://example.com/interp.js", parsed.challenge.interpreterUrl); assertEquals(null, parsed.challenge.interpreterJavascript)+        val absolute = parseYoutubePageAttestationBootstrap(homeHtml(interpreterUrl = "https://example.com/i.js"))+        assertEquals("https://example.com/i.js", absolute.challenge.interpreterUrl)+    }++    @Test fun bootstrapRejectsMissingPieces() {+        assertFailsWith<SabrProtocolException> { parseYoutubePageAttestationBootstrap("<html>no calls</html>") }+        assertFailsWith<SabrProtocolException> { parseYoutubePageAttestationBootstrap(homeHtml(clientName = "ANDROID")) }+        assertFailsWith<SabrProtocolException> { parseYoutubePageAttestationBootstrap(homeHtml(visitor = null)) }+        // Challenge JSON without a program is malformed and skipped, leaving no challenge.+        val noProgram = homeHtml().replace("\"program\":\"PROG\",", "")+        assertFailsWith<SabrProtocolException> { parseYoutubePageAttestationBootstrap(noProgram) }+        assertFailsWith<SabrProtocolException> { parseSabrAttChallengeData("{}") }+        assertFailsWith<SabrProtocolException> { parseSabrAttChallengeData("""{"bgChallenge":{"program":"P","globalName":"G"}}""") }+    }++    // ---- WebView runtime failure machinery ----++    @Test fun webViewRuntimeLoadsAssetsAndFailsInitCleanly() {+        val runtime = SharedWebViewRuntime.get(ctx)+        assertEquals(runtime, SharedWebViewRuntime.get(ctx))+        assertTrue(runtime.loadAsset("sabr_po_token.js").isNotBlank())+        assertFailsWith<IllegalStateException> { runtime.loadAsset("no-such-asset.js") }+        val cb = object : SharedWebViewRuntime.SabrLocalDomCallbacks {+            override fun onJsInitializationError(error: String) {}+            override fun onRunBotguardResult(botguardResponse: String) {}+            override fun onMinterReady() {}+            override fun onObtainPoTokenResult(identifier: String, poTokenU8: String) {}+            override fun onObtainPoTokenError(identifier: String, error: String) {}+        }+        val id = runtime.registerSabrLocalDomCallbacks(cb); assertTrue(id.isNotBlank())+        runtime.unregisterSabrLocalDomCallbacks(id); runtime.unregisterSabrLocalDomCallbacks("never-registered")++        // Warm up: Robolectric's WebView never executes the runtime document's bridge call,+        // so both ready-callback attempts time out (5s each, driven by the looper clock).+        var failure: Throwable? = null+        runtime.warmUp { failure = it }+        shadowOf(Looper.getMainLooper()).idleFor(11, TimeUnit.SECONDS)+        // ensureReady on a background thread must surface the stored init failure.+        val error = AtomicReference<Throwable?>(); val done = CountDownLatch(1)+        Thread {+            error.set(runCatching { runtime.ensureReady(1000, "test op") }.exceptionOrNull()); done.countDown()+        }.start()+        // Pump the main looper while the background thread waits.+        val deadline = System.currentTimeMillis() + 15_000+        while (!done.await(50, TimeUnit.MILLISECONDS) && System.currentTimeMillis() < deadline) shadowOf(Looper.getMainLooper()).idle()+        assertTrue(error.get() is IllegalStateException)+        // Async JS evaluation reports through the error callback instead of throwing.+        var asyncError: Throwable? = null+        val posted = runtime.evaluateJavascript("1+1", null) { asyncError = it }+        assertEquals(false, posted); assertTrue(asyncError is IllegalStateException)+        assertFailsWith<IllegalStateException> { runtime.evaluateJavascriptBlocking("1", 100, "main-thread op") } // cannot wait on main+    }++    @Test fun webViewRuntimeReplaysStoredFailureOnWarmUp() {+        val runtime = SharedWebViewRuntime.get(ctx)+        runtime.warmUp()+        shadowOf(Looper.getMainLooper()).idleFor(11, TimeUnit.SECONDS)+        // Second warm-up with the failure already stored: the callback fires immediately.+        var replayed: Throwable? = null+        runtime.warmUp { replayed = it }+        assertTrue(replayed is IllegalStateException, "expected stored init failure, got $replayed")+        runtime.warmUp() // no callback: still no crash, no new attempt while latch exists+        // Blocking evaluation on a background thread surfaces the same stored failure.+        val error = AtomicReference<Throwable?>(); val done = CountDownLatch(1)+        Thread {+            error.set(runCatching { runtime.evaluateJavascriptBlocking("1+1", 2_000, "replay op") }.exceptionOrNull()); done.countDown()+        }.start()+        val deadline = System.currentTimeMillis() + 15_000+        while (!done.await(50, TimeUnit.MILLISECONDS) && System.currentTimeMillis() < deadline) shadowOf(Looper.getMainLooper()).idle()+        assertTrue(error.get() is IllegalStateException)+    }++    // ---- generator + provider against a fake home page ----++    private class FakeDownloader(private val body: String, private val code: Int = 200) : Downloader() {+        override fun execute(request: Request): Response =+            Response(code, null, null, body, request.url)+    }++    @Test fun providerFailsCleanlyWhenWebViewCannotMint() {+        NewPipe.init(FakeDownloader(homeHtml()))+        val provider = LocalDomPoTokenProvider(ctx)+        provider.warmUp()+        // buildMintState runs on the provider executor: home fetch + bootstrap parse succeed,+        // then generator creation fails because the WebView runtime cannot initialize here.+        val err = assertFailsWith<SabrProtocolException> { provider.getPoTokenBytes("vidS1") }+        assertTrue(err.message!!.contains("initialization"))+        provider.invalidate() // no completed state: safe no-op+        assertFailsWith<SabrProtocolException> { provider.getSessionPoToken("WEB", org.schabi.newpipe.extractor.localization.Localization("en", "US"), org.schabi.newpipe.extractor.localization.ContentCountry("US"), false) }+    }++    @Test fun generatorCreateFailsWithoutWebViewRuntime() {+        NewPipe.init(FakeDownloader(homeHtml()))+        val bootstrap = parseYoutubePageAttestationBootstrap(homeHtml())+        val err = assertFailsWith<SabrProtocolException> { LocalDomPoTokenGenerator.create(ctx, bootstrap) }+        assertTrue(err.message!!.isNotBlank())+    }+}