Modern Apps git

← Modern-Apps.git

sdk: add :sdk:cast for streaming app content to a TV

Commit
52a248ea2a013a7b8b77f68b66cecf0b617db237
Author
vayun-mathur <[email protected]>
When
2026-08-21 20:43 UTC (3 months ago)
Parents
0e693fe

Diff

sdk/cast/build.gradle.kts
diff --git a/sdk/cast/build.gradle.kts b/sdk/cast/build.gradle.ktsnew file mode 100644index 0000000000..6798ca51f6--- /dev/null+++ b/sdk/cast/build.gradle.kts@@ -0,0 +1,3 @@+plugins {+    id("common-conventions-library")+}
sdk/cast/src/main/AndroidManifest.xml
diff --git a/sdk/cast/src/main/AndroidManifest.xml b/sdk/cast/src/main/AndroidManifest.xmlnew file mode 100644index 0000000000..164948c6f4--- /dev/null+++ b/sdk/cast/src/main/AndroidManifest.xml@@ -0,0 +1,12 @@+<?xml version="1.0" encoding="utf-8"?>+<manifest xmlns:android="http://schemas.android.com/apk/res/android">++    <!-- CastContract.PERMISSION is declared by each consuming app, not here. :library depends on+         :sdk:games and every app depends on :library, so a uses-permission in an SDK manifest ends+         up requested by all ~50 apps in the repo. A <queries> entry is different: it only makes the+         Cast package visible to a resolve, which is exactly what CastClient.support() needs. -->++    <queries>+        <package android:name="com.vayunmathur.cast" />+    </queries>+</manifest>
sdk/cast/src/main/java/com/vayunmathur/sdk/cast/CastClient.kt
diff --git a/sdk/cast/src/main/java/com/vayunmathur/sdk/cast/CastClient.kt b/sdk/cast/src/main/java/com/vayunmathur/sdk/cast/CastClient.ktnew file mode 100644index 0000000000..42cd98fb3c--- /dev/null+++ b/sdk/cast/src/main/java/com/vayunmathur/sdk/cast/CastClient.kt@@ -0,0 +1,318 @@+package com.vayunmathur.sdk.cast++import android.content.ComponentName+import android.content.Context+import android.content.Intent+import android.content.ServiceConnection+import android.os.Bundle+import android.os.Handler+import android.os.IBinder+import android.os.Looper+import android.os.Message+import android.os.Messenger+import android.os.ParcelFileDescriptor+import android.os.RemoteException+import android.view.Surface+import kotlinx.coroutines.suspendCancellableCoroutine+import kotlinx.coroutines.withTimeout+import kotlin.coroutines.resume+import kotlin.coroutines.resumeWithException++/**+ * Puts this app's content on a TV, through the installed Cast app.+ *+ * Hold one per casting screen, [openSession] once a TV is connected (see [CastPickerContract]), draw+ * into [Session.surface], and [close] when done. Nothing here touches the network: Cast owns the+ * sockets, the pairing and the encoders, which is why a consumer needs no network permission and why+ * one pairing per TV serves the whole device.+ *+ * **Deliberately not fail-soft, unlike `GameHubClient`.** A hub write that quietly does nothing+ * loses one achievement; a streaming call that quietly does nothing leaves the caller rendering into+ * a surface that goes nowhere, with the local player hidden behind a "Playing on TV" panel, and no+ * way to find out. So every failure is a typed exception - probe with [support] first if a soft path+ * is wanted.+ *+ * The binding *is* the session's lifetime. If this process is killed mid-cast the binding drops and+ * Cast tears the session down, which a request/response IPC would need a death token bolted on to+ * notice.+ */+class CastClient(context: Context) {++    private val appContext = context.applicationContext++    /** Result of the fast, synchronous capability probe. */+    enum class Support {+        /** Cast is not installed; offer its store listing. */+        NOT_INSTALLED,++        /** Installed but older than [CastContract.MIN_CAST_VERSION_CODE]. */+        NEEDS_UPDATE,++        /** Installed and recent enough to serve SDK sessions. */+        READY,+    }++    /** A live session: where to draw, where to write PCM, and what Cast actually agreed. */+    class Session(+        /**+         * The encoder's input surface. Everything drawn here is encoded and sent.+         *+         * Owned by Cast: do not release it. Releasing the client-side copy is what would break the+         * *next* session rather than this one, which is the kind of bug that only shows up on a+         * second consecutive cast.+         */+        val surface: Surface,+        /**+         * Write 48 kHz stereo 16-bit little-endian PCM here, or null if audio was not asked for or+         * could not be started. Null is not a session failure - the video is still going out.+         */+        val audio: ParcelFileDescriptor?,+        /** The granted frame size, clamped to the TV and to this phone's encoder. Lay out for this. */+        val width: Int,+        val height: Int,+        val frameRate: Int,+        /** For a "Playing on <name>" panel where the video used to be. */+        val receiverName: String,+    )++    /**+     * Called when Cast ends the session on its own - the TV went away, screen mirroring took the+     * slot - with one of [CastContract]'s `REASON_` values. Not called for a [close].+     */+    var onEnded: ((Int) -> Unit)? = null++    private var service: Messenger? = null+    private var bound = false++    /** Set once [MSG_SESSION_READY][CastContract.MSG_SESSION_READY] has been answered. */+    private var open = false++    /** Non-null only while [openSession] is waiting, so a failure can be reported to it. */+    private var pending: ((Result<Session>) -> Unit)? = null++    private val incoming = Messenger(+        Handler(Looper.getMainLooper()) { msg ->+            when (msg.what) {+                CastContract.MSG_SESSION_READY -> {+                    onReady(msg.data)+                    true+                }+                CastContract.MSG_SESSION_ENDED -> {+                    val reason = msg.data?.getInt(CastContract.KEY_END_REASON)+                        ?: CastContract.REASON_FAILED+                    onSessionEnded(reason)+                    true+                }+                else -> false+            }+        },+    )++    private val connection = object : ServiceConnection {+        override fun onServiceConnected(name: ComponentName?, binder: IBinder?) {+            service = Messenger(binder)+            sendOpen()+        }++        override fun onServiceDisconnected(name: ComponentName?) {+            service = null+            // The Cast process died. Nothing is being encoded any more, so the caller has to be told+            // even though it never asked for this.+            onSessionEnded(CastContract.REASON_RECEIVER_GONE)+        }+    }++    /** What the caller asked for, replayed in [sendOpen] once the binding lands. */+    private var requestedWidth = 0+    private var requestedHeight = 0+    private var requestedAudio = false++    /**+     * Whether Cast can serve a session, from the installed package's `versionCode` alone.+     *+     * No IPC and no binding, so "needs update" is instant rather than a timeout.+     */+    fun support(): Support = supportFor(installedVersionCode())++    /** null when Cast is absent. minSdk 31, so `longVersionCode` is always available. */+    private fun installedVersionCode(): Long? = try {+        appContext.packageManager.getPackageInfo(CastContract.CAST_PACKAGE, 0).longVersionCode+    } catch (_: Exception) {+        null+    }++    /**+     * Bind Cast and open a session for a [width] x [height] frame.+     *+     * Requires a TV already connected, which is what [CastPickerContract] is for. The returned+     * geometry is what Cast agreed with that TV and may be smaller than requested.+     *+     * @throws CastNotInstalledException Cast is absent.+     * @throws CastNeedsUpdateException Cast is too old to have the service.+     * @throws CastPermissionException this app is not signed with the Modern Apps key.+     * @throws CastNoSessionException no TV is connected.+     * @throws CastSessionFailedException Cast could not start the stream.+     */+    suspend fun openSession(width: Int, height: Int, wantAudio: Boolean): Session {+        when (support()) {+            Support.NOT_INSTALLED -> throw CastNotInstalledException()+            Support.NEEDS_UPDATE -> throw CastNeedsUpdateException()+            Support.READY -> {}+        }+        requestedWidth = width+        requestedHeight = height+        requestedAudio = wantAudio+        return withTimeout(OPEN_TIMEOUT_MS) {+            suspendCancellableCoroutine { continuation ->+                pending = { result ->+                    pending = null+                    result+                        .onSuccess { continuation.resume(it) }+                        .onFailure { continuation.resumeWithException(it) }+                }+                // Includes the timeout: a binding left up after giving up would keep Cast alive and+                // hold a session nothing is drawing into.+                continuation.invokeOnCancellation { close() }+                val intent = Intent().setComponent(+                    ComponentName(CastContract.CAST_PACKAGE, CastContract.SERVICE_CLASS),+                )+                bound = try {+                    appContext.bindService(intent, connection, Context.BIND_AUTO_CREATE)+                } catch (_: SecurityException) {+                    finish(Result.failure(CastPermissionException()))+                    return@suspendCancellableCoroutine+                }+                if (!bound) {+                    // Resolved (support() said READY) but would not bind. The permission is the only+                    // thing that refuses a resolvable component.+                    finish(Result.failure(CastPermissionException()))+                }+            }+        }+    }++    /**+     * End the session and unbind. Idempotent, and safe if [openSession] never succeeded.+     *+     * [onEnded] is not called: the caller asked for this and already knows.+     */+    fun close() {+        onEnded = null+        pending = null+        if (open) {+            try {+                service?.send(Message.obtain(null, CastContract.MSG_CLOSE_SESSION))+            } catch (_: RemoteException) {+                // Already gone; unbinding is all that is left to do.+            }+        }+        open = false+        if (bound) {+            try {+                appContext.unbindService(connection)+            } catch (_: IllegalArgumentException) {+                // Never actually bound.+            }+            bound = false+        }+        service = null+    }++    private fun sendOpen() {+        val remote = service ?: return+        val message = Message.obtain(null, CastContract.MSG_OPEN_SESSION).apply {+            replyTo = incoming+            data = Bundle().apply {+                putInt(CastContract.KEY_WIDTH, requestedWidth)+                putInt(CastContract.KEY_HEIGHT, requestedHeight)+                putBoolean(CastContract.KEY_WANT_AUDIO, requestedAudio)+            }+        }+        try {+            remote.send(message)+        } catch (_: RemoteException) {+            finish(Result.failure(CastSessionFailedException(CastContract.REASON_FAILED)))+        }+    }++    private fun onReady(data: Bundle?) {+        @Suppress("DEPRECATION")+        val surface = data?.getParcelable(CastContract.KEY_SURFACE) as? Surface+        if (surface == null) {+            finish(Result.failure(CastSessionFailedException(CastContract.REASON_FAILED)))+            return+        }+        @Suppress("DEPRECATION")+        val audio = data.getParcelable(CastContract.KEY_AUDIO_FD) as? ParcelFileDescriptor+        open = true+        finish(+            Result.success(+                Session(+                    surface = surface,+                    audio = audio,+                    width = data.getInt(CastContract.KEY_GRANTED_WIDTH, requestedWidth),+                    height = data.getInt(CastContract.KEY_GRANTED_HEIGHT, requestedHeight),+                    frameRate = data.getInt(CastContract.KEY_GRANTED_FRAME_RATE, DEFAULT_FRAME_RATE),+                    receiverName = data.getString(CastContract.KEY_RECEIVER_NAME).orEmpty(),+                ),+            ),+        )+    }++    private fun onSessionEnded(reason: Int) {+        val waiting = pending+        open = false+        if (waiting != null) {+            // Ended before it ever started, so this is [openSession]'s failure rather than a+            // mid-cast teardown the caller has to react to.+            waiting(+                Result.failure(+                    when (reason) {+                        CastContract.REASON_NO_SESSION -> CastNoSessionException()+                        else -> CastSessionFailedException(reason)+                    },+                ),+            )+            return+        }+        onEnded?.invoke(reason)+    }++    /** Hand one outcome to a waiting [openSession], unbinding first if it was a failure. */+    private fun finish(result: Result<Session>) {+        if (result.isFailure) {+            // Nothing is going to arrive on this binding, and leaving it up would keep Cast alive.+            if (bound) {+                try {+                    appContext.unbindService(connection)+                } catch (_: IllegalArgumentException) {+                }+                bound = false+            }+            service = null+        }+        pending?.invoke(result)+    }++    internal companion object {+        /**+         * The whole of [support]'s decision, separated from `PackageManager` so it is provable on+         * the JVM: the three branches are the difference between "install Cast", "update Cast" and+         * "go", and getting the boundary wrong is silent either way.+         */+        internal fun supportFor(versionCode: Long?): Support = when {+            versionCode == null -> Support.NOT_INSTALLED+            versionCode >= CastContract.MIN_CAST_VERSION_CODE -> Support.READY+            else -> Support.NEEDS_UPDATE+        }++        /**+         * Opening involves a `STREAM_CONFIG`/`STREAM_READY` round trip to the TV over the LAN and+         * starting a hardware encoder, so it is not instant - but it is also not minutes, and a+         * caller left waiting is a caller showing a spinner over a video that could be playing.+         */+        const val OPEN_TIMEOUT_MS = 20_000L++        const val DEFAULT_FRAME_RATE = 30+    }+}
sdk/cast/src/main/java/com/vayunmathur/sdk/cast/CastContract.kt
diff --git a/sdk/cast/src/main/java/com/vayunmathur/sdk/cast/CastContract.kt b/sdk/cast/src/main/java/com/vayunmathur/sdk/cast/CastContract.ktnew file mode 100644index 0000000000..08565d026b--- /dev/null+++ b/sdk/cast/src/main/java/com/vayunmathur/sdk/cast/CastContract.kt@@ -0,0 +1,159 @@+package com.vayunmathur.sdk.cast++/**+ * The wire contract between an app that wants its content on a TV and the installed Cast app.+ *+ * Constants only, no framework logic, so both halves can compile against the same names rather than+ * against a byte-for-byte copy of them - which is the one thing `FamilyLocationProtocol` gets wrong+ * by living twice. `GameHubContract` is the shape this follows.+ *+ * **This is not a streaming API.** The SDK owns no sockets, no encoders and no crypto: it hands over+ * a size and gets back a [android.view.Surface] to draw into and a pipe to write PCM to, and Cast does+ * everything from there. That is what makes one pairing per TV serve every app on the device, and why+ * a consumer needs no network permission at all.+ *+ * The sequence, in the order it happens:+ *+ * ```+ * app   launch the picker Activity for result ─►   user picks a TV, pairs if needed+ *                                    ◄──  RESULT_OK+ *       bind the service, MSG_OPEN_SESSION ─►     (width, height, wantAudio)+ *                                    ◄──  MSG_SESSION_READY (Surface, audio pipe, granted size)+ *       … render into the Surface, write PCM into the pipe …+ *       unbind, or MSG_CLOSE_SESSION      ─►+ *                                    ◄──  MSG_SESSION_ENDED (reason)+ * ```+ */+object CastContract {++    /** The app that owns the sockets, the pairing and the encoders. */+    const val CAST_PACKAGE = "com.vayunmathur.cast"++    /**+     * Class names rather than a compile-time dependency on `:cast`: an SDK that made every consumer+     * pull in the whole Cast app would defeat the point of brokering.+     */+    const val PICKER_ACTIVITY = "$CAST_PACKAGE.platform.CastPickerActivity"+    const val SERVICE_CLASS = "$CAST_PACKAGE.service.ContentCastService"++    /**+     * Signature-level, so only apps signed with the Modern Apps key can bind.+     *+     * Worth being honest about what that does and does not buy: it means any first-party app can+     * stream, and nothing narrower is available to a `Messenger` service, because `Message` dispatch+     * goes through a `Handler` and the Binder calling identity is gone by the time the handler runs.+     * The sending app's *name* is therefore never taken from the app - see [KEY_GRANTED_WIDTH]'s+     * neighbours: there is no app-label key here at all. Cast resolves the label from the+     * `callingPackage` the framework attaches to the picker Activity.+     */+    const val PERMISSION = "com.vayunmathur.cast.permission.STREAM_CONTENT"++    /**+     * The lowest Cast `versionCode` that serves SDK sessions.+     *+     * Must stay in lockstep with the root `version.txt` value at the build that first shipped+     * [SERVICE_CLASS]. An older Cast has no such service, so binding would fail with nothing to say+     * why; probing the version code first is what turns that into an actionable "update Cast".+     */+    const val MIN_CAST_VERSION_CODE = 20260816L++    // ---- client → service ----++    /**+     * Open a session. Carries [KEY_WIDTH], [KEY_HEIGHT] and [KEY_WANT_AUDIO], and its `replyTo` is+     * where [MSG_SESSION_READY] and [MSG_SESSION_ENDED] are sent.+     */+    const val MSG_OPEN_SESSION = 1++    /**+     * End the session without unbinding.+     *+     * Unbinding ends it too - that is the point of a bound service, and it is what covers the client+     * being killed - so this exists only for an app that wants to stop casting and keep the binding.+     */+    const val MSG_CLOSE_SESSION = 2++    // ---- service → client ----++    /**+     * The session is live. Carries [KEY_SURFACE], optionally [KEY_AUDIO_FD], and the granted+     * geometry.+     */+    const val MSG_SESSION_READY = 3++    /** The session is over, for the reason in [KEY_END_REASON]. The `Surface` is invalid from here. */+    const val MSG_SESSION_ENDED = 4++    // ---- MSG_OPEN_SESSION payload ----++    /** Requested frame width in pixels. Clamped; read the granted size back, do not assume it. */+    const val KEY_WIDTH = "width"+    const val KEY_HEIGHT = "height"++    /** Whether the app intends to write PCM. False means video only and no pipe is created. */+    const val KEY_WANT_AUDIO = "wantAudio"++    // ---- MSG_SESSION_READY payload ----++    /**+     * The encoder's input surface, as a `Parcelable`.+     *+     * What the app draws into: a `MediaCodec` input surface, so everything rendered to it is encoded+     * and sent. The app must not release it - Cast owns it, and releasing it from the client side is+     * what would break the *next* session rather than this one.+     */+    const val KEY_SURFACE = "surface"++    /**+     * The write end of a pipe for PCM, present only when [KEY_WANT_AUDIO] was set and audio started.+     *+     * A pipe rather than messages because 48 kHz stereo 16-bit is ~192 KB/s: as `Messenger` messages+     * that is fifty Binder transactions a second competing with everything else on the binder+     * thread. Absent means audio was asked for and could not be provided; the video session is still+     * live, so a caller should keep playing rather than treat it as a failure.+     *+     * Format is fixed and not negotiated: [AUDIO_SAMPLE_RATE], [AUDIO_CHANNELS], 16-bit+     * little-endian, interleaved.+     */+    const val KEY_AUDIO_FD = "audioFd"++    /**+     * What Cast actually agreed with the TV, which is not necessarily what was asked for.+     *+     * Clamped to the TV's reported decoder limits and to what this phone's encoder will accept. An+     * app that laid out for the size it requested would be stretched, so this is returned rather+     * than left to be assumed.+     */+    const val KEY_GRANTED_WIDTH = "grantedWidth"+    const val KEY_GRANTED_HEIGHT = "grantedHeight"+    const val KEY_GRANTED_FRAME_RATE = "grantedFrameRate"++    /** The TV's name, for a "Playing on <TV>" panel where the video used to be. */+    const val KEY_RECEIVER_NAME = "receiverName"++    // ---- MSG_SESSION_ENDED payload ----++    /** One of the `REASON_` constants. */+    const val KEY_END_REASON = "endReason"++    /** The app asked, via [MSG_CLOSE_SESSION] or by unbinding. */+    const val REASON_CLIENT_CLOSED = 0++    /** No TV was connected, or the picker was never completed. */+    const val REASON_NO_SESSION = 1++    /** The TV went away, or the control channel closed. */+    const val REASON_RECEIVER_GONE = 2++    /** Screen mirroring, or another app's session, took the single session slot. */+    const val REASON_PREEMPTED = 3++    /** The encoder or the stream negotiation failed. */+    const val REASON_FAILED = 4++    // ---- the fixed audio format ----++    /** Matches the RTP timebase Cast negotiates; resampling here would only add latency. */+    const val AUDIO_SAMPLE_RATE = 48_000+    const val AUDIO_CHANNELS = 2+}
sdk/cast/src/main/java/com/vayunmathur/sdk/cast/CastPickerContract.kt
diff --git a/sdk/cast/src/main/java/com/vayunmathur/sdk/cast/CastPickerContract.kt b/sdk/cast/src/main/java/com/vayunmathur/sdk/cast/CastPickerContract.ktnew file mode 100644index 0000000000..b55fd3dddb--- /dev/null+++ b/sdk/cast/src/main/java/com/vayunmathur/sdk/cast/CastPickerContract.kt@@ -0,0 +1,31 @@+package com.vayunmathur.sdk.cast++import android.app.Activity+import android.content.ComponentName+import android.content.Context+import android.content.Intent+import androidx.activity.result.contract.ActivityResultContract++/**+ * Launch the Cast app's TV picker and find out whether a TV ended up connected.+ *+ * An [ActivityResultContract] rather than a plain intent helper for two reasons. The obvious one is+ * that a Compose caller then uses `rememberLauncherForActivityResult` and gets the result without an+ * `onActivityResult` override. The load-bearing one is that **launching for a result is what gives+ * Cast a `callingPackage`**: that is the identity the framework establishes, and it is the only+ * trustworthy source for "Receiving from YouPipe" on the TV. A self-reported app name would be a lie+ * an app could tell, so the SDK never sends one.+ *+ * `true` means a TV is connected and [CastClient.openSession] will work; `false` means the user+ * backed out, or pairing failed, and nothing should change in the calling app.+ */+class CastPickerContract : ActivityResultContract<Unit, Boolean>() {++    override fun createIntent(context: Context, input: Unit): Intent =+        Intent().setComponent(+            ComponentName(CastContract.CAST_PACKAGE, CastContract.PICKER_ACTIVITY),+        )++    override fun parseResult(resultCode: Int, intent: Intent?): Boolean =+        resultCode == Activity.RESULT_OK+}
sdk/cast/src/main/java/com/vayunmathur/sdk/cast/Exceptions.kt
diff --git a/sdk/cast/src/main/java/com/vayunmathur/sdk/cast/Exceptions.kt b/sdk/cast/src/main/java/com/vayunmathur/sdk/cast/Exceptions.ktnew file mode 100644index 0000000000..99680b73cf--- /dev/null+++ b/sdk/cast/src/main/java/com/vayunmathur/sdk/cast/Exceptions.kt@@ -0,0 +1,27 @@+package com.vayunmathur.sdk.cast++/** Anything the SDK refuses outright. */+open class CastException(message: String) : Exception(message)++/** The Cast app is not installed, so there is nothing to broker through. */+class CastNotInstalledException :+    CastException("MA Cast is not installed")++/** Cast is installed but predates [CastContract.MIN_CAST_VERSION_CODE]. */+class CastNeedsUpdateException :+    CastException("MA Cast is too old to stream app content")++/**+ * The permission was refused, which for a signature permission means the caller is not signed with+ * the Modern Apps key.+ */+class CastPermissionException :+    CastException("Not permitted to bind the Cast content service")++/** No TV is connected. The picker has to be launched and completed first. */+class CastNoSessionException :+    CastException("No TV session; launch the picker first")++/** Cast could not start a stream - negotiation or the encoder failed. */+class CastSessionFailedException(reason: Int) :+    CastException("Cast could not start a session (reason $reason)")
sdk/cast/src/test/java/com/vayunmathur/sdk/cast/CastContractTest.kt
diff --git a/sdk/cast/src/test/java/com/vayunmathur/sdk/cast/CastContractTest.kt b/sdk/cast/src/test/java/com/vayunmathur/sdk/cast/CastContractTest.ktnew file mode 100644index 0000000000..a1c8bd8998--- /dev/null+++ b/sdk/cast/src/test/java/com/vayunmathur/sdk/cast/CastContractTest.kt@@ -0,0 +1,121 @@+package com.vayunmathur.sdk.cast++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * What can be proved without two devices.+ *+ * The `Surface`-over-`Messenger` hop cannot be reached from a JVM test, and neither can the+ * encoder - so this covers the two things that *can* silently disagree and would be invisible on+ * hardware: the message codes and Bundle keys both halves index by, and the version boundary that+ * decides between "install Cast", "update Cast" and "go".+ */+class CastContractTest {++    @Test+    fun `the class names Cast is addressed by live under the Cast package`() {+        // Built by string concatenation, so a typo here is a ComponentName that resolves to nothing+        // and a bindService that returns false with no explanation.+        assertTrue(CastContract.PICKER_ACTIVITY.startsWith("${CastContract.CAST_PACKAGE}."))+        assertTrue(CastContract.SERVICE_CLASS.startsWith("${CastContract.CAST_PACKAGE}."))+        assertEquals("com.vayunmathur.cast.platform.CastPickerActivity", CastContract.PICKER_ACTIVITY)+        assertEquals("com.vayunmathur.cast.service.ContentCastService", CastContract.SERVICE_CLASS)+    }++    @Test+    fun `the permission is namespaced to Cast, so Cast is what declares it`() {+        // A consumer declares uses-permission against this exact string; a mismatch is a+        // SecurityException at bind time and nothing earlier.+        assertEquals("com.vayunmathur.cast.permission.STREAM_CONTENT", CastContract.PERMISSION)+    }++    @Test+    fun `no two message codes collide`() {+        val codes = listOf(+            CastContract.MSG_OPEN_SESSION,+            CastContract.MSG_CLOSE_SESSION,+            CastContract.MSG_SESSION_READY,+            CastContract.MSG_SESSION_ENDED,+        )+        assertEquals(codes.size, codes.toSet().size, "two Messenger `what` codes are the same")+    }++    @Test+    fun `no two bundle keys collide`() {+        // MSG_SESSION_READY carries the granted geometry, the Surface and the pipe in one Bundle, so+        // a duplicated key would silently overwrite one of them.+        val keys = listOf(+            CastContract.KEY_WIDTH,+            CastContract.KEY_HEIGHT,+            CastContract.KEY_WANT_AUDIO,+            CastContract.KEY_SURFACE,+            CastContract.KEY_AUDIO_FD,+            CastContract.KEY_GRANTED_WIDTH,+            CastContract.KEY_GRANTED_HEIGHT,+            CastContract.KEY_GRANTED_FRAME_RATE,+            CastContract.KEY_RECEIVER_NAME,+            CastContract.KEY_END_REASON,+        )+        assertEquals(keys.size, keys.toSet().size, "two Bundle keys are the same string")+        assertFalse(keys.any { it.isBlank() })+    }++    @Test+    fun `the requested and granted geometry keys are different`() {+        // They are written into the same conversation in opposite directions. If they were the same+        // strings the granted size would look like the requested one and clamping would appear to+        // work while doing nothing.+        assertTrue(CastContract.KEY_WIDTH != CastContract.KEY_GRANTED_WIDTH)+        assertTrue(CastContract.KEY_HEIGHT != CastContract.KEY_GRANTED_HEIGHT)+    }++    @Test+    fun `no two end reasons collide`() {+        val reasons = listOf(+            CastContract.REASON_CLIENT_CLOSED,+            CastContract.REASON_NO_SESSION,+            CastContract.REASON_RECEIVER_GONE,+            CastContract.REASON_PREEMPTED,+            CastContract.REASON_FAILED,+        )+        assertEquals(reasons.size, reasons.toSet().size, "two end reasons are the same int")+    }++    @Test+    fun `the audio format the pipe expects is the one the RTP timebase uses`() {+        assertEquals(48_000, CastContract.AUDIO_SAMPLE_RATE)+        assertEquals(2, CastContract.AUDIO_CHANNELS)+    }++    // ---- the capability probe ----++    @Test+    fun `an absent Cast is NOT_INSTALLED`() {+        assertEquals(CastClient.Support.NOT_INSTALLED, CastClient.supportFor(null))+    }++    @Test+    fun `a Cast older than the minimum needs an update`() {+        assertEquals(+            CastClient.Support.NEEDS_UPDATE,+            CastClient.supportFor(CastContract.MIN_CAST_VERSION_CODE - 1),+        )+    }++    @Test+    fun `the minimum version itself is ready, not one past it`() {+        // An off-by-one here would tell every user of the build that first shipped the service to go+        // and update it, with no update to find.+        assertEquals(+            CastClient.Support.READY,+            CastClient.supportFor(CastContract.MIN_CAST_VERSION_CODE),+        )+        assertEquals(+            CastClient.Support.READY,+            CastClient.supportFor(CastContract.MIN_CAST_VERSION_CODE + 1),+        )+    }+}
settings.gradle.kts
diff --git a/settings.gradle.kts b/settings.gradle.ktsindex a2920cc7c4..1f8b8de283 100644--- a/settings.gradle.kts+++ b/settings.gradle.kts@@ -72,6 +72,7 @@ include(":weather") include(":camera") include(":sdk:openassistant") include(":sdk:games")+include(":sdk:cast") include(":things") include(":office") include(":tools:holidaygen")