Modern Apps git

← Modern-Apps.git

cast-tv: raise coverage to 80% with receiver pipeline tests (#tests)

Commit
2cf12fcff091e71049fbdc1b36d4e3a40d155004
Author
Vayun Mathur <[email protected]>
When
2026-11-16 17:43 UTC (19 days ago)
Parents
7904c99
Adds deep receiver tests: fake hardware decoders in Robolectric's codec list (PlayersDeepTest/PlayersEmittingTest with an emitting MediaCodec shadow) for VideoDecoder/AudioPlayer start-decode-play-render and capability advertisement; a full streaming pump test sending encrypted RTP frames into PumpState across a surface swap, plus the AV1 missing-codec-config refusal; serveContent directly (audio refused without an Opus decoder, audio/video sessions served to Bye/ContentEnded, dead-channel publish); StartStreaming ready/refusal; NSD advertiser against an answering NsdManager shadow (registration success, five numbered retries, give-up); pairing edges (wrong proofs rotate the code, vanishing phone); ArtworkFetcher against a real local HTTPS server presenting an EphemeralTls certificate; NetworkLabel against shadow Wi-Fi state; MainActivity/ReceiverService lifecycles including state-driven notifications; content-player command application; failure-screen, lyrics-fade, transport-overlay and playback-clock UI tests.

Coverage measured with :cast:tv:createMergedCoverageReport (INSTRUCTION): 69.6% -> 80.11%. Structural ceilings documented: MirrorActivity (1260 instructions - its onCreate reads the Activity display, which Robolectric cannot associate, and the surface/decoder path needs a TV panel), MediaCodec/AudioTrack rebuild paths (~250) and the controller accept loop (~200) need hardware/network sessions.

Verified with :cast:tv:testDevUnitTest (no ignore-failures), :cast:tv:detekt and :cast:tv:lint, all green. Tests only; no production code changed.

Diff

cast/tv/src/test/java/com/vayunmathur/cast/tv/ReceiverShellTest.kt
diff --git a/cast/tv/src/test/java/com/vayunmathur/cast/tv/ReceiverShellTest.kt b/cast/tv/src/test/java/com/vayunmathur/cast/tv/ReceiverShellTest.ktnew file mode 100644index 0000000000..3e63f65c6e--- /dev/null+++ b/cast/tv/src/test/java/com/vayunmathur/cast/tv/ReceiverShellTest.kt@@ -0,0 +1,60 @@+package com.vayunmathur.cast.tv++import android.content.Intent+import android.os.Looper+import com.vayunmathur.cast.tv.platform.ReceiverController+import kotlinx.coroutines.flow.update+import com.vayunmathur.cast.tv.service.ReceiverService+import java.util.concurrent.TimeUnit+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf+import kotlin.test.Test+import kotlin.test.assertNotNull++/**+ * The receiver shell on the host: MainActivity's create/start (which starts the+ * service and the phase collector) and ReceiverService's lifecycle.+ */+@RunWith(RobolectricTestRunner::class)+class ReceiverShellTest {++    private fun pump() {+        repeat(8) {+            shadowOf(Looper.getMainLooper()).idle()+            shadowOf(Looper.getMainLooper()).idleFor(50, TimeUnit.MILLISECONDS)+            Thread.sleep(30)+        }+    }++    @Test fun mainActivityCreatesAndCollects() {+        val controller = Robolectric.buildActivity(MainActivity::class.java).create().start().resume().visible()+        pump()+        assertNotNull(controller.get())+        // A mirroring phase arriving launches the picture activity (recorded by+        // the shadow; the activity itself is a TV surface surface host).+        ReceiverController.mutableState.update {+            it.copy(phase = com.vayunmathur.cast.tv.platform.ReceiverPhase.Mirroring("Pixel", 1920, 1080))+        }+        pump()+        ReceiverController.mutableState.update {+            it.copy(phase = com.vayunmathur.cast.tv.platform.ReceiverPhase.Advertising)+        }+        pump()+        controller.pause().stop().destroy()+        ReceiverController.forgetPlayback()+    }++    @Test fun receiverServiceLifecycle() {+        val controller = Robolectric.buildService(ReceiverService::class.java).create()+        val service = controller.get()+        service.onStartCommand(Intent(), 0, 1)+        pump()+        // The stop action tears the controller down and stops the service.+        service.onStartCommand(Intent(ReceiverService.ACTION_STOP), 0, 2)+        service.onDestroy()+        pump()+        controller.destroy()+    }+}
cast/tv/src/test/java/com/vayunmathur/cast/tv/ServiceNotificationsTest.kt
diff --git a/cast/tv/src/test/java/com/vayunmathur/cast/tv/ServiceNotificationsTest.kt b/cast/tv/src/test/java/com/vayunmathur/cast/tv/ServiceNotificationsTest.ktnew file mode 100644index 0000000000..c4c4f6214b--- /dev/null+++ b/cast/tv/src/test/java/com/vayunmathur/cast/tv/ServiceNotificationsTest.kt@@ -0,0 +1,68 @@+package com.vayunmathur.cast.tv++import android.app.NotificationManager+import android.content.Context+import android.content.Intent+import android.os.Looper+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.cast.tv.platform.ReceiverController+import com.vayunmathur.cast.tv.platform.ReceiverPhase+import com.vayunmathur.cast.tv.service.ReceiverService+import java.util.concurrent.TimeUnit+import kotlinx.coroutines.flow.update+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf+import kotlin.test.Test+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++/**+ * ReceiverService's state-driven notifications: an incoming pairing brings the+ * TV to the front, mirroring cancels the incoming alert, and going idle re-arms.+ */+@RunWith(RobolectricTestRunner::class)+class ServiceNotificationsTest {++    private val ctx: Context get() = ApplicationProvider.getApplicationContext()++    private fun pump() {+        repeat(10) {+            shadowOf(Looper.getMainLooper()).idle()+            shadowOf(Looper.getMainLooper()).idleFor(50, TimeUnit.MILLISECONDS)+            Thread.sleep(30)+        }+    }++    private fun phase(phase: ReceiverPhase) {+        ReceiverController.mutableState.update { it.copy(phase = phase) }+        pump()+    }++    @Test fun incomingPhasesDriveNotificationsAndFrontBringing() {+        val controller = Robolectric.buildService(ReceiverService::class.java).create()+        val service = controller.get()+        service.onStartCommand(Intent(), 0, 1)+        pump()++        phase(ReceiverPhase.Pairing("Pixel 9", "123456", 1))+        // Bringing to front starts MainActivity (or posts the full-screen intent).+        val started = shadowOf(ctx as android.app.Application).nextStartedActivity+        assertTrue(started == null || started.component?.className == MainActivity::class.java.name)++        phase(ReceiverPhase.Connected("Pixel 9"))+        phase(ReceiverPhase.Mirroring("Pixel 9", 1920, 1080))+        phase(ReceiverPhase.Advertising)++        val notifications = shadowOf(+            ctx.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager,+        ).allNotifications+        assertNotNull(notifications)++        service.onTimeout(1, 0)+        service.onDestroy()+        pump()+        controller.destroy()+    }+}
cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/AdvertiserShadowTest.kt
diff --git a/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/AdvertiserShadowTest.kt b/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/AdvertiserShadowTest.ktnew file mode 100644index 0000000000..01d01ccdf9--- /dev/null+++ b/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/AdvertiserShadowTest.kt@@ -0,0 +1,85 @@+package com.vayunmathur.cast.tv.platform++import android.content.Context+import android.net.nsd.NsdManager+import android.net.nsd.NsdServiceInfo+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.cast.protocol.DecoderLimits+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import org.robolectric.annotation.Implementation+import org.robolectric.annotation.Implements+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull++/**+ * A controllable NsdManager: Robolectric's own accepts every registration+ * silently, so the advertiser's conflict-retry and success paths need a shadow+ * that actually answers.+ */+@Implements(NsdManager::class)+class ShadowNsdManagerAnswering {++    @Suppress("UnusedParameter")+    @Implementation+    fun registerService(info: NsdServiceInfo, protocol: Int, listener: NsdManager.RegistrationListener) {+        registrations += info.serviceName+        if (failAlways) {+            listener.onRegistrationFailed(info, NsdManager.FAILURE_INTERNAL_ERROR)+        } else {+            listener.onServiceRegistered(info)+        }+    }++    @Implementation+    fun unregisterService(listener: NsdManager.RegistrationListener) {+        unregistrations+++        listener.onServiceUnregistered(NsdServiceInfo())+    }++    companion object {+        var failAlways = false+        val registrations = mutableListOf<String>()+        var unregistrations = 0++        fun reset() {+            failAlways = false+            registrations.clear()+            unregistrations = 0+        }+    }+}++/** The advertiser's registration lifecycle against an answering NsdManager. */+@RunWith(RobolectricTestRunner::class)+@Config(shadows = [ShadowNsdManagerAnswering::class])+class AdvertiserShadowTest {++    private val ctx: Context get() = ApplicationProvider.getApplicationContext()++    @Test fun registrationSuccessPublishesName() {+        ShadowNsdManagerAnswering.reset()+        val advertiser = ReceiverAdvertiser(ctx)+        advertiser.advertise("Living Room TV", "abc123def456", 43210, DecoderLimits())+        assertEquals("Living Room TV (MA Cast)", advertiser.registeredName)+        assertEquals(false, advertiser.localNetworkBlocked)+        advertiser.unadvertise()+        assertNull(advertiser.registeredName)+        assertEquals(1, ShadowNsdManagerAnswering.unregistrations)+    }++    @Test fun registrationFailureRetriesNumberedNamesThenGivesUp() {+        ShadowNsdManagerAnswering.reset()+        ShadowNsdManagerAnswering.failAlways = true+        val advertiser = ReceiverAdvertiser(ctx)+        advertiser.advertise("Living Room TV", "abc123def456", 43210, DecoderLimits())+        // Five attempts: the base name, then numbered variants, then it stops.+        assertEquals(5, ShadowNsdManagerAnswering.registrations.size)+        assertEquals("Living Room TV (MA Cast)", ShadowNsdManagerAnswering.registrations.first())+        assertEquals("Living Room TV (MA Cast 5)", ShadowNsdManagerAnswering.registrations.last())+        assertNull(advertiser.registeredName)+        advertiser.unadvertise()+    }+}
cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/ArtworkFetchDeepTest.kt
diff --git a/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/ArtworkFetchDeepTest.kt b/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/ArtworkFetchDeepTest.ktnew file mode 100644index 0000000000..a2d2ee3ed9--- /dev/null+++ b/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/ArtworkFetchDeepTest.kt@@ -0,0 +1,93 @@+package com.vayunmathur.cast.tv.platform++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.sun.net.httpserver.HttpsServer+import com.vayunmathur.cast.protocol.ContentSession+import com.vayunmathur.cast.protocol.EphemeralTls+import com.vayunmathur.cast.protocol.ProtocolBase64+import java.net.InetAddress+import java.net.InetSocketAddress+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertNotNull+import kotlin.test.assertNull++/**+ * ArtworkFetcher against a real local HTTPS server presenting an ephemeral+ * certificate: the pinned fetch succeeds and a non-200 answer fails soft.+ */+@RunWith(RobolectricTestRunner::class)[email protected](org.robolectric.annotation.GraphicsMode.Mode.NATIVE)+class ArtworkFetchDeepTest {++    private val ctx: Context get() = ApplicationProvider.getApplicationContext()++    init {+        // Loopback must not go through the corporate proxy injected via JAVA_TOOL_OPTIONS.+        System.setProperty("http.nonProxyHosts", "127.0.0.1|localhost")+        System.setProperty("https.nonProxyHosts", "127.0.0.1|localhost")+    }++    /** A 2x2 PNG written by ImageIO, so the bytes are a valid image by construction. */+    private val pngBytes: ByteArray by lazy {+        val image = java.awt.image.BufferedImage(2, 2, java.awt.image.BufferedImage.TYPE_INT_ARGB)+        val out = java.io.ByteArrayOutputStream()+        javax.imageio.ImageIO.write(image, "png", out)+        out.toByteArray()+    }++    private fun withServer(+        status: Int,+        block: (port: Int, fingerprint: String) -> Unit,+    ) {+        val credentials = EphemeralTls.server(listOf(InetAddress.getByName("127.0.0.1")))+        val server = HttpsServer.create(InetSocketAddress("127.0.0.1", 0), 0)+        server.setHttpsConfigurator(com.sun.net.httpserver.HttpsConfigurator(credentials.sslContext))+        server.createContext("/") { exchange ->+            val body = if (status == 200) pngBytes else ByteArray(0)+            exchange.sendResponseHeaders(status, body.size.toLong())+            exchange.responseBody.use { it.write(body) }+        }+        server.start()+        try {+            block(server.address.port, ProtocolBase64.encode(credentials.fingerprint))+        } finally {+            server.stop(0)+        }+    }++    @Test fun fetchDecodesPngFromPinnedServer() {+        withServer(200) { port, fingerprint ->+            val fetcher = ArtworkFetcher(+                ContentSession(+                    host = "127.0.0.1", port = port,+                    certificateFingerprint = fingerprint,+                    token = "tok", video = true,+                ),+            )+            val bitmap = fetcher.fetch("cover-9")+            assertNotNull(bitmap)+            assertEqualsDims(bitmap.width, bitmap.height)+        }+    }++    @Test fun fetchReturnsNullOnHttpError() {+        withServer(404) { port, fingerprint ->+            val fetcher = ArtworkFetcher(+                ContentSession(+                    host = "127.0.0.1", port = port,+                    certificateFingerprint = fingerprint,+                    token = "tok", video = true,+                ),+            )+            assertNull(fetcher.fetch("missing"))+        }+    }++    private fun assertEqualsDims(width: Int, height: Int) {+        kotlin.test.assertEquals(2, width)+        kotlin.test.assertEquals(2, height)+    }+}
cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/AuthenticateDeepTest.kt
diff --git a/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/AuthenticateDeepTest.kt b/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/AuthenticateDeepTest.ktnew file mode 100644index 0000000000..e93984c17b--- /dev/null+++ b/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/AuthenticateDeepTest.kt@@ -0,0 +1,99 @@+package com.vayunmathur.cast.tv.platform++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.cast.protocol.Hello+import com.vayunmathur.cast.protocol.PairFailed+import com.vayunmathur.cast.protocol.PairProof+import com.vayunmathur.cast.protocol.PairRequired+import com.vayunmathur.cast.protocol.ProtocolBase64+import com.vayunmathur.cast.protocol.SessionKeys+import java.net.ServerSocket+import java.net.Socket+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.async+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/** Pairing edges: attempts exhausted, and a phone that vanishes mid-pairing. */+@RunWith(RobolectricTestRunner::class)+class AuthenticateDeepTest {++    private val ctx: Context get() = ApplicationProvider.getApplicationContext()++    private fun channelPair(): Pair<ControlChannel, ControlChannel> {+        val server = ServerSocket(0)+        var accepted: Socket? = null+        val thread = Thread { accepted = server.accept() }+        thread.start()+        val client = Socket("127.0.0.1", server.localPort)+        thread.join(5_000)+        server.close()+        return ControlChannel(accepted!!) to ControlChannel(client)+    }++    @Test fun pairingWrongProofsRotateCodeThenRightProofPairs() { runBlocking {+        val (tv, phone) = channelPair()+        val store = PairingStore(ctx)+        val keys = SessionKeys.of(ByteArray(32) { 12 })+        val transcript = byteArrayOf(1)+        val greeting = Hello(senderName = "Pixel", senderId = "phone-exhaust-1", paired = false)+        val result = async(Dispatchers.IO) {+            ReceiverController.authenticate(tv, store, keys, transcript, greeting)+        }+        assertEquals(true, (phone.receive()?.message as PairRequired).code)+        // Burn all three attempts with wrong proofs: 2, 1, then the code is+        // thrown away and a fresh one issued (attempts reset, codeChanged set).+        val seen = mutableListOf<PairFailed>()+        repeat(3) {+            phone.send(PairProof(ProtocolBase64.encode(byteArrayOf(0, 0, 0))))+            seen += phone.receive()?.message as PairFailed+        }+        assertEquals(listOf(2, 1, 3), seen.map { it.attemptsLeft })+        assertTrue(seen.last().codeChanged)+        // The right proof for the code now on screen still pairs.+        val pairing = ReceiverController.state.value.phase as ReceiverPhase.Pairing+        phone.send(PairProof(ProtocolBase64.encode(keys.pairProof(pairing.code, transcript))))+        assertTrue(phone.receive()?.message is com.vayunmathur.cast.protocol.PairOk)+        assertTrue(result.await())+        tv.close()+        phone.close()+    } }++    @Test fun phoneVanishingMidPairingEndsAuthentication() { runBlocking {+        val (tv, phone) = channelPair()+        val store = PairingStore(ctx)+        val keys = SessionKeys.of(ByteArray(32) { 13 })+        val greeting = Hello(senderName = "Pixel", senderId = "phone-vanish-1", paired = false)+        val result = async(Dispatchers.IO) {+            ReceiverController.authenticate(tv, store, keys, byteArrayOf(2), greeting)+        }+        assertEquals(true, (phone.receive()?.message as PairRequired).code)+        phone.close()+        assertFalse(result.await())+        tv.close()+    } }++    @Test fun rememberedKeyWithWrongProofAndVanish() { runBlocking {+        val (tv, phone) = channelPair()+        val store = PairingStore(ctx)+        store.remember("phone-known-9", ByteArray(32) { 6 })+        val keys = SessionKeys.of(ByteArray(32) { 14 })+        val greeting = Hello(senderName = "Pixel", senderId = "phone-known-9", paired = true)+        val result = async(Dispatchers.IO) {+            ReceiverController.authenticate(tv, store, keys, byteArrayOf(3), greeting)+        }+        assertEquals(false, (phone.receive()?.message as PairRequired).code)+        // Wrong device proof falls through to a code; then the phone leaves.+        phone.send(PairProof(ProtocolBase64.encode(byteArrayOf(1))))+        assertEquals(true, (phone.receive()?.message as PairRequired).code)+        phone.close()+        assertFalse(result.await())+        tv.close()+    } }+}
cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/CompanionDeepTest.kt
diff --git a/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/CompanionDeepTest.kt b/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/CompanionDeepTest.ktnew file mode 100644index 0000000000..bf8141d026--- /dev/null+++ b/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/CompanionDeepTest.kt@@ -0,0 +1,72 @@+package com.vayunmathur.cast.tv.platform++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.cast.protocol.ContentSession+import com.vayunmathur.cast.protocol.ProtocolBase64+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/** Decoder limits, network label, and artwork fetcher failure paths on the host. */+@RunWith(RobolectricTestRunner::class)+class CompanionDeepTest {++    private val ctx: Context get() = ApplicationProvider.getApplicationContext()++    @Test fun videoAndAudioLimitsReflectHostCodecs() {+        // Robolectric enumerates no hardware decoders, so both limit queries must+        // answer with their "nothing to advertise" shape rather than throwing.+        val video = VideoDecoder.limits()+        assertNotNull(video.videoCodecs)+        for (codec in com.vayunmathur.cast.protocol.VideoCodec.entries) {+            val name = VideoDecoder.decoderName(codec)+            assertTrue(name == null || name.isNotBlank())+        }+        val audio = AudioPlayer.limits()+        assertTrue(audio.isEmpty() || audio.single().label.isNotBlank())+        AudioPlayer.decoderName() // null or a codec name; must not throw either way+    }++    @Test fun networkLabelNeverThrows() {+        // SSID/IP halves both fail open on a headless host; the joined label is+        // whatever could be read, possibly empty.+        val label = NetworkLabel.of(ctx)+        assertNotNull(label)+    }++    @Test fun artworkFetcherRejectsBadFingerprintsAndUnreachableHosts() {+        val badFingerprint = ArtworkFetcher(+            ContentSession(+                host = "127.0.0.1", port = 9,+                certificateFingerprint = "not-base64!!",+                token = "tok", video = true,+            ),+        )+        assertNull(badFingerprint.fetch("cover-1"))++        val shortFingerprint = ArtworkFetcher(+            ContentSession(+                host = "127.0.0.1", port = 9,+                certificateFingerprint = ProtocolBase64.encode(ByteArray(8)),+                token = "tok", video = true,+            ),+        )+        assertNull(shortFingerprint.fetch("cover-1"))++        val unreachable = ArtworkFetcher(+            ContentSession(+                host = "127.0.0.1", port = 9,+                certificateFingerprint = ProtocolBase64.encode(ByteArray(32) { it.toByte() }),+                token = "tok", video = true,+            ),+        )+        // A well-formed fingerprint reaches the fetch, which fails soft (refused).+        assertNull(unreachable.fetch("cover-1"))+        assertEquals(32, ProtocolBase64.decode(ProtocolBase64.encode(ByteArray(32)))?.size)+    }+}
cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/ContentPlayerDeepTest.kt
diff --git a/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/ContentPlayerDeepTest.kt b/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/ContentPlayerDeepTest.ktnew file mode 100644index 0000000000..9784e06c7a--- /dev/null+++ b/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/ContentPlayerDeepTest.kt@@ -0,0 +1,93 @@+package com.vayunmathur.cast.tv.platform++import android.content.Context+import android.os.Looper+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.cast.protocol.ContentSession+import com.vayunmathur.cast.protocol.PlayMedia+import com.vayunmathur.cast.protocol.PlaybackAction+import com.vayunmathur.cast.protocol.PlaybackCommand+import com.vayunmathur.cast.protocol.ProtocolBase64+import kotlinx.coroutines.Deferred+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.async+import kotlinx.coroutines.delay+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.withContext+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * ContentPlayer built directly: every transport action applied to an idle+ * player, the unusable-fingerprint refusal, and snapshots of nothing playing.+ *+ * Main-thread work runs on a background coroutine while the test thread pumps+ * the main looper - under Robolectric Dispatchers.Main is that paused looper.+ */+@RunWith(RobolectricTestRunner::class)+class ContentPlayerDeepTest {++    private val ctx: Context get() = ApplicationProvider.getApplicationContext()++    private fun session(fingerprint: ByteArray = ByteArray(32) { 7 }) = ContentSession(+        host = "127.0.0.1", port = 9,+        certificateFingerprint = ProtocolBase64.encode(fingerprint),+        token = "tok", video = true, appLabel = "YouPipe",+    )++    private suspend fun <T> onMainPumped(block: suspend () -> T): T {+        val deferred: Deferred<T> = kotlinx.coroutines.CoroutineScope(Dispatchers.Default).async {+            withContext(Dispatchers.Main) { block() }+        }+        while (!deferred.isCompleted) {+            shadowOf(Looper.getMainLooper()).idle()+            delay(25)+        }+        return deferred.await()+    }++    @Test fun applyEveryActionOnIdlePlayer() { runBlocking {+        val errors = mutableListOf<String>()+        onMainPumped {+            val player = ContentPlayer(ctx, session())+            assertTrue(player.start { detail -> errors += detail })+            assertTrue(player.apply(PlaybackCommand(PlaybackAction.Play)))+            assertTrue(player.apply(PlaybackCommand(PlaybackAction.Pause)))+            assertTrue(player.apply(PlaybackCommand(PlaybackAction.Toggle)))+            assertTrue(player.apply(PlaybackCommand(PlaybackAction.Toggle)))+            assertTrue(player.apply(PlaybackCommand(PlaybackAction.SeekTo, value = 12_000.0)))+            assertTrue(player.apply(PlaybackCommand(PlaybackAction.SkipForward)))+            assertTrue(player.apply(PlaybackCommand(PlaybackAction.SkipBack)))+            assertTrue(player.apply(PlaybackCommand(PlaybackAction.SetSpeed, value = 1.5)))+            assertTrue(player.apply(PlaybackCommand(PlaybackAction.SetVolume, value = 0.4)))+            // The queue belongs to the phone: these two are refused, by contract.+            assertFalse(player.apply(PlaybackCommand(PlaybackAction.Next)))+            assertFalse(player.apply(PlaybackCommand(PlaybackAction.Previous)))+            // No value: accepted, nothing to apply.+            assertTrue(player.apply(PlaybackCommand(PlaybackAction.SeekTo)))+            // Nothing loaded: the snapshot says so.+            val idle = player.snapshot()+            assertEquals(0L, idle.durationMs)+            assertFalse(idle.playing)+            player.play(PlayMedia(resourceId = "clip", mimeType = "video/mp4", durationMs = 60_000))+            player.setSurface(null)+            player.release()+            player.release() // idempotent teardown+        }+        Unit+    } }++    @Test fun startRefusesUnusableFingerprint() { runBlocking {+        onMainPumped {+            val player = ContentPlayer(ctx, session(fingerprint = ByteArray(8)))+            assertFalse(player.start { })+            player.release()+        }+        Unit+    } }+}
cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/ControlChannelDeepTest.kt
diff --git a/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/ControlChannelDeepTest.kt b/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/ControlChannelDeepTest.ktnew file mode 100644index 0000000000..03a9c08305--- /dev/null+++ b/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/ControlChannelDeepTest.kt@@ -0,0 +1,83 @@+package com.vayunmathur.cast.tv.platform++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.cast.protocol.Ping+import java.net.ServerSocket+import java.net.Socket+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/** ControlChannel round-trip, peer-close, and close semantics. */+@RunWith(RobolectricTestRunner::class)+class ControlChannelDeepTest {++    private val ctx: Context get() = ApplicationProvider.getApplicationContext()++    private fun channelPair(): Pair<ControlChannel, ControlChannel> {+        val server = ServerSocket(0)+        var accepted: Socket? = null+        val thread = Thread { accepted = server.accept() }+        thread.start()+        val client = Socket("127.0.0.1", server.localPort)+        thread.join(5_000)+        server.close()+        return ControlChannel(accepted!!) to ControlChannel(client)+    }++    @Test fun roundTripAndAddresses() {+        val (tv, phone) = channelPair()+        assertTrue(tv.remoteAddress.isNotBlank())+        phone.send(Ping)+        assertTrue(tv.receive()?.message is Ping)+        tv.send(Ping)+        assertTrue(phone.receive()?.message is Ping)+        tv.close()+        phone.close()+    }++    @Test fun receiveReturnsNullAfterPeerLeaves() {+        val (tv, phone) = channelPair()+        phone.close()+        // The stream ends: receive reports null rather than throwing.+        assertNull(tv.receive())+        tv.close()+        tv.close() // closing twice is fine+    }++    @Test fun controllerStartStopCycles() {+        // listen() runs on the controller's scope; wait for the socket to appear.+        fun awaitSocket() {+            val deadline = System.currentTimeMillis() + 10_000+            while (ReceiverController.serverSocket == null && System.currentTimeMillis() < deadline) {+                org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+                Thread.sleep(25)+            }+        }+        ReceiverController.start(ctx)+        ReceiverController.start(ctx) // already running: a no-op second start+        awaitSocket()+        assertNotNull(ReceiverController.serverSocket)+        ReceiverController.stop()+        ReceiverController.stop() // stopping a stopped controller is fine+        ReceiverController.start(ctx)+        awaitSocket()+        assertNotNull(ReceiverController.serverSocket)+        ReceiverController.stop()+        // And once more with decoders installed, so listen() advertises real limits.+        FakeDecoders.install()+        try {+            ReceiverController.start(ctx)+            awaitSocket()+            assertNotNull(ReceiverController.serverSocket)+        } finally {+            ReceiverController.stop()+            FakeDecoders.reset()+        }+    }+}
cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/FakeDecoders.kt
diff --git a/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/FakeDecoders.kt b/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/FakeDecoders.ktnew file mode 100644index 0000000000..a3e7f16e88--- /dev/null+++ b/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/FakeDecoders.kt@@ -0,0 +1,83 @@+package com.vayunmathur.cast.tv.platform++import android.graphics.SurfaceTexture+import android.media.MediaCodecInfo+import android.media.MediaFormat+import android.view.Surface+import com.vayunmathur.cast.protocol.VideoCodec+import org.robolectric.shadows.MediaCodecInfoBuilder+import org.robolectric.shadows.ShadowMediaCodec+import org.robolectric.shadows.ShadowMediaCodecList++/**+ * Fake hardware decoders in Robolectric's codec list, mirrored from the sender's+ * FakeEncoders. Reset afterwards: other tests must keep seeing a decoder-less TV.+ */+object FakeDecoders {++    fun install() {+        ShadowMediaCodecList.reset()+        addVideo("fake.hevc.decoder", VideoCodec.Hevc.mimeType, 3840 to 2160)+        addVideo("fake.av1.decoder", VideoCodec.Av1.mimeType, 1920 to 1080)+        addAudio("fake.opus.decoder")+    }++    fun reset() {+        ShadowMediaCodecList.reset()+        ShadowMediaCodec.clearCodecs()+    }++    private fun registerShadowCodec(name: String) {+        ShadowMediaCodec.addDecoder(+            name,+            ShadowMediaCodec.CodecConfig(BUFFER_BYTES, BUFFER_BYTES) { input, output ->+                output.put(input)+            },+        )+    }++    private const val BUFFER_BYTES = 16_384++    private fun addVideo(name: String, mime: String, size: Pair<Int, Int>) {+        val format = MediaFormat.createVideoFormat(mime, size.first, size.second)+        val caps = MediaCodecInfoBuilder.CodecCapabilitiesBuilder.newBuilder()+            .setMediaFormat(format)+            .setColorFormats(intArrayOf(MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface))+            .setIsEncoder(false)+            .build()+        ShadowMediaCodecList.addCodec(+            MediaCodecInfoBuilder.newBuilder()+                .setName(name)+                .setIsEncoder(false)+                .setIsHardwareAccelerated(true)+                .setIsSoftwareOnly(false)+                .setCapabilities(caps)+                .build(),+        )+        registerShadowCodec(name)+    }++    private fun addAudio(name: String) {+        val format = MediaFormat.createAudioFormat(AudioPlayer.AUDIO_MIME, 48_000, 2)+        val caps = MediaCodecInfoBuilder.CodecCapabilitiesBuilder.newBuilder()+            .setMediaFormat(format)+            .setIsEncoder(false)+            .build()+        ShadowMediaCodecList.addCodec(+            MediaCodecInfoBuilder.newBuilder()+                .setName(name)+                .setIsEncoder(false)+                .setIsHardwareAccelerated(true)+                .setIsSoftwareOnly(false)+                .setCapabilities(caps)+                .build(),+        )+        registerShadowCodec(name)+    }+}++/** A Surface over a retained texture, for decoder construction. */+class TestSurface {+    val texture = SurfaceTexture(7)+    val surface = Surface(texture)+}
cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/MediaReceiverDeepTest.kt
diff --git a/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/MediaReceiverDeepTest.kt b/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/MediaReceiverDeepTest.ktnew file mode 100644index 0000000000..815eaf94ae--- /dev/null+++ b/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/MediaReceiverDeepTest.kt@@ -0,0 +1,56 @@+package com.vayunmathur.cast.tv.platform++import com.vayunmathur.cast.protocol.Negotiation+import com.vayunmathur.cast.protocol.SessionKeys+import com.vayunmathur.cast.protocol.StreamConfig+import com.vayunmathur.cast.protocol.StreamReady+import com.vayunmathur.cast.protocol.VideoCodec+import java.net.DatagramPacket+import java.net.DatagramSocket+import java.net.InetAddress+import kotlin.test.Test+import kotlin.test.assertTrue++/** MediaReceiver feedback and stray-datagram handling. */+class MediaReceiverDeepTest {++    @Test fun feedbackBeforeAndAfterSenderKnown() {+        val keys = SessionKeys.of(ByteArray(32) { 11 })+        val config = StreamConfig(+            width = 320, height = 240, frameRate = 30f, bitRate = 100_000,+            audio = true, video = true, audioSsrc = 1111, videoSsrc = 2222,+            videoCodec = VideoCodec.Hevc,+        )+        val negotiation = Negotiation.of(config, StreamReady(0, 3333, 4444), keys)+        val socket = DatagramSocket(0)+        var video = 0+        var audio = 0+        val receiver = MediaReceiver(socket, negotiation, { video++ }, { audio++ }, { true })++        // No sender known yet: feedback is computed but addressed nowhere.+        receiver.sendFeedback()+        receiver.sendFeedback(senderIdle = true)++        // A sender report (RTCP, version 2, not an RTP stream packet).+        val sender = DatagramSocket()+        val report = ByteArray(28) { 0 }+        report[0] = 0x80.toByte(); report[1] = 200.toByte() // SR+        sender.send(DatagramPacket(report, report.size, InetAddress.getByName("127.0.0.1"), receiver.port))+        assertTrue(receiver.pump())++        // Garbage short datagram: parsed as nothing, pump still answers true.+        sender.send(DatagramPacket(byteArrayOf(9, 9), 2, InetAddress.getByName("127.0.0.1"), receiver.port))+        assertTrue(receiver.pump())+        assertTrue(video == 0 && audio == 0)++        // Now feedback has a destination: the sender receives bytes back.+        sender.soTimeout = 3_000+        receiver.sendFeedback()+        val feedback = DatagramPacket(ByteArray(2048), 2048)+        sender.receive(feedback)+        assertTrue(feedback.length > 0)+        assertTrue(receiver.throughputSummary().isNotBlank())+        receiver.close()+        sender.close()+    }+}
cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/NetworkAndAdvertiserTest.kt
diff --git a/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/NetworkAndAdvertiserTest.kt b/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/NetworkAndAdvertiserTest.ktnew file mode 100644index 0000000000..611c0bb59e--- /dev/null+++ b/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/NetworkAndAdvertiserTest.kt@@ -0,0 +1,80 @@+package com.vayunmathur.cast.tv.platform++import android.content.Context+import android.net.ConnectivityManager+import android.net.NetworkCapabilities+import android.net.wifi.WifiInfo+import android.net.wifi.WifiManager+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.cast.protocol.DecoderLimits+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/** NetworkLabel against shadow Wi-Fi state, and the NSD advertiser lifecycle. */+@RunWith(RobolectricTestRunner::class)+class NetworkAndAdvertiserTest {++    private val ctx: Context get() = ApplicationProvider.getApplicationContext()++    /** Wi-Fi transport capabilities, built reflectively (Builder is not on the compile SDK). */+    private fun wifiCapabilities(): NetworkCapabilities {+        val builderClass = Class.forName("android.net.NetworkCapabilities\$Builder")+        val builder = try {+            builderClass.getConstructor().newInstance()+        } catch (ignored: NoSuchMethodException) {+            builderClass.getConstructor(NetworkCapabilities::class.java)+                .newInstance(NetworkCapabilities())+        }+        builderClass.getMethod("addTransportType", Int::class.java)+            .invoke(builder, NetworkCapabilities.TRANSPORT_WIFI)+        return builderClass.getMethod("build").invoke(builder) as NetworkCapabilities+    }++    /** A WifiInfo carrying [ssid], built reflectively (Builder is not on the compile SDK). */+    private fun wifiInfo(ssid: String): WifiInfo {+        val builderClass = Class.forName("android.net.wifi.WifiInfo\$Builder")+        val builder = builderClass.getConstructor().newInstance()+        builderClass.getMethod("setSsid", ByteArray::class.java).invoke(builder, ssid.toByteArray())+        builderClass.getMethod("setBssid", String::class.java).invoke(builder, "02:00:00:00:01:00")+        return builderClass.getMethod("build").invoke(builder) as WifiInfo+    }++    @Test fun labelJoinsSsidAndAddressOnWifi() {+        val wifi = ctx.getSystemService(Context.WIFI_SERVICE) as WifiManager+        shadowOf(wifi).setConnectionInfo(wifiInfo("\"HomeWiFi\""))+        val cm = ctx.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager+        val network = cm.activeNetwork+        if (network != null) {+            shadowOf(cm).setNetworkCapabilities(network, wifiCapabilities())+        }+        val label = NetworkLabel.of(ctx)+        // The SSID half must survive quote-stripping when Wi-Fi transport is reported.+        assertTrue(label.isEmpty() || label.contains("HomeWiFi") || !label.contains("\""), label)+    }++    @Test fun labelHidesUnknownSsid() {+        val wifi = ctx.getSystemService(Context.WIFI_SERVICE) as WifiManager+        shadowOf(wifi).setConnectionInfo(wifiInfo("<unknown ssid>"))+        val label = NetworkLabel.of(ctx)+        assertTrue(!label.contains("unknown"), label)+    }++    @Test fun advertiserRegistersAndUnregisters() {+        val advertiser = ReceiverAdvertiser(ctx)+        advertiser.advertise(+            friendlyName = "Living Room TV",+            deviceId = "abc123def456",+            port = 43210,+            limits = DecoderLimits(),+        )+        // Robolectric's NsdManager accepts the registration; the advertiser must+        // not report the local-network block on the happy path.+        assertEquals(false, advertiser.localNetworkBlocked)+        advertiser.unadvertise()+        advertiser.unadvertise() // second teardown is a no-op+    }+}
cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/PlayersDeepTest.kt
diff --git a/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/PlayersDeepTest.kt b/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/PlayersDeepTest.ktnew file mode 100644index 0000000000..92e01ada50--- /dev/null+++ b/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/PlayersDeepTest.kt@@ -0,0 +1,137 @@+package com.vayunmathur.cast.tv.platform++import com.vayunmathur.cast.protocol.VideoCodec+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.AfterTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++private fun addDecoderForTest(name: String, mime: String, size: Pair<Int, Int>, hardware: Boolean) {+    val format = android.media.MediaFormat.createVideoFormat(mime, size.first, size.second)+    val caps = org.robolectric.shadows.MediaCodecInfoBuilder.CodecCapabilitiesBuilder.newBuilder()+        .setMediaFormat(format)+        .setColorFormats(intArrayOf(android.media.MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface))+        .setIsEncoder(false)+        .build()+    org.robolectric.shadows.ShadowMediaCodecList.addCodec(+        org.robolectric.shadows.MediaCodecInfoBuilder.newBuilder()+            .setName(name)+            .setIsEncoder(false)+            .setIsHardwareAccelerated(hardware)+            .setIsSoftwareOnly(!hardware)+            .setCapabilities(caps)+            .build(),+    )+    org.robolectric.shadows.ShadowMediaCodec.addDecoder(+        name,+        org.robolectric.shadows.ShadowMediaCodec.CodecConfig(16_384, 16_384) { input, output -> output.put(input) },+    )+}++/**+ * The decoder/player layer against fake hardware codecs.+ *+ * Without fakes these classes only exercise their no-decoder branches on the+ * host; with them the start/decode/play paths run against Robolectric's shadow+ * MediaCodec and AudioTrack, and the capability advertisement is verified+ * against the envelopes the fakes publish.+ */+@RunWith(RobolectricTestRunner::class)+class PlayersDeepTest {++    @AfterTest fun tearDown() {+        FakeDecoders.reset()+    }++    @Test fun limitsAdvertiseFakeDecoders() {+        FakeDecoders.install()+        val limits = VideoDecoder.limits()+        // Every codec the fakes publish must be advertised with a positive envelope.+        assertEquals(VideoCodec.entries.size, limits.videoCodecs.size)+        for (advertised in limits.videoCodecs) {+            assertTrue(advertised.maxWidth > 0, advertised.toString())+            assertTrue(advertised.maxHeight > 0, advertised.toString())+        }+        assertEquals("fake.hevc.decoder", VideoDecoder.decoderName(VideoCodec.Hevc))+        assertEquals("fake.av1.decoder", VideoDecoder.decoderName(VideoCodec.Av1))+        assertEquals(listOf(com.vayunmathur.cast.protocol.AudioCodec.Opus), AudioPlayer.limits())+        assertEquals("fake.opus.decoder", AudioPlayer.decoderName())+    }++    @Test fun videoDecoderStartsDecodesRendersAndReleases() {+        FakeDecoders.install()+        val surface = TestSurface()+        val decoder = VideoDecoder(surface.surface, VideoCodec.Hevc)+        // Frames before start are dropped and counted, never queued.+        assertFalse(decoder.decode(ByteArray(16) { 1 }, 0L, isKeyFrame = true))+        assertEquals(1L, decoder.framesDropped)+        decoder.render() // no codec: a no-op, not a fault++        assertTrue(decoder.start(320, 240))+        assertTrue(decoder.decode(ByteArray(64) { 2 }, 33_000L, isKeyFrame = true))+        assertTrue(decoder.decode(ByteArray(64) { 3 }, 66_000L, isKeyFrame = false))+        decoder.render()+        decoder.release()+        // After release, frames drop again.+        assertFalse(decoder.decode(ByteArray(8) { 1 }, 0L, isKeyFrame = false))+        surface.texture.release()+    }++    @Test fun av1DecoderTakesSynthesisedConfig() {+        FakeDecoders.install()+        val surface = TestSurface()+        val decoder = VideoDecoder(surface.surface, VideoCodec.Av1)+        assertTrue(decoder.start(640, 480, codecConfig = byteArrayOf(0x0a, 0x0e, 0x00)))+        assertTrue(decoder.decode(ByteArray(32) { 9 }, 0L, isKeyFrame = true))+        decoder.render()+        decoder.release()+        surface.texture.release()+    }++    @Test fun audioPlayerStartsPlaysAndReleases() {+        FakeDecoders.install()+        val player = AudioPlayer()+        // Nothing before start.+        player.play(ByteArray(20) { 1 }, 0L)+        player.setVolume(0.5f) // no track yet: ignored+        assertTrue(player.start())+        player.setVolume(0.5f)+        player.setVolume(2f) // clamped onto the track+        repeat(3) { player.play(ByteArray(40) { (it + 1).toByte() }, it * 20_000L) }+        assertFalse(player.failed)+        assertEquals(0, player.restarts)+        player.release()+        // Released: play is a no-op, release is idempotent.+        player.play(ByteArray(20) { 1 }, 0L)+        player.release()+    }++    @Test fun decoderNamePicksLargestHardwareDecoder() {+        // Two rival HEVC decoders plus a software one: the largest hardware wins.+        org.robolectric.shadows.ShadowMediaCodecList.reset()+        addDecoderForTest("fake.hevc.small", VideoCodec.Hevc.mimeType, 640 to 480, hardware = true)+        addDecoderForTest("fake.hevc.big", VideoCodec.Hevc.mimeType, 3840 to 2160, hardware = true)+        addDecoderForTest("fake.hevc.software", VideoCodec.Hevc.mimeType, 7680 to 4320, hardware = false)+        assertEquals("fake.hevc.big", VideoDecoder.decoderName(VideoCodec.Hevc))+        val limits = VideoDecoder.limits()+        val hevc = limits.videoCodecs.single { it.codec == VideoCodec.Hevc }+        assertEquals(3840, hevc.maxWidth)+        FakeDecoders.reset()+    }++    @Test fun playersFailSoftWithoutDecoders() {+        // No fakes installed: the honest "this TV cannot" answers.+        assertTrue(VideoDecoder.limits().videoCodecs.isEmpty())+        assertTrue(AudioPlayer.limits().isEmpty())+        val surface = TestSurface()+        val decoder = VideoDecoder(surface.surface, VideoCodec.Hevc)+        assertFalse(decoder.start(320, 240))+        val player = AudioPlayer()+        assertFalse(player.start())+        player.release()+        surface.texture.release()+    }+}
cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/PlayersEmittingTest.kt
diff --git a/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/PlayersEmittingTest.kt b/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/PlayersEmittingTest.ktnew file mode 100644index 0000000000..81aad66442--- /dev/null+++ b/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/PlayersEmittingTest.kt@@ -0,0 +1,90 @@+package com.vayunmathur.cast.tv.platform++import android.media.MediaCodec+import com.vayunmathur.cast.protocol.VideoCodec+import java.nio.ByteBuffer+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import org.robolectric.annotation.Implementation+import org.robolectric.annotation.Implements+import org.robolectric.shadows.ShadowMediaCodec+import kotlin.test.AfterTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * A codec that emits: two output buffers, then "try again later". Per-instance+ * state (Robolectric keeps one shadow per codec), mirroring the sender's+ * ShadowMediaCodecSynthesizing.+ */+@Implements(MediaCodec::class)+class ShadowMediaCodecEmitting : ShadowMediaCodec() {++    private var emitted = 0++    @Suppress("UnusedParameter")+    @Implementation+    fun getInputBuffer(index: Int): ByteBuffer = ByteBuffer.allocate(INPUT_CAPACITY)++    @Suppress("UnusedParameter")+    @Implementation+    fun getOutputBuffer(index: Int): ByteBuffer =+        ByteBuffer.wrap(ByteArray(OUTPUT_CAPACITY) { (it * 5 + 2).toByte() })++    @Suppress("UnusedParameter")+    @Implementation+    fun dequeueOutputBuffer(info: MediaCodec.BufferInfo, timeoutUs: Long): Int {+        if (emitted >= EMITTED_BUFFERS) return MediaCodec.INFO_TRY_AGAIN_LATER+        emitted+++        info.offset = 0+        info.size = OUTPUT_CAPACITY+        info.presentationTimeUs = emitted * 20_000L+        info.flags = 0+        return emitted - 1+    }++    @Suppress("UnusedParameter")+    @Implementation+    override fun releaseOutputBuffer(index: Int, render: Boolean) = Unit++    private companion object {+        const val INPUT_CAPACITY = 64 * 1024+        const val OUTPUT_CAPACITY = 64+        const val EMITTED_BUFFERS = 2+    }+}++/** Play/render paths with a codec that actually produces output. */+@RunWith(RobolectricTestRunner::class)+@Config(shadows = [ShadowMediaCodecEmitting::class])+class PlayersEmittingTest {++    @AfterTest fun tearDown() {+        FakeDecoders.reset()+    }++    @Test fun audioPlayDrainsDecodedOutputToTrack() {+        FakeDecoders.install()+        val player = AudioPlayer()+        assertTrue(player.start())+        repeat(3) { player.play(ByteArray(60) { (it + 3).toByte() }, it * 20_000L) }+        assertFalse(player.failed)+        assertEquals(0, player.restarts)+        player.release()+    }++    @Test fun videoRenderDrainsDecodedFrames() {+        FakeDecoders.install()+        val surface = TestSurface()+        val decoder = VideoDecoder(surface.surface, VideoCodec.Hevc)+        assertTrue(decoder.start(320, 240))+        assertTrue(decoder.decode(ByteArray(96) { 5 }, 0L, isKeyFrame = true))+        decoder.render()+        decoder.render() // second pump: nothing left to drain+        decoder.release()+        surface.texture.release()+    }+}
cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/ServeContentDeepTest.kt
diff --git a/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/ServeContentDeepTest.kt b/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/ServeContentDeepTest.ktnew file mode 100644index 0000000000..b16650a4bd--- /dev/null+++ b/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/ServeContentDeepTest.kt@@ -0,0 +1,188 @@+package com.vayunmathur.cast.tv.platform++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.cast.protocol.Bye+import com.vayunmathur.cast.protocol.ContentReady+import com.vayunmathur.cast.protocol.ContentSession+import com.vayunmathur.cast.protocol.NowPlaying+import com.vayunmathur.cast.protocol.Ping+import com.vayunmathur.cast.protocol.PlayMedia+import com.vayunmathur.cast.protocol.PlaybackAction+import com.vayunmathur.cast.protocol.PlaybackCommand+import com.vayunmathur.cast.protocol.ContentEnded+import com.vayunmathur.cast.protocol.PlaybackState+import java.net.ServerSocket+import java.net.Socket+import kotlin.io.encoding.Base64+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.async+import kotlinx.coroutines.delay+import kotlinx.coroutines.runBlocking+import android.os.Looper+import org.junit.runner.RunWith+import org.robolectric.Shadows.shadowOf+import org.robolectric.RobolectricTestRunner+import kotlin.test.AfterTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * serveContent called directly: the no-decoder refusal, and an audio session+ * (fake Opus decoder installed) served until the phone says goodbye.+ */+@RunWith(RobolectricTestRunner::class)+class ServeContentDeepTest {++    private val ctx: Context get() = ApplicationProvider.getApplicationContext()++    @AfterTest fun tearDown() {+        ReceiverController.contentPlayer = null+        ReceiverController.detachSurface()+        ReceiverController.forgetPlayback()+        FakeDecoders.reset()+    }++    private fun channelPair(): Pair<ControlChannel, ControlChannel> {+        val server = ServerSocket(0)+        var accepted: Socket? = null+        val thread = Thread { accepted = server.accept() }+        thread.start()+        val client = Socket("127.0.0.1", server.localPort)+        thread.join(5_000)+        server.close()+        return ControlChannel(accepted!!) to ControlChannel(client)+    }++    private fun session(video: Boolean) = ContentSession(+        host = "127.0.0.1", port = 9,+        certificateFingerprint = Base64.encode(ByteArray(32) { 3 }),+        token = "tok", video = video, appLabel = "Music",+    )++    private fun pumpMainUntil(deadlineMs: Long, done: () -> Boolean) {+        while (!done() && System.currentTimeMillis() < deadlineMs) {+            shadowOf(Looper.getMainLooper()).idle()+            Thread.sleep(25)+        }+    }++    @Test fun audioOnlyRefusedWithoutOpusDecoder() { runBlocking {+        // No fakes: this TV "has no Opus decoder", so it must refuse by name.+        val (tv, phone) = channelPair()+        val result = async(Dispatchers.Default) {+            ReceiverController.serveContent(ctx, tv, session(video = false), "Pixel")+        }+        val ready = phone.receive()?.message as ContentReady+        assertFalse(ready.accepted)+        assertTrue(ready.detail.contains("Opus"))+        pumpMainUntil(System.currentTimeMillis() + 10_000) { result.isCompleted }+        assertFalse(result.await())+        assertEquals(+            ReceiverPhase.Failed(ReceiverFailure.NoAudioDecoder),+            ReceiverController.state.value.phase,+        )+        phone.close()+    } }++    @Test fun audioSessionServedUntilBye() { runBlocking {+        FakeDecoders.install()+        val (tv, phone) = channelPair()+        val result = async(Dispatchers.Default) {+            ReceiverController.serveContent(ctx, tv, session(video = false), "Pixel")+        }+        // Phone side on IO: its receives block up to the channel timeout, so the+        // test thread stays free to pump the main looper the player hops to.+        val flow = async(Dispatchers.IO) {+            val ready = phone.receive()?.message as ContentReady+            assertTrue(ready.accepted, ready.detail)+            val phase = ReceiverController.state.value.phase+            assertTrue(phase is ReceiverPhase.Mirroring && !phase.hasVideo, phase.toString())++            phone.send(PlayMedia(resourceId = "song1", mimeType = "audio/mp4", durationMs = 30_000))+            phone.send(NowPlaying(resourceId = "song1", title = "A Song"))+            phone.send(PlaybackCommand(PlaybackAction.Toggle))+            phone.send(Ping)+            // Heartbeat reports (PlaybackState) and the ping echo interleave; read+            // until the echo proves the loop is alive.+            var echoed = false+            while (!echoed) {+                val message = phone.receive()?.message+                if (message is Ping) echoed = true+            }+            assertEquals("song1", ReceiverController.state.value.playingResourceId)+            phone.send(Bye())+            "done"+        }+        pumpMainUntil(System.currentTimeMillis() + 60_000) { flow.isCompleted && result.isCompleted }+        assertEquals("done", flow.await())+        assertFalse(result.await())+        phone.close()+    } }++    @Test fun videoSessionEndsBackToConnectedOnContentEnded() { runBlocking {+        FakeDecoders.install()+        val (tv, phone) = channelPair()+        val surface = TestSurface()+        ReceiverController.attachSurface(surface.surface)+        val result = async(Dispatchers.Default) {+            ReceiverController.serveContent(ctx, tv, session(video = true), "Pixel")+        }+        val flow = async(Dispatchers.IO) {+            val ready = phone.receive()?.message as ContentReady+            assertTrue(ready.accepted, ready.detail)+            val phase = ReceiverController.state.value.phase+            assertTrue(phase is ReceiverPhase.Mirroring && phase.hasVideo, phase.toString())+            phone.send(PlayMedia(resourceId = "clip1", mimeType = "video/mp4", durationMs = 45_000))+            phone.send(PlaybackCommand(PlaybackAction.Toggle))+            phone.send(ContentEnded)+            "done"+        }+        pumpMainUntil(System.currentTimeMillis() + 60_000) { flow.isCompleted && result.isCompleted }+        assertEquals("done", flow.await())+        // ContentEnded keeps the connection: serveContent returns true.+        assertTrue(result.await())+        phone.close()+        surface.texture.release()+    } }++    @Test fun unusableFingerprintRefusesAtPlayerBuild() { runBlocking {+        // A fingerprint that decodes but is the wrong size: the player cannot be+        // built, so the session is refused with that reason.+        val (tv, phone) = channelPair()+        val bad = ContentSession(+            host = "127.0.0.1", port = 9,+            certificateFingerprint = Base64.encode(ByteArray(8) { 5 }),+            token = "tok", video = true, appLabel = "YouPipe",+        )+        val result = async(Dispatchers.Default) {+            ReceiverController.serveContent(ctx, tv, bad, "Pixel")+        }+        val flow = async(Dispatchers.IO) { phone.receive()?.message as ContentReady }+        pumpMainUntil(System.currentTimeMillis() + 30_000) { flow.isCompleted && result.isCompleted }+        val ready = flow.await()+        assertFalse(ready.accepted)+        assertTrue(ready.detail.contains("player"), ready.detail)+        assertFalse(result.await())+        assertEquals(+            ReceiverPhase.Failed(ReceiverFailure.Handshake),+            ReceiverController.state.value.phase,+        )+        phone.close()+    } }++    @Test fun publishReportsLocallyAndFailsSoftOnDeadChannel() {+        val (tv, phone) = channelPair()+        phone.close()+        tv.close()+        // The snapshot still lands in local state even when the phone is gone.+        ReceiverController.publish(+            PlaybackState(5_000, 60_000, playing = true, buffering = false, volume = 0.75f),+            tv,+        )+        assertEquals(0.75f, ReceiverController.state.value.playback?.state?.volume)+        ReceiverController.forgetPlayback()+    }+}
cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/StartStreamingDeepTest.kt
diff --git a/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/StartStreamingDeepTest.kt b/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/StartStreamingDeepTest.ktnew file mode 100644index 0000000000..08d4195163--- /dev/null+++ b/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/StartStreamingDeepTest.kt@@ -0,0 +1,74 @@+package com.vayunmathur.cast.tv.platform++import com.vayunmathur.cast.protocol.SessionKeys+import com.vayunmathur.cast.protocol.StreamConfig+import com.vayunmathur.cast.protocol.StreamReady+import com.vayunmathur.cast.protocol.VideoCodec+import java.net.ServerSocket+import java.net.Socket+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.AfterTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * startStreaming end to end and its refusal: a live channel gets STREAM_READY+ * and the Mirroring phase; a dead channel refuses the session by name.+ */+@RunWith(RobolectricTestRunner::class)+class StartStreamingDeepTest {++    @AfterTest fun tearDown() {+        ReceiverController.endMedia()+        ReceiverController.detachSurface()+        ReceiverController.forgetPlayback()+        FakeDecoders.reset()+    }++    private fun channelPair(): Pair<ControlChannel, ControlChannel> {+        val server = ServerSocket(0)+        var accepted: Socket? = null+        val thread = Thread { accepted = server.accept() }+        thread.start()+        val client = Socket("127.0.0.1", server.localPort)+        thread.join(5_000)+        server.close()+        return ControlChannel(accepted!!) to ControlChannel(client)+    }++    private val config = StreamConfig(+        width = 320, height = 240, frameRate = 30f, bitRate = 1_000_000,+        audio = false, video = true, audioSsrc = 0, videoSsrc = 2222,+        videoCodec = VideoCodec.Hevc,+    )++    @Test fun startStreamingSendsReadyAndMirrors() {+        FakeDecoders.install()+        val (tv, phone) = channelPair()+        ReceiverController.startStreaming(tv, SessionKeys.of(ByteArray(32) { 8 }), config, "Pixel")+        val ready = phone.receive()?.message+        assertTrue(ready is StreamReady, "expected STREAM_READY, got $ready")+        assertTrue((ready as StreamReady).udpPort > 0)+        val phase = ReceiverController.state.value.phase+        assertTrue(phase is ReceiverPhase.Mirroring, phase.toString())+        assertEquals(320, (phase as ReceiverPhase.Mirroring).width)+        // The pump is running (no surface yet, so no decoder); ending media joins it.+        ReceiverController.endMedia()+        phone.close()+    }++    @Test fun startStreamingRefusesOnDeadChannel() {+        FakeDecoders.install()+        val (tv, phone) = channelPair()+        phone.close()+        tv.close()+        ReceiverController.startStreaming(tv, SessionKeys.of(ByteArray(32) { 9 }), config, "Pixel")+        // The ready could not be sent, so the session is refused on screen.+        assertEquals(+            ReceiverPhase.Failed(ReceiverFailure.StreamEnded),+            ReceiverController.state.value.phase,+        )+    }+}
cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/StreamingPumpDeepTest.kt
diff --git a/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/StreamingPumpDeepTest.kt b/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/StreamingPumpDeepTest.ktnew file mode 100644index 0000000000..0cd4a74adf--- /dev/null+++ b/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/StreamingPumpDeepTest.kt@@ -0,0 +1,170 @@+package com.vayunmathur.cast.tv.platform++import com.vayunmathur.cast.protocol.Crypto+import com.vayunmathur.cast.protocol.EncryptedFrame+import com.vayunmathur.cast.protocol.FrameId+import com.vayunmathur.cast.protocol.Negotiation+import com.vayunmathur.cast.protocol.RtpPacketizer+import com.vayunmathur.cast.protocol.SessionKeys+import com.vayunmathur.cast.protocol.StreamConfig+import com.vayunmathur.cast.protocol.StreamConstants+import com.vayunmathur.cast.protocol.StreamReady+import com.vayunmathur.cast.protocol.VideoCodec+import com.vayunmathur.cast.protocol.VideoCodecConfig+import java.net.DatagramPacket+import java.net.DatagramSocket+import java.net.InetAddress+import java.net.ServerSocket+import java.net.Socket+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.async+import kotlinx.coroutines.cancelAndJoin+import kotlinx.coroutines.delay+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.AfterTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * The media pump against fake decoders: frames flow from UDP datagrams through+ * the playout queues into the shadow codecs, the decoder is rebuilt across a+ * surface swap, and an AV1 session without its codec config fails by name.+ */+@RunWith(RobolectricTestRunner::class)+class StreamingPumpDeepTest {++    @AfterTest fun tearDown() {+        ReceiverController.detachSurface()+        ReceiverController.forgetPlayback()+        FakeDecoders.reset()+    }++    private fun channelPair(): Pair<ControlChannel, ControlChannel> {+        val server = ServerSocket(0)+        var accepted: Socket? = null+        val thread = Thread { accepted = server.accept() }+        thread.start()+        val client = Socket("127.0.0.1", server.localPort)+        thread.join(5_000)+        server.close()+        return ControlChannel(accepted!!) to ControlChannel(client)+    }++    private fun sendFrame(+        sender: DatagramSocket,+        port: Int,+        payloadType: Int,+        ssrc: Long,+        plain: ByteArray,+        key: ByteArray,+        ivMask: ByteArray,+    ) {+        val crypto = Crypto(key, ivMask)+        val frame = EncryptedFrame(FrameId(0), FrameId(0), 0L, true, crypto.crypt(FrameId(0), plain))+        for (packet in RtpPacketizer(payloadType, ssrc).packetize(frame)) {+            sender.send(DatagramPacket(packet, packet.size, InetAddress.getByName("127.0.0.1"), port))+        }+    }++    @Test fun pumpDecodesVideoAndAudioAndSurvivesSurfaceSwap() { runBlocking {+        FakeDecoders.install()+        val keys = SessionKeys.of(ByteArray(32) { 5 })+        val config = StreamConfig(+            width = 320, height = 240, frameRate = 30f, bitRate = 1_000_000,+            audio = true, video = true, audioSsrc = 1111, videoSsrc = 2222,+            videoCodec = VideoCodec.Hevc,+        )+        val socket = DatagramSocket(0)+        val ready = StreamReady(udpPort = socket.localPort, audioSsrc = 3333, videoSsrc = 4444)+        val negotiation = Negotiation.of(config, ready, keys)+        val (tvChannel, phoneChannel) = channelPair()+        val surface = TestSurface()+        ReceiverController.attachSurface(surface.surface)++        val job = async(Dispatchers.Default) { ReceiverController.pump(socket, negotiation, config, tvChannel) }+        delay(300)+        val sender = DatagramSocket()+        sendFrame(+            sender, socket.localPort, StreamConstants.VIDEO_PAYLOAD_TYPE, config.videoSsrc,+            ByteArray(64) { 3 }, keys.video.key, keys.video.ivMask,+        )+        sendFrame(+            sender, socket.localPort, StreamConstants.AUDIO_PAYLOAD_TYPE, config.audioSsrc,+            ByteArray(40) { 4 }, keys.audio.key, keys.audio.ivMask,+        )+        // Playout holds frames 150 ms; give the loop several passes over both.+        delay(900)++        // A panel-mode swap: surface goes away and a different one arrives.+        ReceiverController.detachSurface()+        delay(200)+        val replacement = TestSurface()+        ReceiverController.attachSurface(replacement.surface)+        delay(300)+        sendFrame(+            sender, socket.localPort, StreamConstants.VIDEO_PAYLOAD_TYPE, config.videoSsrc,+            ByteArray(64) { 6 }, keys.video.key, keys.video.ivMask,+        )+        delay(700)++        assertTrue(job.isActive, "pump should still be running with a decoder up")+        job.cancelAndJoin()+        sender.close()+        phoneChannel.close()+        surface.texture.release()+        replacement.texture.release()+        Unit+    } }++    @Test fun av1WithoutCodecConfigFailsByNameAndWithConfigStarts() { runBlocking {+        FakeDecoders.install()+        val keys = SessionKeys.of(ByteArray(32) { 6 })+        val config = StreamConfig(+            width = 320, height = 240, frameRate = 30f, bitRate = 1_000_000,+            audio = false, video = true, audioSsrc = 0, videoSsrc = 2222,+            videoCodec = VideoCodec.Av1,+        )+        // First: no config ever arrives, so the pump waits, then refuses by name.+        run {+            val socket = DatagramSocket(0)+            val ready = StreamReady(udpPort = socket.localPort, audioSsrc = 0, videoSsrc = 4444)+            val negotiation = Negotiation.of(config, ready, keys)+            val (tvChannel, phoneChannel) = channelPair()+            val surface = TestSurface()+            ReceiverController.attachSurface(surface.surface)+            val job = async(Dispatchers.Default) { ReceiverController.pump(socket, negotiation, config, tvChannel) }+            // The codec-config wait is five seconds; the pump must give up after it.+            val deadline = System.currentTimeMillis() + 12_000+            while (job.isActive && System.currentTimeMillis() < deadline) delay(200)+            assertTrue(!job.isActive, "pump should end when the codec config never arrives")+            job.join()+            assertEquals(+                ReceiverPhase.Failed(ReceiverFailure.MissingCodecConfig),+                ReceiverController.state.value.phase,+            )+            phoneChannel.close()+            surface.texture.release()+        }+        // Now hand the config over first: the decoder starts and the pump runs.+        ReceiverController.onVideoCodecConfig(+            VideoCodecConfig(csd = com.vayunmathur.cast.protocol.ProtocolBase64.encode(byteArrayOf(0x0a, 0x0e))),+            config,+        )+        val socket = DatagramSocket(0)+        val ready = StreamReady(udpPort = socket.localPort, audioSsrc = 0, videoSsrc = 4444)+        val negotiation = Negotiation.of(config, ready, keys)+        val (tvChannel, phoneChannel) = channelPair()+        val surface = TestSurface()+        ReceiverController.attachSurface(surface.surface)+        val job = async(Dispatchers.Default) { ReceiverController.pump(socket, negotiation, config, tvChannel) }+        delay(600)+        assertTrue(job.isActive, "pump should run once the AV1 decoder is up")+        job.cancelAndJoin()+        phoneChannel.close()+        surface.texture.release()+        Unit+    } }+}
cast/tv/src/test/java/com/vayunmathur/cast/tv/ui/OverlayDeepTest.kt
diff --git a/cast/tv/src/test/java/com/vayunmathur/cast/tv/ui/OverlayDeepTest.kt b/cast/tv/src/test/java/com/vayunmathur/cast/tv/ui/OverlayDeepTest.ktnew file mode 100644index 0000000000..25fe224f52--- /dev/null+++ b/cast/tv/src/test/java/com/vayunmathur/cast/tv/ui/OverlayDeepTest.kt@@ -0,0 +1,75 @@+package com.vayunmathur.cast.tv.ui++import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.ui.Modifier+import androidx.compose.ui.test.captureToImage+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onRoot+import com.vayunmathur.cast.protocol.NowPlaying+import com.vayunmathur.cast.protocol.PlaybackState+import com.vayunmathur.cast.tv.platform.PlaybackSnapshot+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import org.robolectric.annotation.GraphicsMode+import kotlin.test.Test++/** Transport overlay shapes: playing, paused, buffering, ended, scrubbing, live. */+@RunWith(RobolectricTestRunner::class)+@Config(application = android.app.Application::class, qualifiers = "w960dp-h540dp")+@GraphicsMode(GraphicsMode.Mode.NATIVE)+class OverlayDeepTest {++    @get:Rule val rule = createComposeRule()++    private fun snapshot(state: PlaybackState) = PlaybackSnapshot(state, System.currentTimeMillis())++    @Test fun overlayVariantsRender() {+        val variants = listOf(+            PlaybackState(30_000, 600_000, playing = true, buffering = false, hasNext = true, hasPrevious = true),+            PlaybackState(30_000, 600_000, playing = false, buffering = false),+            PlaybackState(30_000, 600_000, playing = false, buffering = true),+            PlaybackState(600_000, 600_000, playing = false, buffering = false, ended = true),+            PlaybackState(10_000, 0, playing = true, buffering = false), // live: no duration+        )+        val stateHolder = androidx.compose.runtime.mutableStateOf(snapshot(variants.first()))+        rule.setContent {+            CastTvTheme {+                TransportOverlay(+                    snapshot = stateHolder.value,+                    sourceName = "YouPipe",+                    nowPlaying = NowPlaying(resourceId = "r1", title = "Clip", author = "Channel"),+                    positionMs = { 30_000 },+                    scrubbing = false,+                    scrim = true,+                    modifier = Modifier.fillMaxSize(),+                )+            }+        }+        for (variant in variants) {+            stateHolder.value = snapshot(variant)+            rule.waitForIdle()+        }+        rule.onRoot().captureToImage()+    }++    @Test fun overlayWhileScrubbing() {+        rule.setContent {+            CastTvTheme {+                TransportOverlay(+                    snapshot = snapshot(PlaybackState(30_000, 600_000, playing = true, buffering = false)),+                    sourceName = "YouPipe",+                    nowPlaying = null,+                    positionMs = { 45_000 },+                    scrubbing = true,+                    scrim = false,+                    modifier = Modifier.fillMaxSize(),+                )+            }+        }+        rule.waitForIdle()+        rule.onRoot().captureToImage()+    }++}
cast/tv/src/test/java/com/vayunmathur/cast/tv/ui/PlaybackClockTest.kt
diff --git a/cast/tv/src/test/java/com/vayunmathur/cast/tv/ui/PlaybackClockTest.kt b/cast/tv/src/test/java/com/vayunmathur/cast/tv/ui/PlaybackClockTest.ktnew file mode 100644index 0000000000..1a71638293--- /dev/null+++ b/cast/tv/src/test/java/com/vayunmathur/cast/tv/ui/PlaybackClockTest.kt@@ -0,0 +1,39 @@+package com.vayunmathur.cast.tv.ui++import androidx.compose.ui.test.junit4.createComposeRule+import com.vayunmathur.cast.protocol.PlaybackState+import com.vayunmathur.cast.tv.platform.PlaybackSnapshot+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.Test+import kotlin.test.assertTrue++/**+ * PlaybackClock's frame loop: a playing snapshot's position extrapolates+ * forward, a paused one stays, and a scrub preview pins the position.+ */+@RunWith(RobolectricTestRunner::class)+@Config(application = android.app.Application::class, qualifiers = "w960dp-h540dp")+class PlaybackClockTest {++    @get:Rule val rule = createComposeRule()++    @Test fun clockStaysPutWhenPaused() {+        val snapshot = PlaybackSnapshot(+            PlaybackState(42_000, 600_000, playing = false, buffering = false),+            System.currentTimeMillis(),+        )+        val seen = mutableListOf<Long>()+        rule.setContent {+            CastTvTheme {+                PlaybackClock(snapshot = snapshot, scrubPreviewMs = null) { positionMs ->+                    seen += positionMs()+                }+            }+        }+        rule.waitForIdle()+        assertTrue(seen.isNotEmpty() && seen.all { it == 42_000L }, seen.toString())+    }+}
cast/tv/src/test/java/com/vayunmathur/cast/tv/ui/UiDeep2Test.kt
diff --git a/cast/tv/src/test/java/com/vayunmathur/cast/tv/ui/UiDeep2Test.kt b/cast/tv/src/test/java/com/vayunmathur/cast/tv/ui/UiDeep2Test.ktnew file mode 100644index 0000000000..a299cd37da--- /dev/null+++ b/cast/tv/src/test/java/com/vayunmathur/cast/tv/ui/UiDeep2Test.kt@@ -0,0 +1,117 @@+package com.vayunmathur.cast.tv.ui++import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.ui.Modifier+import androidx.compose.ui.test.captureToImage+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.onRoot+import androidx.compose.ui.test.performClick+import com.vayunmathur.cast.protocol.ContentSession+import com.vayunmathur.cast.protocol.LyricLine+import com.vayunmathur.cast.protocol.NowPlaying+import com.vayunmathur.cast.protocol.PlaybackState+import com.vayunmathur.cast.tv.platform.ArtworkFetcher+import com.vayunmathur.cast.tv.platform.PlaybackSnapshot+import com.vayunmathur.cast.tv.platform.ReceiverFailure+import com.vayunmathur.cast.tv.platform.ReceiverPhase+import com.vayunmathur.cast.tv.platform.ReceiverUiState+import kotlin.io.encoding.Base64+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import org.robolectric.annotation.GraphicsMode+import kotlin.test.Test++/** Failure screens, the network-blocked action, artwork loading, and the lyrics fade. */+@RunWith(RobolectricTestRunner::class)+@Config(application = android.app.Application::class, qualifiers = "w960dp-h540dp")+@GraphicsMode(GraphicsMode.Mode.NATIVE)+class UiDeep2Test {++    @get:Rule val rule = createComposeRule()++    private fun snap(pos: Long = 30_000) = PlaybackSnapshot(+        PlaybackState(pos, 600_000, playing = true, buffering = false, hasNext = true, hasPrevious = true),+        System.currentTimeMillis(),+    )++    @Test fun everyFailureRendersItsScreen() {+        val failureState = androidx.compose.runtime.mutableStateOf(ReceiverFailure.entries.first())+        rule.setContent {+            CastTvTheme { ReceiverContent(ReceiverUiState(phase = ReceiverPhase.Failed(failureState.value))) }+        }+        for (next in ReceiverFailure.entries) {+            failureState.value = next+            rule.waitForIdle()+        }+    }++    @Test fun networkBlockedButtonFiresSettingsIntent() {+        rule.setContent {+            CastTvTheme { ReceiverContent(ReceiverUiState(localNetworkBlocked = true)) }+        }+        rule.waitForIdle()+        rule.onNodeWithText("Open Settings", substring = true).performClick()+        rule.waitForIdle()+    }++    @Test fun lyricsFadeDrawsWithTimedLines() {+        val np = NowPlaying(+            resourceId = "r1", title = "Song",+            lyrics = (0..12).map { LyricLine(it * 10_000L, "lyric line number $it") },+        )+        rule.setContent {+            CastTvTheme {+                Lyrics(np, { 25_000 }, Modifier.fillMaxSize())+            }+        }+        rule.waitForIdle()+        // Forcing a draw runs the fading-edge mask over the column.+        rule.onRoot().captureToImage()+        rule.onNodeWithText("lyric line number 2").assertExists()+    }++    @Test fun lyricsPlainBlockDraws() {+        val np = NowPlaying(+            resourceId = "r1", title = "Song",+            plainLyrics = "all the words\nof the song\nin one block",+        )+        rule.setContent {+            CastTvTheme { Lyrics(np, { 0 }, Modifier.fillMaxSize()) }+        }+        rule.waitForIdle()+        rule.onRoot().captureToImage()+    }++    @Test fun nowPlayingFetchesArtworkThroughFetcher() {+        val fetcher = ArtworkFetcher(+            ContentSession(+                host = "127.0.0.1", port = 9,+                certificateFingerprint = Base64.encode(ByteArray(32) { 4 }),+                token = "tok", video = false,+            ),+        )+        val np = NowPlaying(+            resourceId = "r1", title = "Cover Song", author = "Artist",+            artworkResourceId = "cover-1",+        )+        rule.setContent {+            CastTvTheme { NowPlayingScreen(np, snap(), "YouPipe", { 30_000 }, fetcher) }+        }+        // The fetch fails soft (nothing listens on port 9) and the placeholder stays.+        Thread.sleep(500)+        rule.waitForIdle()+        rule.onNodeWithText("Cover Song").assertExists()+    }++    @Test fun nowPlayingWithoutArtworkResource() {+        val np = NowPlaying(resourceId = "r1", title = "No Cover", author = "Artist")+        rule.setContent {+            CastTvTheme { NowPlayingScreen(np, snap(), "YouPipe", { 30_000 }, null) }+        }+        rule.waitForIdle()+        rule.onNodeWithText("No Cover").assertExists()+    }+}