Modern Apps git

← Modern-Apps.git

cast: add CastV2 media casting and mirroring app-id spike

Commit
b9e34ab6d28b0ee23c2643802ffe013baa773caf
Author
vayun-mathur <[email protected]>
When
2026-08-21 06:01 UTC (3 months ago)
Parents
aa42c75

Diff

README.md
diff --git a/README.md b/README.mdindex df29aca42d..dc442801a1 100644--- a/README.md+++ b/README.md@@ -43,6 +43,7 @@ Though some apps may have exceptions, generally a 64-bit device running at least | **Calculator** | [Homepage](https://ma.vayunmathur.com/apps/calculator) | [![MA Repo](https://img.shields.io/badge/MA_Repo-Download-green?logo=f-droid&style=flat-square)](https://f-droid.org/packages/com.vayunmathur.calculator/) | [![Obtainium](https://img.shields.io/badge/Obtainium-Download-purple?style=flat-square)](https://api.vayunmathur.com/obtainium-link?name=Calculator&packageName=com.vayunmathur.calculator&apk=calculator-release.apk) | | **Calendar** | [Homepage](https://ma.vayunmathur.com/apps/calendar) | [![MA Repo](https://img.shields.io/badge/MA_Repo-Download-green?logo=f-droid&style=flat-square)](https://f-droid.org/packages/com.vayunmathur.calendar/) | [![Obtainium](https://img.shields.io/badge/Obtainium-Download-purple?style=flat-square)](https://api.vayunmathur.com/obtainium-link?name=Calendar&packageName=com.vayunmathur.calendar&apk=calendar-release.apk) | | **Camera** | [Homepage](https://ma.vayunmathur.com/apps/camera) | [![MA Repo](https://img.shields.io/badge/MA_Repo-Download-green?logo=f-droid&style=flat-square)](https://f-droid.org/packages/com.vayunmathur.camera/) | [![Obtainium](https://img.shields.io/badge/Obtainium-Download-purple?style=flat-square)](https://api.vayunmathur.com/obtainium-link?name=Camera&packageName=com.vayunmathur.camera&apk=camera-release.apk) |+| **Cast** | [Homepage](https://ma.vayunmathur.com/apps/cast) | In Progress | In Progress | | **Clock** | [Homepage](https://ma.vayunmathur.com/apps/clock) | [![MA Repo](https://img.shields.io/badge/MA_Repo-Download-green?logo=f-droid&style=flat-square)](https://f-droid.org/packages/com.vayunmathur.clock/) | [![Obtainium](https://img.shields.io/badge/Obtainium-Download-purple?style=flat-square)](https://api.vayunmathur.com/obtainium-link?name=Clock&packageName=com.vayunmathur.clock&apk=clock-release.apk) | | **Code** | [Homepage](https://ma.vayunmathur.com/apps/code) | [![MA Repo](https://img.shields.io/badge/MA_Repo-Download-green?logo=f-droid&style=flat-square)](https://f-droid.org/packages/com.vayunmathur.code/) | [![Obtainium](https://img.shields.io/badge/Obtainium-Download-purple?style=flat-square)](https://api.vayunmathur.com/obtainium-link?name=Code&packageName=com.vayunmathur.code&apk=code-release.apk) | | **Contacts** | [Homepage](https://ma.vayunmathur.com/apps/contacts) | [![MA Repo](https://img.shields.io/badge/MA_Repo-Download-green?logo=f-droid&style=flat-square)](https://f-droid.org/packages/com.vayunmathur.contacts/) | [![Obtainium](https://img.shields.io/badge/Obtainium-Download-purple?style=flat-square)](https://api.vayunmathur.com/obtainium-link?name=Contacts&packageName=com.vayunmathur.contacts&apk=contacts-release.apk) |
cast/build.gradle.kts
diff --git a/cast/build.gradle.kts b/cast/build.gradle.ktsnew file mode 100644index 0000000000..0346dd8885--- /dev/null+++ b/cast/build.gradle.kts@@ -0,0 +1,19 @@+plugins {+    id("common-conventions-app")+    id("common-conventions-preview-metadata")+}++launcherIcon {+    symbol = "cast"+}++android {+    defaultConfig {+        applicationId = "com.vayunmathur.cast"+    }+}++// No Rust crate, unlike :share. CastV2 needs a TLS client socket and the root Cargo.toml+// forbids network stacks in Rust, so the socket has to be Kotlin either way - and once it+// is, CastMessage's seven scalar protobuf fields are cheaper to hand-roll in Kotlin than+// to bridge over JNI. See cast/src/main/java/.../network/CastMessageCodec.kt.
cast/src/main/AndroidManifest.xml
diff --git a/cast/src/main/AndroidManifest.xml b/cast/src/main/AndroidManifest.xmlnew file mode 100644index 0000000000..c9824c14d8--- /dev/null+++ b/cast/src/main/AndroidManifest.xml@@ -0,0 +1,69 @@+<?xml version="1.0" encoding="utf-8"?>+<manifest xmlns:android="http://schemas.android.com/apk/res/android">++    <!-- Google Cast (CastV2) without Play Services or the Cast SDK: mDNS discovery of+         _googlecast._tcp, a TLS socket to port 8009, and a local HTTP server so the+         receiver can fetch a file the user picked. -->+    <uses-permission android:name="android.permission.INTERNET" />+    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />+    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />+    <!-- Local Network Protections (Android 16+): without this NsdManager.discoverServices+         throws SecurityException and every LAN socket is blocked, which would make the+         device list silently empty and the cast socket unopenable. Everything this app+         does is on the LAN, so it is not optional. -->+    <uses-permission android:name="android.permission.ACCESS_LOCAL_NETWORK" />++    <!-- mediaPlayback rather than connectedDevice: the session this service holds open is a+         playback session on the receiver, which is what Android's own docs list this type+         for. Not dataSync - Android 15 caps that at 6 cumulative hours per 24h and then+         calls onTimeout(), which for a long film would stop the service mid-playback (see+         :vpn's manifest for the same reasoning first-hand). -->+    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />+    <uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />+    <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />++    <!-- Deliberately NO storage or media permissions. Local files are picked with+         ACTION_OPEN_DOCUMENT or arrive as a share-sheet URI, and both grant access to+         exactly the URI the user chose; the file is read through+         ContentResolver.openFileDescriptor. -->++    <uses-feature android:name="android.hardware.wifi" android:required="false" />++    <application+        android:allowBackup="true"+        android:dataExtractionRules="@xml/data_extraction_rules"+        android:icon="@mipmap/ic_launcher"+        android:label="@string/app_name"+        android:roundIcon="@mipmap/ic_launcher"+        android:supportsRtl="true"+        android:theme="@style/Theme.General">+        <activity+            android:name=".MainActivity"+            android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode"+            android:exported="true"+            android:launchMode="singleTop"+            android:theme="@style/Theme.General">+            <intent-filter>+                <action android:name="android.intent.action.MAIN" />+                <category android:name="android.intent.category.LAUNCHER" />+            </intent-filter>+            <!-- The share sheet's target. singleTop plus onNewIntent, rather than a second+                 activity: the device picker is the whole app, so there is nothing a separate+                 popup would show that this does not. -->+            <intent-filter>+                <action android:name="android.intent.action.SEND" />+                <category android:name="android.intent.category.DEFAULT" />+                <data android:mimeType="video/*" />+                <data android:mimeType="audio/*" />+                <data android:mimeType="image/*" />+            </intent-filter>+        </activity>++        <!-- Holds the cast channel and the local file server up while the app is not in+             front, so backgrounding the app does not stop playback. -->+        <service+            android:name=".service.CastService"+            android:exported="false"+            android:foregroundServiceType="mediaPlayback" />+    </application>+</manifest>
cast/src/main/java/com/vayunmathur/cast/MainActivity.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/MainActivity.kt b/cast/src/main/java/com/vayunmathur/cast/MainActivity.ktnew file mode 100644index 0000000000..12efc972af--- /dev/null+++ b/cast/src/main/java/com/vayunmathur/cast/MainActivity.kt@@ -0,0 +1,52 @@+package com.vayunmathur.cast++import android.content.Intent+import android.net.Uri+import android.os.Bundle+import androidx.activity.ComponentActivity+import androidx.activity.compose.setContent+import androidx.activity.enableEdgeToEdge+import androidx.activity.viewModels+import androidx.core.content.IntentCompat+import com.vayunmathur.cast.platform.CastViewModel+import com.vayunmathur.cast.platform.CastViewModelFactory+import com.vayunmathur.library.ui.DynamicTheme++/**+ * The app's only Activity, from the launcher or from the share sheet.+ *+ * `ACTION_SEND` lands here rather than in a separate popup, unlike `:share`: the device picker+ * *is* the app, so a bottom sheet would show the same list with less room. `singleTop` plus+ * [onNewIntent] is what makes sharing into an already-open Cast work.+ */+class MainActivity : ComponentActivity() {++    private val viewModel: CastViewModel by viewModels { CastViewModelFactory(application) }++    override fun onCreate(savedInstanceState: Bundle?) {+        super.onCreate(savedInstanceState)+        enableEdgeToEdge()+        consumeSharedUri(intent)+        setContent {+            DynamicTheme {+                Navigation(viewModel)+            }+        }+    }++    override fun onNewIntent(intent: Intent) {+        super.onNewIntent(intent)+        consumeSharedUri(intent)+    }++    /**+     * Take the shared URI as the pending source. It is cast as soon as a receiver is joined, so+     * arriving from the share sheet with nothing connected is a device pick rather than an error.+     */+    private fun consumeSharedUri(intent: Intent?) {+        if (intent?.action != Intent.ACTION_SEND) return+        val uri = IntentCompat.getParcelableExtra(intent, Intent.EXTRA_STREAM, Uri::class.java)+            ?: return+        viewModel.pickLocalFile(uri.toString())+    }+}
cast/src/main/java/com/vayunmathur/cast/Navigation.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/Navigation.kt b/cast/src/main/java/com/vayunmathur/cast/Navigation.ktnew file mode 100644index 0000000000..c1786c9cb1--- /dev/null+++ b/cast/src/main/java/com/vayunmathur/cast/Navigation.kt@@ -0,0 +1,15 @@+package com.vayunmathur.cast++import androidx.compose.runtime.Composable+import com.vayunmathur.cast.platform.CastViewModel+import com.vayunmathur.cast.ui.CastScreen+import com.vayunmathur.library.util.MainNavigation+import com.vayunmathur.library.util.rememberNavBackStack++@Composable+fun Navigation(viewModel: CastViewModel) {+    val backStack = rememberNavBackStack<Route>(Route.Cast)+    MainNavigation(backStack) {+        entry<Route.Cast> { CastScreen(viewModel) }+    }+}
cast/src/main/java/com/vayunmathur/cast/Route.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/Route.kt b/cast/src/main/java/com/vayunmathur/cast/Route.ktnew file mode 100644index 0000000000..fe3425c407--- /dev/null+++ b/cast/src/main/java/com/vayunmathur/cast/Route.kt@@ -0,0 +1,11 @@+package com.vayunmathur.cast++import com.vayunmathur.library.util.NavKey+import kotlinx.serialization.Serializable++@Serializable+sealed interface Route : NavKey {+    /** The only screen: device list, source picker and transport, in one place. */+    @Serializable+    data object Cast : Route+}
cast/src/main/java/com/vayunmathur/cast/domain/CastDevice.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/domain/CastDevice.kt b/cast/src/main/java/com/vayunmathur/cast/domain/CastDevice.ktnew file mode 100644index 0000000000..cd68bc9813--- /dev/null+++ b/cast/src/main/java/com/vayunmathur/cast/domain/CastDevice.kt@@ -0,0 +1,51 @@+package com.vayunmathur.cast.domain++/** What the device is, which is all the icon and the subtitle need. */+enum class CastDeviceKind { Tv, Speaker, Group }++/**+ * A device found on the LAN by browsing `_googlecast._tcp`.+ *+ * Everything here comes out of the mDNS record's TXT attributes, so a device is fully+ * described before anything is connected to. [id] is the receiver's own UUID (`id`) rather+ * than the mDNS instance name, because the instance name changes when a device is renamed+ * and the UUID does not.+ */+data class CastDevice(+    val id: String,+    val friendlyName: String,+    val host: String,+    /**+     * The mDNS instance name. Kept alongside [id] because `onServiceLost` reports only this,+     * so it is the only handle available for removing a device that went away.+     */+    val instanceName: String = id,+    val port: Int = CAST_PORT,+    val model: String? = null,+    /**+     * `rs` - what the device is doing right now, e.g. "YouTube" or "Backdrop". Blank on an+     * idle device, which is why it is only shown when non-empty.+     */+    val statusText: String? = null,+    /** `ca`, a bitmask. See [kind] for the two bits that matter. */+    val capabilities: Int = 0,+) {+    /**+     * Bit 0 (`VIDEO_OUT`) means there is a screen; bit 5 (`MULTIZONE_GROUP`) means this is a+     * speaker group rather than one device. Anything else is a speaker.+     *+     * A group is checked first only for naming: groups do not set `VIDEO_OUT`, so the order+     * is not load-bearing, but reading it in this order makes the intent obvious.+     */+    val kind: CastDeviceKind+        get() = when {+            capabilities and CAPABILITY_MULTIZONE_GROUP != 0 -> CastDeviceKind.Group+            capabilities and CAPABILITY_VIDEO_OUT != 0 -> CastDeviceKind.Tv+            else -> CastDeviceKind.Speaker+        }++    private companion object {+        const val CAPABILITY_VIDEO_OUT = 1 shl 0+        const val CAPABILITY_MULTIZONE_GROUP = 1 shl 5+    }+}
cast/src/main/java/com/vayunmathur/cast/domain/CastPayloads.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/domain/CastPayloads.kt b/cast/src/main/java/com/vayunmathur/cast/domain/CastPayloads.ktnew file mode 100644index 0000000000..45fd8dc64c--- /dev/null+++ b/cast/src/main/java/com/vayunmathur/cast/domain/CastPayloads.kt@@ -0,0 +1,234 @@+package com.vayunmathur.cast.domain++import kotlinx.serialization.Serializable+import kotlinx.serialization.json.Json++/**+ * The CastV2 namespaces this app speaks.+ *+ * A frame's namespace is what decides how its JSON payload is read, so these are the whole+ * routing table. There is no registration or discovery step: every receiver implements the+ * first four, and the Default Media Receiver's media namespace is the public one.+ */+object CastNamespaces {+    const val CONNECTION = "urn:x-cast:com.google.cast.tp.connection"+    const val HEARTBEAT = "urn:x-cast:com.google.cast.tp.heartbeat"+    const val RECEIVER = "urn:x-cast:com.google.cast.receiver"+    const val MEDIA = "urn:x-cast:com.google.cast.media"++    /**+     * OFFER/ANSWER - the Cast Streaming control plane, which is where mirroring is negotiated+     * instead of on [MEDIA].+     *+     * openscreen `cast/streaming/message_fields.h`, `kCastWebrtcNamespace`. The name is+     * historical; nothing about it is WebRTC.+     */+    const val WEBRTC = "urn:x-cast:com.google.cast.webrtc"+}++/**+ * The Default Media Receiver.+ *+ * The one app id a sender can launch without registering as a Google Cast developer, which+ * is the entire reason this app is buildable. It plays a media URL and nothing else - screen+ * mirroring uses [MirroringAppIds] instead.+ */+const val DEFAULT_MEDIA_RECEIVER_APP_ID = "CC1AD845"++/**+ * The Cast Streaming receiver app ids, which are what mirroring has to launch.+ *+ * Four, not two: openscreen names a desktop/Chrome pair *and* an Android pair, and there is+ * no documentation saying which of them will accept an unregistered sender. Deciding that is+ * the entire job of the Phase 0 spike, so all four are listed and all four get tried.+ *+ * openscreen `cast/common/public/cast_streaming_app_ids.h`.+ */+object MirroringAppIds {+    /** `GetCastStreamingAudioVideoAppId()` - what desktop Chrome mirrors with. */+    const val AUDIO_VIDEO = "0F5096E8"++    /** `GetCastStreamingAudioOnlyAppId()`. */+    const val AUDIO_ONLY = "85CDB22F"++    /** `GetAndroidMirroringAudioVideoAppId()`. */+    const val ANDROID_AUDIO_VIDEO = "674A0243"++    /** `GetAndroidMirroringAudioOnlyAppId()`. */+    const val ANDROID_AUDIO_ONLY = "8E6C866D"++    val all: List<String> =+        listOf(AUDIO_VIDEO, AUDIO_ONLY, ANDROID_AUDIO_VIDEO, ANDROID_AUDIO_ONLY)++    /** An audio-only receiver is offered no video stream; a speaker has nothing to draw on. */+    fun isAudioOnly(appId: String): Boolean = appId == AUDIO_ONLY || appId == ANDROID_AUDIO_ONLY+}++/** Every sender is `sender-0`; the platform receiver is always `receiver-0`. */+const val SENDER_ID = "sender-0"+const val RECEIVER_ID = "receiver-0"++/** The receiver's TLS port. Not configurable - it is fixed by the protocol. */+const val CAST_PORT = 8009++/**+ * A payload plus where it goes.+ *+ * [CastSession] deals in these rather than in `CastMessage` so it stays free of the+ * transport: the source id is always [SENDER_ID] and the codec fills it in.+ */+data class CastFrame(+    val namespace: String,+    val destinationId: String,+    val payload: String,+)++/**+ * Lenient on the way in, complete on the way out.+ *+ * `ignoreUnknownKeys` is not optional: receiver and media status carry a large, versioned+ * object graph and a firmware update adding a field must not break playback.+ * `encodeDefaults` is on because a request's `type` is a defaulted constant and the receiver+ * rejects a frame without it, and `explicitNulls` is off so an absent optional stays absent+ * rather than becoming `null` - `SET_VOLUME` with `"muted": null` is an error.+ */+val CastJson: Json = Json {+    ignoreUnknownKeys = true+    encodeDefaults = true+    explicitNulls = false+}++/** Just enough of any payload to route it. Every CastV2 payload has a `type`. */+@Serializable+data class CastEnvelope(+    val type: String = "",+    val requestId: Int? = null,+    /** Present on LAUNCH_ERROR / LOAD_FAILED, e.g. `CANCELLED` or `NOT_AVAILABLE`. */+    val reason: String? = null,+)++@Serializable+data class CastVolume(+    val level: Double? = null,+    val muted: Boolean? = null,+)++@Serializable+data class ReceiverApplication(+    val appId: String = "",+    val displayName: String? = null,+    val sessionId: String = "",+    val statusText: String? = null,+    /**+     * The id to address the *running app* at, which is not [sessionId] and not+     * [RECEIVER_ID]. Media commands sent anywhere else are silently dropped.+     */+    val transportId: String = "",+    val isIdleScreen: Boolean = false,+)++@Serializable+data class ReceiverStatus(+    val applications: List<ReceiverApplication> = emptyList(),+    val volume: CastVolume? = null,+)++@Serializable+data class ReceiverStatusMessage(+    val type: String = "",+    val requestId: Int? = null,+    val status: ReceiverStatus = ReceiverStatus(),+)++@Serializable+data class CastMediaMetadata(+    /** 0 = GENERIC, which is all the Default Media Receiver needs to draw a title. */+    val metadataType: Int = 0,+    val title: String? = null,+    val subtitle: String? = null,+)++@Serializable+data class CastMediaInformation(+    /** The URL the receiver fetches. Local files are served by `MediaFileServer`. */+    val contentId: String = "",+    val contentType: String = "",+    /** BUFFERED for a seekable file, LIVE for a stream with no known end. */+    val streamType: String = "BUFFERED",+    val duration: Double? = null,+    val metadata: CastMediaMetadata? = null,+)++@Serializable+data class CastMediaStatus(+    val mediaSessionId: Int = 0,+    /** IDLE, BUFFERING, PLAYING or PAUSED. */+    val playerState: String = "IDLE",+    val currentTime: Double = 0.0,+    val media: CastMediaInformation? = null,+    val volume: CastVolume? = null,+    val idleReason: String? = null,+)++@Serializable+data class CastMediaStatusMessage(+    val type: String = "",+    val requestId: Int? = null,+    /** Empty when the receiver has no media loaded, which is how STOP is reported. */+    val status: List<CastMediaStatus> = emptyList(),+)++/** `CONNECT`, `CLOSE`, `PING`, `PONG` - the payloads with nothing in them but a type. */+@Serializable+data class CastSimpleMessage(val type: String)++/** `GET_STATUS` on the receiver namespace, and anything else that is type + requestId. */+@Serializable+data class CastRequest(val type: String, val requestId: Int)++@Serializable+data class LaunchRequest(+    val requestId: Int,+    val appId: String,+    val type: String = "LAUNCH",+)++@Serializable+data class StopSessionRequest(+    val requestId: Int,+    val sessionId: String,+    val type: String = "STOP",+)++@Serializable+data class SetVolumeRequest(+    val requestId: Int,+    val volume: CastVolume,+    val type: String = "SET_VOLUME",+)++@Serializable+data class LoadRequest(+    val requestId: Int,+    val sessionId: String,+    val media: CastMediaInformation,+    val autoplay: Boolean = true,+    val currentTime: Double = 0.0,+    val type: String = "LOAD",+)++/** `PLAY`, `PAUSE`, `STOP` and `GET_STATUS` on the media namespace. */+@Serializable+data class MediaCommand(+    val requestId: Int,+    val mediaSessionId: Int,+    val type: String,+)++@Serializable+data class SeekRequest(+    val requestId: Int,+    val mediaSessionId: Int,+    val currentTime: Double,+    val type: String = "SEEK",+)
cast/src/main/java/com/vayunmathur/cast/domain/CastSession.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/domain/CastSession.kt b/cast/src/main/java/com/vayunmathur/cast/domain/CastSession.ktnew file mode 100644index 0000000000..71fe673e93--- /dev/null+++ b/cast/src/main/java/com/vayunmathur/cast/domain/CastSession.kt@@ -0,0 +1,421 @@+package com.vayunmathur.cast.domain++/** How far along the CONNECT -> LAUNCH -> join -> LOAD sequence the session is. */+enum class CastPhase {+    /** No channel, or the receiver closed it. */+    Idle,++    /** CONNECT and LAUNCH are on the wire; waiting for a RECEIVER_STATUS naming the app. */+    Launching,++    /** The app is running and joined: [CastSessionState.transportId] is addressable. */+    Ready,++    /** The receiver refused, and [CastSessionState.failure] says why. */+    Failed,+}++/** The receiver's own player states, verbatim from the media namespace. */+enum class CastPlayerState {+    Idle, Buffering, Playing, Paused;++    companion object {+        fun fromWire(value: String): CastPlayerState = when (value) {+            "BUFFERING" -> Buffering+            "PLAYING" -> Playing+            "PAUSED" -> Paused+            else -> Idle+        }+    }+}++/**+ * Everything the session knows, as one value.+ *+ * [durationSec] and [title] survive a status that omits them: the receiver includes the+ * `media` object only in the first MEDIA_STATUS after a LOAD and leaves it out of the+ * periodic ones, so treating absent as unknown would blank the title a second into playback.+ */+data class CastSessionState(+    val phase: CastPhase = CastPhase.Idle,+    val sessionId: String? = null,+    val transportId: String? = null,+    val mediaSessionId: Int? = null,+    val playerState: CastPlayerState = CastPlayerState.Idle,+    val currentTimeSec: Double = 0.0,+    val durationSec: Double? = null,+    val title: String? = null,+    val volumeLevel: Double = 1.0,+    val muted: Boolean = false,+    val failure: String? = null,+)++/**+ * THROWAWAY (Phase 0): the audio half of the spike's OFFER, hand-transcribed.+ *+ * Field names, the `1/48000` timebase string form and the `rtpProfile` constant come from+ * openscreen `cast/streaming/public/offer_messages.cc` (`Stream::ToJson`, `AudioStream::ToJson`);+ * `rtpPayloadType` 127 is `RtpPayloadType::kAudioHackForAndroidTV` from+ * `cast/streaming/impl/rtp_defines.h`, which is what a real sender puts on the wire because+ * openscreen's `use_android_rtp_hack` defaults to true and Chrome never overrides it.+ * `channels` 2 and `bitRate` 128000 are Chrome's own values from+ * `components/mirroring/service/mirror_settings.cc`. The SSRC is in the high-priority range+ * (1..50000, `cast/streaming/ssrc.cc`).+ *+ * The keys are a fixed literal on purpose: nothing is encrypted during the spike, and a+ * hardcoded key cannot be mistaken for a working crypto path later.+ */+private const val SPIKE_AUDIO_STREAM = """+    {"index":0,"type":"audio_source","codecName":"opus","rtpProfile":"cast",+     "rtpPayloadType":127,"ssrc":20001,"channels":2,"bitRate":128000,+     "targetDelay":400,"timeBase":"1/48000","receiverRtcpEventLog":true,+     "aesKey":"51027e4e2347cbcb49d57ef10177aebc",+     "aesIvMask":"7f12a19be62a36c04ae4116caaeff6d1"}+"""++/**+ * THROWAWAY (Phase 0): the video half, from `VideoStream::ToJson` in the same file.+ *+ * `rtpPayloadType` 96 is `kVideoHackForAndroidTV`, which collides with `kAudioOpus` by design -+ * the receiver disambiguates by index, not by payload type. `maxFrameRate` is a rational+ * *string*, not a number. The SSRC is in the normal-priority range (50001..100000). 720p and+ * 5 Mbit/s are Chrome's starting values; the spike is not measuring picture quality.+ */+private const val SPIKE_VIDEO_STREAM = """+    {"index":1,"type":"video_source","codecName":"h264","rtpProfile":"cast",+     "rtpPayloadType":96,"ssrc":50001,"channels":1,"maxFrameRate":"30000/1000",+     "maxBitRate":5000000,"targetDelay":400,"timeBase":"1/90000",+     "receiverRtcpEventLog":true,"resolutions":[{"width":1280,"height":720}],+     "aesKey":"040d756791711fd3adb939066e6d8690",+     "aesIvMask":"9ff0f022a959150e70a2d05a6c184aed"}+"""++/**+ * The CastV2 sequencing rules, with no I/O.+ *+ * Every method returns the frames to put on the wire and mutates [state]; nothing here+ * touches a socket, a Context or a coroutine, which is what makes the ordering testable on+ * the JVM. The ordering is the part that is easy to get wrong:+ *+ *  1. CONNECT to [RECEIVER_ID], then LAUNCH the app id.+ *  2. The RECEIVER_STATUS that comes back names a `sessionId` **and** a `transportId`.+ *  3. CONNECT again, to that `transportId` - a media command sent before this is dropped+ *     without an error.+ *  4. Only then LOAD.+ *+ * A [load] issued before step 3 is therefore held and replayed rather than rejected, which+ * is what lets the UI treat "pick a device" and "pick a file" as independent.+ *+ * `requestId` is a monotonic counter starting at 1 (zero means "no response wanted" and+ * would lose the correlation), and every response echoes it.+ *+ * [appId] is what gets launched and what a RECEIVER_STATUS is matched against. It is a+ * parameter rather than a constant because mirroring launches a different receiver on the same+ * control plane - the CONNECT -> LAUNCH -> join sequence is identical either way.+ */+class CastSession(private val appId: String = DEFAULT_MEDIA_RECEIVER_APP_ID) {++    var state: CastSessionState = CastSessionState()+        private set++    /**+     * THROWAWAY (Phase 0): every `webrtc` payload, verbatim, for the spike's log.+     *+     * A callback rather than a `Log` call because this class has no Android imports and is not+     * going to acquire one for a spike.+     */+    var onWebrtcPayload: ((String) -> Unit)? = null++    private var nextRequestId = 1++    /** A LOAD asked for before [CastPhase.Ready]; replayed once the app is joined. */+    private var pendingLoad: CastMediaInformation? = null++    fun allocateRequestId(): Int = nextRequestId++++    /** CONNECT to the platform receiver and launch the media receiver app. */+    fun open(): List<CastFrame> {+        state = CastSessionState(phase = CastPhase.Launching)+        return listOf(+            frame(CastNamespaces.CONNECTION, RECEIVER_ID, CastSimpleMessage("CONNECT")),+            frame(CastNamespaces.RECEIVER, RECEIVER_ID, LaunchRequest(allocateRequestId(), appId)),+        )+    }++    /**+     * The keepalive. The receiver drops a channel that has been quiet for about 10 seconds,+     * so this has to be sent on a timer whether or not anything is playing.+     */+    fun heartbeat(): CastFrame =+        frame(CastNamespaces.HEARTBEAT, RECEIVER_ID, CastSimpleMessage("PING"))++    /**+     * Feed one received frame in; get the replies to send back out.+     *+     * Anything unrecognised is ignored rather than treated as an error - receivers send+     * status types and namespaces this app has no interest in.+     */+    fun onMessage(namespace: String, payload: String): List<CastFrame> {+        val envelope = runCatching { CastJson.decodeFromString<CastEnvelope>(payload) }.getOrNull()+            ?: return emptyList()+        return when (namespace) {+            CastNamespaces.HEARTBEAT ->+                if (envelope.type == "PING") {+                    listOf(frame(CastNamespaces.HEARTBEAT, RECEIVER_ID, CastSimpleMessage("PONG")))+                } else {+                    emptyList()+                }+            CastNamespaces.CONNECTION -> {+                if (envelope.type == "CLOSE") onClosed()+                emptyList()+            }+            CastNamespaces.RECEIVER -> onReceiverMessage(envelope, payload)+            CastNamespaces.WEBRTC -> {+                onWebrtcPayload?.invoke(payload)+                emptyList()+            }+            CastNamespaces.MEDIA -> {+                onMediaMessage(envelope, payload)+                emptyList()+            }+            else -> emptyList()+        }+    }++    /**+     * Load a URL into the running app, or remember it until there is one.+     *+     * Returns the frames to send, which is empty when the request was held.+     */+    fun load(media: CastMediaInformation): List<CastFrame> {+        state = state.copy(+            failure = null,+            title = media.metadata?.title,+            durationSec = media.duration,+            currentTimeSec = 0.0,+            playerState = CastPlayerState.Buffering,+        )+        val sessionId = state.sessionId+        val transportId = state.transportId+        if (state.phase != CastPhase.Ready || sessionId == null || transportId == null) {+            pendingLoad = media+            return emptyList()+        }+        pendingLoad = null+        return listOf(+            frame(+                CastNamespaces.MEDIA,+                transportId,+                LoadRequest(allocateRequestId(), sessionId, media),+            ),+        )+    }++    /**+     * THROWAWAY (Phase 0): put one hand-written OFFER on the `webrtc` namespace.+     *+     * The envelope is `{"type":"OFFER","seqNum":N,"offer":{...}}` per openscreen+     * `cast/streaming/sender_message.cc`, and `castMode` is `"mirroring"` per+     * `CreateMirroringOffer` in `cast/streaming/public/sender_session.cc`. That same function is+     * why there is no GET_CAPABILITIES first: openscreen sends one only from+     * `NegotiateRemoting`, never from the mirroring path.+     *+     * `seqNum` shares the `requestId` counter. They are separate sequences in the protocol, but+     * one monotonic source cannot collide with itself and the spike only ever sends one OFFER.+     */+    fun sendSpikeOffer(audioOnly: Boolean): List<CastFrame> {+        val transportId = state.transportId ?: return emptyList()+        val streams = if (audioOnly) {+            SPIKE_AUDIO_STREAM+        } else {+            "$SPIKE_AUDIO_STREAM,$SPIKE_VIDEO_STREAM"+        }+        val payload =+            """{"type":"OFFER","seqNum":${allocateRequestId()},""" ++                """"offer":{"castMode":"mirroring","supportedStreams":[$streams]}}"""+        return listOf(CastFrame(CastNamespaces.WEBRTC, transportId, payload))+    }++    fun play(): List<CastFrame> = mediaCommand("PLAY")++    fun pause(): List<CastFrame> = mediaCommand("PAUSE")++    /** Stops playback but leaves the app running, so another LOAD needs no relaunch. */+    fun stopMedia(): List<CastFrame> = mediaCommand("STOP")++    fun refreshMediaStatus(): List<CastFrame> = mediaCommand("GET_STATUS")++    fun seek(positionSec: Double): List<CastFrame> {+        val transportId = state.transportId ?: return emptyList()+        val mediaSessionId = state.mediaSessionId ?: return emptyList()+        // Optimistic: the receiver's next MEDIA_STATUS corrects it, and without this the+        // progress bar snaps back to the old position for as long as the round trip takes.+        state = state.copy(currentTimeSec = positionSec)+        return listOf(+            frame(+                CastNamespaces.MEDIA,+                transportId,+                SeekRequest(allocateRequestId(), mediaSessionId, positionSec),+            ),+        )+    }++    /**+     * Volume is the *receiver's* volume, not the media's, so it goes to [RECEIVER_ID] on the+     * receiver namespace even while media is playing.+     */+    fun setVolume(level: Double): List<CastFrame> {+        val clamped = level.coerceIn(0.0, 1.0)+        state = state.copy(volumeLevel = clamped)+        return listOf(+            frame(+                CastNamespaces.RECEIVER,+                RECEIVER_ID,+                SetVolumeRequest(allocateRequestId(), CastVolume(level = clamped)),+            ),+        )+    }++    fun setMuted(muted: Boolean): List<CastFrame> {+        state = state.copy(muted = muted)+        return listOf(+            frame(+                CastNamespaces.RECEIVER,+                RECEIVER_ID,+                SetVolumeRequest(allocateRequestId(), CastVolume(muted = muted)),+            ),+        )+    }++    /**+     * Tear the session down: stop the receiver app, then CLOSE the channel.+     *+     * Stopping the app is what returns the TV to its backdrop; closing without it leaves the+     * media receiver on screen with the last frame frozen.+     */+    fun close(): List<CastFrame> {+        val frames = buildList {+            state.sessionId?.let {+                add(+                    frame(+                        CastNamespaces.RECEIVER,+                        RECEIVER_ID,+                        StopSessionRequest(allocateRequestId(), it),+                    ),+                )+            }+            state.transportId?.let {+                add(frame(CastNamespaces.CONNECTION, it, CastSimpleMessage("CLOSE")))+            }+            add(frame(CastNamespaces.CONNECTION, RECEIVER_ID, CastSimpleMessage("CLOSE")))+        }+        onClosed()+        return frames+    }++    private fun onClosed() {+        pendingLoad = null+        state = CastSessionState(phase = CastPhase.Idle)+    }++    private fun onReceiverMessage(envelope: CastEnvelope, payload: String): List<CastFrame> {+        if (envelope.type == "LAUNCH_ERROR") {+            state = state.copy(+                phase = CastPhase.Failed,+                failure = envelope.reason ?: envelope.type,+            )+            return emptyList()+        }+        if (envelope.type != "RECEIVER_STATUS") return emptyList()+        val status = runCatching { CastJson.decodeFromString<ReceiverStatusMessage>(payload) }+            .getOrNull()?.status ?: return emptyList()+        status.volume?.let { volume ->+            state = state.copy(+                volumeLevel = volume.level ?: state.volumeLevel,+                muted = volume.muted ?: state.muted,+            )+        }+        val app = status.applications.firstOrNull {+            it.appId == appId && it.transportId.isNotEmpty()+        }+        if (app == null) {+            // The app is gone - either someone else took the receiver over or STOP landed.+            // Not a failure, but there is nothing left to send media to.+            if (state.phase == CastPhase.Ready) {+                state = state.copy(+                    phase = CastPhase.Idle,+                    sessionId = null,+                    transportId = null,+                    mediaSessionId = null,+                    playerState = CastPlayerState.Idle,+                )+            }+            return emptyList()+        }+        // A relaunch produces a new transportId, so join on change rather than on phase:+        // reusing the old one is how a session ends up connected to an app that has exited.+        if (state.phase == CastPhase.Ready && state.transportId == app.transportId) {+            return emptyList()+        }+        state = state.copy(+            phase = CastPhase.Ready,+            sessionId = app.sessionId,+            transportId = app.transportId,+            failure = null,+        )+        return buildList {+            add(frame(CastNamespaces.CONNECTION, app.transportId, CastSimpleMessage("CONNECT")))+            pendingLoad?.let { addAll(load(it)) }+        }+    }++    private fun onMediaMessage(envelope: CastEnvelope, payload: String) {+        if (envelope.type == "LOAD_FAILED" || envelope.type == "LOAD_CANCELLED") {+            state = state.copy(+                playerState = CastPlayerState.Idle,+                failure = envelope.reason ?: envelope.type,+            )+            return+        }+        if (envelope.type != "MEDIA_STATUS") return+        val statuses = runCatching { CastJson.decodeFromString<CastMediaStatusMessage>(payload) }+            .getOrNull()?.status ?: return+        val status = statuses.firstOrNull()+        if (status == null) {+            // An empty status array is how the receiver reports "nothing loaded" after STOP.+            state = state.copy(+                mediaSessionId = null,+                playerState = CastPlayerState.Idle,+                currentTimeSec = 0.0,+                durationSec = null,+                title = null,+            )+            return+        }+        state = state.copy(+            mediaSessionId = status.mediaSessionId,+            playerState = CastPlayerState.fromWire(status.playerState),+            currentTimeSec = status.currentTime,+            durationSec = status.media?.duration ?: state.durationSec,+            title = status.media?.metadata?.title ?: state.title,+        )+    }++    private fun mediaCommand(type: String): List<CastFrame> {+        val transportId = state.transportId ?: return emptyList()+        val mediaSessionId = state.mediaSessionId ?: return emptyList()+        return listOf(+            frame(+                CastNamespaces.MEDIA,+                transportId,+                MediaCommand(allocateRequestId(), mediaSessionId, type),+            ),+        )+    }++    private inline fun <reified T> frame(+        namespace: String,+        destinationId: String,+        payload: T,+    ): CastFrame = CastFrame(namespace, destinationId, CastJson.encodeToString(payload))+}
cast/src/main/java/com/vayunmathur/cast/network/ByteRange.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/network/ByteRange.kt b/cast/src/main/java/com/vayunmathur/cast/network/ByteRange.ktnew file mode 100644index 0000000000..bd03dcc5e4--- /dev/null+++ b/cast/src/main/java/com/vayunmathur/cast/network/ByteRange.kt@@ -0,0 +1,71 @@+package com.vayunmathur.cast.network++/**+ * A resolved `Range` request: the byte offsets to send, inclusive of both ends.+ *+ * [MediaFileServer] answers one of these with `206 Partial Content` and a+ * `Content-Range: bytes first-last/total` header.+ */+data class ByteRange(val first: Long, val last: Long) {+    val length: Long get() = last - first + 1+}++/** The three things a `Range` header can mean to a server that supports one range. */+sealed interface ByteRangeResult {+    /** No `Range` header, or one this server does not implement: send the whole entity. */+    data object Whole : ByteRangeResult++    data class Partial(val range: ByteRange) : ByteRangeResult++    /** The range is syntactically fine but outside the entity: answer `416`. */+    data object Unsatisfiable : ByteRangeResult+}++/**+ * Parse a `Range` header value against a known entity length.+ *+ * Chromecast probes with `HEAD` and then seeks with `Range`, and without a correct `206` the+ * seek bar does nothing - which is the whole reason this is a separate, pure function with+ * its own tests rather than a few lines inside the request loop.+ *+ * Deliberately narrow, per RFC 9110 6.1: only `bytes=` is understood, and only a single+ * range. A multi-range request (`bytes=0-9,20-29`) would need a `multipart/byteranges` body;+ * no receiver sends one, so it degrades to [ByteRangeResult.Whole] rather than being+ * answered wrongly. A malformed header does the same, which is what the spec requires -+ * an unparseable `Range` must be ignored, not rejected.+ *+ * The forms that do matter:+ *  - `bytes=N-M`  first N, last M+ *  - `bytes=N-`   from N to the end, which is what a player sends when it seeks+ *  - `bytes=-N`   the *last* N bytes, a suffix range+ */+fun parseByteRange(header: String?, totalLength: Long): ByteRangeResult {+    if (header == null || totalLength <= 0) return ByteRangeResult.Whole+    val trimmed = header.trim()+    if (!trimmed.startsWith("bytes=", ignoreCase = true)) return ByteRangeResult.Whole+    val spec = trimmed.substring("bytes=".length).trim()+    if (spec.contains(',')) return ByteRangeResult.Whole+    val dash = spec.indexOf('-')+    if (dash < 0) return ByteRangeResult.Whole+    val firstText = spec.substring(0, dash).trim()+    val lastText = spec.substring(dash + 1).trim()+    if (firstText.isEmpty()) {+        // Suffix range. A suffix longer than the entity is the whole entity, not a 416.+        val suffix = lastText.toLongOrNull() ?: return ByteRangeResult.Whole+        if (suffix <= 0) return ByteRangeResult.Unsatisfiable+        val first = (totalLength - suffix).coerceAtLeast(0)+        return ByteRangeResult.Partial(ByteRange(first, totalLength - 1))+    }+    val first = firstText.toLongOrNull() ?: return ByteRangeResult.Whole+    if (first < 0) return ByteRangeResult.Whole+    if (first >= totalLength) return ByteRangeResult.Unsatisfiable+    val last = if (lastText.isEmpty()) {+        totalLength - 1+    } else {+        val requested = lastText.toLongOrNull() ?: return ByteRangeResult.Whole+        if (requested < first) return ByteRangeResult.Unsatisfiable+        // A last-byte-pos past the end is clamped, not an error.+        requested.coerceAtMost(totalLength - 1)+    }+    return ByteRangeResult.Partial(ByteRange(first, last))+}
cast/src/main/java/com/vayunmathur/cast/network/CastChannel.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/network/CastChannel.kt b/cast/src/main/java/com/vayunmathur/cast/network/CastChannel.ktnew file mode 100644index 0000000000..5072785f9c--- /dev/null+++ b/cast/src/main/java/com/vayunmathur/cast/network/CastChannel.kt@@ -0,0 +1,173 @@+package com.vayunmathur.cast.network++import android.annotation.SuppressLint+import android.util.Log+import com.vayunmathur.cast.domain.CAST_PORT+import com.vayunmathur.cast.domain.CastFrame+import com.vayunmathur.cast.domain.SENDER_ID+import java.io.DataInputStream+import java.io.DataOutputStream+import java.io.EOFException+import java.net.InetSocketAddress+import java.net.Socket+import java.security.SecureRandom+import java.security.cert.X509Certificate+import javax.net.ssl.SSLContext+import javax.net.ssl.SSLSocket+import javax.net.ssl.SSLSocketFactory+import javax.net.ssl.X509TrustManager+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.flow+import kotlinx.coroutines.flow.flowOn+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock+import kotlinx.coroutines.withContext++private const val TAG = "CastChannel"++private const val CONNECT_TIMEOUT_MS = 8_000++/**+ * How long a read may block before the link is treated as dead.+ *+ * Comfortably longer than the heartbeat interval, so a healthy channel never trips it: the+ * receiver answers every PING, so silence for this long means the link is gone even though+ * TCP has not noticed - which is what happens when Wi-Fi drops rather than being closed.+ */+private const val READ_TIMEOUT_MS = 30_000++/**+ * A frame larger than this is refused rather than allocated.+ *+ * RECEIVER_STATUS on a device with many namespaces is a few kilobytes, so this is orders of+ * magnitude of headroom; the point is only that a corrupt length prefix cannot ask for a+ * gigabyte.+ */+private const val MAX_FRAME_BYTES = 1 shl 20++/**+ * The TLS socket to a receiver, and the length-prefix framing on it.+ *+ * Transport only: it knows about `int32be(len) โ€– CastMessage` and nothing about namespaces,+ * request ids or sequencing - that all lives in `CastSession`, which is pure. The keepalive+ * timer lives with the session too, since PING is a session frame like any other; this class+ * just carries whatever it is handed.+ */+class CastChannel(private val host: String, private val port: Int = CAST_PORT) {++    private var socket: SSLSocket? = null+    private var input: DataInputStream? = null+    private var output: DataOutputStream? = null++    /** One writer at a time: a half-written frame desynchronises the stream permanently. */+    private val writeMutex = Mutex()++    suspend fun connect() = withContext(Dispatchers.IO) {+        val plain = Socket()+        try {+            plain.connect(InetSocketAddress(host, port), CONNECT_TIMEOUT_MS)+            // autoClose = true, so the TLS socket adopts `plain` from here on - but only once+            // createSocket has returned, which is why the handshake is inside this try.+            val tls = permissiveSocketFactory().createSocket(plain, host, port, true) as SSLSocket+            tls.soTimeout = READ_TIMEOUT_MS+            tls.startHandshake()+            socket = tls+            input = DataInputStream(tls.inputStream.buffered())+            output = DataOutputStream(tls.outputStream.buffered())+            Log.i(TAG, "connected to $host:$port (${tls.session.protocol})")+        } catch (e: Exception) {+            // Nothing else holds `plain` yet, so a failure here would leak the descriptor.+            runCatching { plain.close() }+            throw e+        }+    }++    /**+     * Every frame the receiver sends, until the channel closes.+     *+     * Completes normally on a clean close and throws on a broken link, so the collector's+     * `catch` is the one place a dropped connection has to be handled.+     */+    fun messages(): Flow<CastMessage> = flow {+        while (true) {+            val message = readFrame() ?: break+            emit(message)+        }+    }.flowOn(Dispatchers.IO)++    suspend fun send(frame: CastFrame) = withContext(Dispatchers.IO) {+        val message = CastMessage(+            sourceId = SENDER_ID,+            destinationId = frame.destinationId,+            namespace = frame.namespace,+            payloadUtf8 = frame.payload,+        )+        val bytes = CastMessageCodec.encode(message)+        writeMutex.withLock {+            val stream = output ?: error("send before connect")+            stream.writeInt(bytes.size)+            stream.write(bytes)+            stream.flush()+        }+    }++    fun close() {+        // Closing the socket is what unblocks a reader parked in readFrame; the streams are+        // dropped afterwards so a late send fails fast instead of writing into a dead socket.+        runCatching { socket?.close() }+        socket = null+        input = null+        output = null+    }++    /** Returns null at end of stream. Throws when the link breaks or a frame is malformed. */+    private fun readFrame(): CastMessage? {+        while (true) {+            val stream = input ?: return null+            val length = try {+                stream.readInt()+            } catch (_: EOFException) {+                return null+            }+            if (length <= 0 || length > MAX_FRAME_BYTES) {+                error("refusing a $length byte frame from $host")+            }+            val bytes = ByteArray(length)+            stream.readFully(bytes)+            // A frame that will not decode is dropped rather than fatal: the stream is still+            // in sync, because the length prefix said exactly how much to skip.+            val message = CastMessageCodec.decode(bytes)+            if (message != null) return message+            Log.w(TAG, "dropping a $length byte frame that is not a CastMessage")+        }+    }++    /**+     * TLS with verification switched off, for this socket and nothing else.+     *+     * CastV2 has no PKI: receivers present a self-signed device certificate, there is no CA+     * to chain it to and no name to match it against, so `pychromecast`, `node-castv2` and+     * Chrome's own implementation all skip verification. Doing the same is the only way to+     * speak the protocol at all.+     *+     * Deliberately a private [SSLContext] rather than+     * `HttpsURLConnection.setDefaultSSLSocketFactory` or anything touching+     * `library:network`'s `TrustBundle`: the permissiveness must not be reachable from any+     * other connection in the app. What is on this channel is a device name, a media URL and+     * transport controls, on the local network, with no credential of any kind - so the+     * attack it does not defend against (a LAN attacker impersonating the TV) costs the user+     * a video playing on the wrong screen.+     */+    @SuppressLint("TrustAllX509TrustManager", "CustomX509TrustManager")+    private fun permissiveSocketFactory(): SSLSocketFactory {+        val trustManager = object : X509TrustManager {+            override fun checkClientTrusted(chain: Array<X509Certificate>, authType: String) = Unit+            override fun checkServerTrusted(chain: Array<X509Certificate>, authType: String) = Unit+            override fun getAcceptedIssuers(): Array<X509Certificate> = emptyArray()+        }+        return SSLContext.getInstance("TLS").apply {+            init(null, arrayOf(trustManager), SecureRandom())+        }.socketFactory+    }+}
cast/src/main/java/com/vayunmathur/cast/network/CastMessageCodec.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/network/CastMessageCodec.kt b/cast/src/main/java/com/vayunmathur/cast/network/CastMessageCodec.ktnew file mode 100644index 0000000000..32912cab24--- /dev/null+++ b/cast/src/main/java/com/vayunmathur/cast/network/CastMessageCodec.kt@@ -0,0 +1,147 @@+package com.vayunmathur.cast.network++/**+ * One CastV2 frame.+ *+ * `CastMessage` from Chrome's `cast_channel.proto` is the only message on the wire; every+ * namespace's payload rides inside it as a UTF-8 JSON string. The two enum fields have a+ * single value each in practice - protocol version `CASTV2_1_0` and payload type `STRING` -+ * so they are not modelled here: [CastMessageCodec] writes them as the constants they are+ * and a frame that arrives with a binary payload decodes to an empty [payloadUtf8], which+ * is indistinguishable from a payload we cannot parse and is handled the same way.+ */+data class CastMessage(+    val sourceId: String,+    val destinationId: String,+    val namespace: String,+    val payloadUtf8: String,+)++/**+ * Hand-rolled `CastMessage` protobuf codec.+ *+ * Seven scalar fields, so a codegen dependency would cost more than it saves - `:share`+ * hand-rolls its Nearby Connections protobuf for the same reason and there are no `.proto`+ * files anywhere in the repo. Field numbers are taken from Chromium's+ * `components/cast_channel/proto/cast_channel.proto` and cited per field below; getting one+ * wrong is the kind of mistake that shows up as a device silently ignoring us, which is why+ * the round trip is asserted by a unit test against golden bytes.+ */+object CastMessageCodec {++    /** `protocol_version = 1`, the only value being `CASTV2_1_0 = 0`. */+    private const val TAG_PROTOCOL_VERSION = 1+    private const val TAG_SOURCE_ID = 2+    private const val TAG_DESTINATION_ID = 3+    private const val TAG_NAMESPACE = 4++    /** `payload_type = 5`; `STRING = 0`, `BINARY = 1`. Only STRING is ever sent. */+    private const val TAG_PAYLOAD_TYPE = 5+    private const val TAG_PAYLOAD_UTF8 = 6+    private const val TAG_PAYLOAD_BINARY = 7++    private const val WIRE_VARINT = 0+    private const val WIRE_FIXED64 = 1+    private const val WIRE_LENGTH_DELIMITED = 2+    private const val WIRE_FIXED32 = 5++    private const val PROTOCOL_VERSION_CASTV2_1_0 = 0L+    private const val PAYLOAD_TYPE_STRING = 0L++    fun encode(message: CastMessage): ByteArray {+        val out = ArrayList<Byte>(64 + message.payloadUtf8.length)+        // Both enums are `required`, so they are written even at their default value: a+        // receiver that validates presence rejects the frame otherwise.+        out.writeVarintField(TAG_PROTOCOL_VERSION, PROTOCOL_VERSION_CASTV2_1_0)+        out.writeStringField(TAG_SOURCE_ID, message.sourceId)+        out.writeStringField(TAG_DESTINATION_ID, message.destinationId)+        out.writeStringField(TAG_NAMESPACE, message.namespace)+        out.writeVarintField(TAG_PAYLOAD_TYPE, PAYLOAD_TYPE_STRING)+        out.writeStringField(TAG_PAYLOAD_UTF8, message.payloadUtf8)+        return out.toByteArray()+    }++    /** Returns null when [bytes] is not a decodable `CastMessage`. */+    fun decode(bytes: ByteArray): CastMessage? {+        var sourceId = ""+        var destinationId = ""+        var namespace = ""+        var payload = ""+        var offset = 0+        while (offset < bytes.size) {+            val tag = bytes.readVarint(offset) ?: return null+            offset = tag.next+            val fieldNumber = (tag.value ushr 3).toInt()+            when ((tag.value and 0x7L).toInt()) {+                WIRE_VARINT -> {+                    val v = bytes.readVarint(offset) ?: return null+                    offset = v.next+                }+                WIRE_LENGTH_DELIMITED -> {+                    val len = bytes.readVarint(offset) ?: return null+                    val start = len.next+                    if (len.value < 0 || len.value > (bytes.size - start).toLong()) return null+                    val end = start + len.value.toInt()+                    when (fieldNumber) {+                        TAG_SOURCE_ID -> sourceId = String(bytes, start, end - start, Charsets.UTF_8)+                        TAG_DESTINATION_ID -> destinationId = String(bytes, start, end - start, Charsets.UTF_8)+                        TAG_NAMESPACE -> namespace = String(bytes, start, end - start, Charsets.UTF_8)+                        TAG_PAYLOAD_UTF8 -> payload = String(bytes, start, end - start, Charsets.UTF_8)+                        // A binary payload is skipped rather than surfaced: no namespace this+                        // app speaks uses one, and a caller could not do anything with it.+                        TAG_PAYLOAD_BINARY -> Unit+                    }+                    offset = end+                }+                WIRE_FIXED64 -> offset += 8+                WIRE_FIXED32 -> offset += 4+                else -> return null // groups (3/4) were removed from proto3 and never appear+            }+            if (offset > bytes.size) return null+        }+        if (namespace.isEmpty()) return null+        return CastMessage(sourceId, destinationId, namespace, payload)+    }++    private fun MutableList<Byte>.writeVarint(value: Long) {+        var v = value+        while (true) {+            val b = (v and 0x7F).toInt()+            v = v ushr 7+            if (v == 0L) {+                add(b.toByte())+                return+            }+            add((b or 0x80).toByte())+        }+    }++    private fun MutableList<Byte>.writeVarintField(fieldNumber: Int, value: Long) {+        writeVarint((fieldNumber.toLong() shl 3) or WIRE_VARINT.toLong())+        writeVarint(value)+    }++    private fun MutableList<Byte>.writeStringField(fieldNumber: Int, value: String) {+        val utf8 = value.toByteArray(Charsets.UTF_8)+        writeVarint((fieldNumber.toLong() shl 3) or WIRE_LENGTH_DELIMITED.toLong())+        writeVarint(utf8.size.toLong())+        utf8.forEach { add(it) }+    }++    private class Varint(val value: Long, val next: Int)++    private fun ByteArray.readVarint(from: Int): Varint? {+        var result = 0L+        var shift = 0+        var i = from+        while (i < size) {+            val b = this[i].toInt()+            result = result or ((b and 0x7F).toLong() shl shift)+            i+++            if (b and 0x80 == 0) return Varint(result, i)+            shift += 7+            if (shift > 63) return null+        }+        return null+    }+}
cast/src/main/java/com/vayunmathur/cast/network/MediaFileServer.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/network/MediaFileServer.kt b/cast/src/main/java/com/vayunmathur/cast/network/MediaFileServer.ktnew file mode 100644index 0000000000..bf6851057b--- /dev/null+++ b/cast/src/main/java/com/vayunmathur/cast/network/MediaFileServer.kt@@ -0,0 +1,318 @@+package com.vayunmathur.cast.network++import android.content.ContentResolver+import android.net.Uri+import android.util.Log+import java.io.BufferedInputStream+import java.io.BufferedOutputStream+import java.io.FileInputStream+import java.io.InputStream+import java.io.OutputStream+import java.net.InetAddress+import java.net.NetworkInterface+import java.net.ServerSocket+import java.net.Socket+import java.security.SecureRandom+import java.util.Collections+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Job+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.cancel+import kotlinx.coroutines.launch++private const val TAG = "MediaFileServer"++private const val COPY_BUFFER_BYTES = 64 * 1024++/**+ * The one-file HTTP server a local cast needs.+ *+ * A Chromecast plays a URL, not a file, so casting something the user picked means serving it+ * over the LAN for the duration of the session. There is no embedded HTTP server anywhere+ * else in this repo, so this is deliberately the smallest thing that works with a real+ * receiver:+ *+ *  - **One URI at a time**, at a random 128-bit path token. The server is reachable by+ *    anything on the LAN, so the token is what stops it being a browsable window onto+ *    whatever the app can read; nothing else is served, at any path.+ *  - **`GET` and `HEAD` only.** Chromecast probes with `HEAD` before it plays.+ *  - **`Range` with `206 Partial Content`.** Seeking is implemented client-side by asking for+ *    a byte offset, so without this the scrub bar silently does nothing. See [parseByteRange].+ *  - **Bound to the Wi-Fi address**, so the URL handed to the receiver is one it can reach,+ *    and torn down with the session.+ *+ * The file is read through `ContentResolver.openFileDescriptor`, which is why the app needs no+ * storage or media permission: a URI from `ACTION_OPEN_DOCUMENT` or the share sheet already+ * carries its own grant.+ */+class MediaFileServer(private val contentResolver: ContentResolver) {++    private var scope: CoroutineScope? = null+    private var server: ServerSocket? = null+    private var acceptJob: Job? = null++    /**+     * Sockets with a response in flight.+     *+     * Closing the [ServerSocket] frees the port but does nothing to a `GET` already streaming,+     * and neither does cancelling the scope: the copy loop is blocking I/O. So [stop] closes+     * these too, which is what makes "the session ended" mean the file stops being readable.+     */+    private val openClients = Collections.synchronizedSet(mutableSetOf<Socket>())++    @Volatile+    private var served: Served? = null++    private class Served(+        val token: String,+        val uri: Uri,+        val mimeType: String,+        val length: Long,+    )++    /**+     * Start serving [uri] and return the URL to hand to the receiver, or null when the file+     * cannot be measured or there is no LAN address to bind to.+     *+     * Replaces whatever was being served: the previous URL stops working immediately, which is+     * correct - a session only ever plays one thing.+     */+    fun start(uri: Uri, mimeType: String): String? {+        stop()+        val length = fileLength(uri)+        if (length <= 0) {+            Log.w(TAG, "cannot determine the length of $uri - refusing to serve it")+            return null+        }+        val address = localAddress() ?: run {+            Log.w(TAG, "no usable local network address - cannot serve $uri")+            return null+        }+        val socket = try {+            ServerSocket(0, 8, address)+        } catch (e: Exception) {+            Log.w(TAG, "could not bind a server socket on ${address.hostAddress}", e)+            return null+        }+        val token = randomToken()+        served = Served(token, uri, mimeType, length)+        server = socket+        val serverScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)+        scope = serverScope+        acceptJob = serverScope.launch {+            while (true) {+                val client = try {+                    socket.accept()+                } catch (_: Exception) {+                    // Closed by stop(), or the interface went away. Either way we are done.+                    break+                }+                launch { handle(client) }+            }+        }+        return "http://${address.hostAddress}:${socket.localPort}/$token"+    }++    fun stop() {+        served = null+        runCatching { server?.close() }+        server = null+        acceptJob = null+        synchronized(openClients) {+            openClients.forEach { runCatching { it.close() } }+            openClients.clear()+        }+        scope?.cancel()+        scope = null+    }++    private fun handle(client: Socket) {+        openClients.add(client)+        try {+            client.use { socket ->+                val input = BufferedInputStream(socket.getInputStream())+                val output = BufferedOutputStream(socket.getOutputStream())+                val requestLine = readLine(input) ?: return+                val parts = requestLine.split(' ')+                if (parts.size < 2) {+                    respondStatus(output, 400, "Bad Request")+                    return+                }+                val method = parts[0].uppercase()+                val path = parts[1]+                val headers = readHeaders(input)+                val target = served+                if (target == null || path != "/${target.token}") {+                    respondStatus(output, 404, "Not Found")+                    return+                }+                if (method != "GET" && method != "HEAD") {+                    respondStatus(output, 405, "Method Not Allowed", extra = "Allow: GET, HEAD")+                    return+                }+                respondBody(output, method, headers["range"], target)+            }+        } catch (e: Exception) {+            // A receiver that abandons a request mid-body is normal - it does exactly that+            // when the user seeks - so a broken pipe here is not worth more than a debug line.+            Log.d(TAG, "request failed", e)+        } finally {+            openClients.remove(client)+        }+    }++    private fun respondBody(+        output: OutputStream,+        method: String,+        rangeHeader: String?,+        target: Served,+    ) {+        when (val range = parseByteRange(rangeHeader, target.length)) {+            is ByteRangeResult.Unsatisfiable -> respondStatus(+                output,+                416,+                "Range Not Satisfiable",+                extra = "Content-Range: bytes */${target.length}",+            )+            is ByteRangeResult.Whole -> {+                writeHeaders(+                    output,+                    status = "200 OK",+                    contentType = target.mimeType,+                    contentLength = target.length,+                )+                if (method == "GET") copy(target, ByteRange(0, target.length - 1), output)+            }+            is ByteRangeResult.Partial -> {+                writeHeaders(+                    output,+                    status = "206 Partial Content",+                    contentType = target.mimeType,+                    contentLength = range.range.length,+                    extra = "Content-Range: bytes ${range.range.first}-${range.range.last}/${target.length}",+                )+                if (method == "GET") copy(target, range.range, output)+            }+        }+        output.flush()+    }++    private fun copy(target: Served, range: ByteRange, output: OutputStream) {+        contentResolver.openFileDescriptor(target.uri, "r")?.use { descriptor ->+            FileInputStream(descriptor.fileDescriptor).use { stream ->+                // position() rather than skip(): skip on a large offset is allowed to do less+                // than asked, which would silently serve the wrong bytes for a seek.+                stream.channel.position(range.first)+                var remaining = range.length+                val buffer = ByteArray(COPY_BUFFER_BYTES)+                while (remaining > 0) {+                    val wanted = minOf(remaining, buffer.size.toLong()).toInt()+                    val read = stream.read(buffer, 0, wanted)+                    if (read <= 0) break+                    output.write(buffer, 0, read)+                    remaining -= read+                }+            }+        }+    }++    private fun writeHeaders(+        output: OutputStream,+        status: String,+        contentType: String,+        contentLength: Long,+        extra: String? = null,+    ) {+        val head = buildString {+            append("HTTP/1.1 ").append(status).append("\r\n")+            append("Content-Type: ").append(contentType).append("\r\n")+            append("Content-Length: ").append(contentLength).append("\r\n")+            // Advertised unconditionally: a receiver that does not see this will not attempt a+            // Range request at all, and seeking would be unavailable even though it works.+            append("Accept-Ranges: bytes\r\n")+            if (extra != null) append(extra).append("\r\n")+            append("Connection: close\r\n\r\n")+        }+        output.write(head.toByteArray(Charsets.US_ASCII))+    }++    private fun respondStatus(+        output: OutputStream,+        code: Int,+        reason: String,+        extra: String? = null,+    ) {+        val head = buildString {+            append("HTTP/1.1 ").append(code).append(' ').append(reason).append("\r\n")+            append("Content-Length: 0\r\n")+            if (extra != null) append(extra).append("\r\n")+            append("Connection: close\r\n\r\n")+        }+        output.write(head.toByteArray(Charsets.US_ASCII))+        output.flush()+    }++    /** Header names are case-insensitive, so they are lowercased on the way in. */+    private fun readHeaders(input: InputStream): Map<String, String> {+        val headers = mutableMapOf<String, String>()+        while (true) {+            val line = readLine(input) ?: break+            if (line.isEmpty()) break+            val colon = line.indexOf(':')+            if (colon <= 0) continue+            headers[line.substring(0, colon).trim().lowercase()] =+                line.substring(colon + 1).trim()+        }+        return headers+    }++    /**+     * One CRLF-terminated line, read a byte at a time.+     *+     * Not a `BufferedReader`: that decodes ahead into a character buffer, which would swallow+     * the start of the body on a request that had one.+     */+    private fun readLine(input: InputStream): String? {+        val line = StringBuilder()+        while (true) {+            when (val b = input.read()) {+                -1 -> return if (line.isEmpty()) null else line.toString()+                '\n'.code -> return line.toString().removeSuffix("\r")+                else -> {+                    if (line.length > 8192) return null+                    line.append(b.toChar())+                }+            }+        }+    }++    private fun fileLength(uri: Uri): Long =+        runCatching {+            contentResolver.openFileDescriptor(uri, "r")?.use { it.statSize } ?: -1L+        }.getOrDefault(-1L)++    /**+     * The address the receiver has to be able to reach us on.+     *+     * Enumerating interfaces rather than asking `ConnectivityManager`: this needs a bindable+     * `InetAddress`, and it must be the LAN one - a link-local or loopback address in the URL+     * produces a receiver that reports a load failure with no explanation.+     */+    private fun localAddress(): InetAddress? =+        runCatching {+            NetworkInterface.getNetworkInterfaces()+                .asSequence()+                .filter { it.isUp && !it.isLoopback }+                .flatMap { it.inetAddresses.asSequence() }+                .firstOrNull {+                    it.address.size == 4 && !it.isLoopbackAddress && !it.isLinkLocalAddress+                }+        }.getOrNull()++    private fun randomToken(): String {+        val bytes = ByteArray(16)+        SecureRandom().nextBytes(bytes)+        return bytes.joinToString("") { "%02x".format(it) }+    }+}
cast/src/main/java/com/vayunmathur/cast/platform/CastController.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/platform/CastController.kt b/cast/src/main/java/com/vayunmathur/cast/platform/CastController.ktnew file mode 100644index 0000000000..05ef2aefb9--- /dev/null+++ b/cast/src/main/java/com/vayunmathur/cast/platform/CastController.kt@@ -0,0 +1,373 @@+package com.vayunmathur.cast.platform++import android.content.Context+import android.net.Uri+import android.util.Log+import com.vayunmathur.cast.R+import com.vayunmathur.cast.domain.CastDevice+import com.vayunmathur.cast.domain.CastFrame+import com.vayunmathur.cast.domain.CastMediaInformation+import com.vayunmathur.cast.domain.CastMediaMetadata+import com.vayunmathur.cast.domain.CastNamespaces+import com.vayunmathur.cast.domain.CastPhase+import com.vayunmathur.cast.domain.CastPlayerState+import com.vayunmathur.cast.domain.CastSession+import com.vayunmathur.cast.domain.CastSessionState+import com.vayunmathur.cast.domain.DEFAULT_MEDIA_RECEIVER_APP_ID+import com.vayunmathur.cast.domain.MirroringAppIds+import com.vayunmathur.cast.network.CastChannel+import com.vayunmathur.cast.network.MediaFileServer+import com.vayunmathur.cast.platform.discovery.CastDiscoveryManager+import com.vayunmathur.cast.service.CastService+import com.vayunmathur.library.util.AppMessages+import kotlinx.coroutines.CancellationException+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Job+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.delay+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.launch+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock++private const val TAG = "CastController"++/**+ * The receiver drops a channel it has not heard from in roughly ten seconds, so this has to+ * stay comfortably under that even when the app is doing nothing.+ */+private const val HEARTBEAT_INTERVAL_MS = 5_000L++/**+ * MEDIA_STATUS is pushed when the player state changes but not as time passes, so the position+ * has to be asked for. One second is what makes a progress bar look live.+ */+private const val MEDIA_POLL_INTERVAL_MS = 1_000L++/** THROWAWAY (Phase 0): everything `CastSession.onMessage` has a branch for. */+private val HANDLED_NAMESPACES = setOf(+    CastNamespaces.CONNECTION,+    CastNamespaces.HEARTBEAT,+    CastNamespaces.RECEIVER,+    CastNamespaces.MEDIA,+    CastNamespaces.WEBRTC,+)++/**+ * The single owner of the live cast session.+ *+ * An object rather than ViewModel-owned state, because both [CastViewModel] and [CastService]+ * act on the same session and neither reliably outlives the other: rotating the device rebuilds+ * the ViewModel, and the service is what keeps the session alive while the app is not in front.+ * `:share`'s `ShareReceiveController` exists for the same reason.+ *+ * Everything that touches [CastSession] happens under [mutex] on [scope], because the session is+ * a plain mutable state machine and the frames it returns have to reach the socket in the order+ * it produced them.+ */+object CastController {++    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)+    private val mutex = Mutex()++    private var channel: CastChannel? = null+    private var session: CastSession? = null+    private var fileServer: MediaFileServer? = null+    private var pumpJob: Job? = null+    private var heartbeatJob: Job? = null+    private var pollJob: Job? = null++    /** THROWAWAY (Phase 0): waits for the mirroring app to join, then sends one OFFER. */+    private var spikeJob: Job? = null++    private var discoveryManager: CastDiscoveryManager? = null++    private val _device = MutableStateFlow<CastDevice?>(null)+    val device: StateFlow<CastDevice?> = _device.asStateFlow()++    private val _sessionState = MutableStateFlow(CastSessionState())+    val sessionState: StateFlow<CastSessionState> = _sessionState.asStateFlow()++    /** True from the moment a device is tapped until the app on it is joined or refuses. */+    private val _isConnecting = MutableStateFlow(false)+    val isConnecting: StateFlow<Boolean> = _isConnecting.asStateFlow()++    fun discovery(context: Context): CastDiscoveryManager =+        discoveryManager ?: CastDiscoveryManager(context.applicationContext)+            .also { discoveryManager = it }++    /**+     * Open a channel to [device] and launch the media receiver on it.+     *+     * A no-op for the device already connected to; switching devices tears the old session down+     * first, since a sender holds one session at a time.+     */+    fun connect(context: Context, device: CastDevice) {+        if (_device.value?.id == device.id && _sessionState.value.phase != CastPhase.Idle) return+        openSession(context, device, DEFAULT_MEDIA_RECEIVER_APP_ID)+    }++    /**+     * THROWAWAY (Phase 0): launch a Cast Streaming receiver instead of the media receiver and+     * put one hand-written OFFER on the `webrtc` namespace.+     *+     * The only question it answers is whether an unregistered sender is allowed to launch these+     * app ids at all. Deleted in Phase 1 whichever way that goes; nothing is built on top of it+     * until it comes back green.+     *+     * Unguarded by the same-device check [connect] has, because trying the next app id on the+     * device already connected to is the whole point.+     */+    fun spikeMirror(context: Context, device: CastDevice, appId: String) {+        openSession(context, device, appId)+    }++    private fun openSession(context: Context, device: CastDevice, appId: String) {+        val appContext = context.applicationContext+        scope.launch {+            teardown()+            _device.value = device+            _isConnecting.value = true+            val newChannel = CastChannel(device.host, device.port)+            val newSession = CastSession(appId)+            try {+                newChannel.connect()+            } catch (e: Exception) {+                Log.w(TAG, "could not open a channel to ${device.host}", e)+                _isConnecting.value = false+                _device.value = null+                AppMessages.show(+                    appContext.getString(R.string.cast_connect_failed, device.friendlyName),+                )+                return@launch+            }+            channel = newChannel+            session = newSession+            fileServer = MediaFileServer(appContext.contentResolver)+            startPump(appContext, newChannel, newSession)+            send(newChannel, newSession) { it.open() }+            heartbeatJob = scope.launch {+                while (true) {+                    delay(HEARTBEAT_INTERVAL_MS)+                    send(newChannel, newSession) { listOf(it.heartbeat()) }+                }+            }+            pollJob = scope.launch {+                while (true) {+                    delay(MEDIA_POLL_INTERVAL_MS)+                    if (_sessionState.value.playerState != CastPlayerState.Playing) continue+                    send(newChannel, newSession) { it.refreshMediaStatus() }+                }+            }+            if (appId != DEFAULT_MEDIA_RECEIVER_APP_ID) {+                startSpike(newChannel, newSession, appId)+            }+            // Started only once a channel is actually open, so a failed connection does not+            // leave a notification behind.+            CastService.start(appContext)+        }+    }++    /**+     * THROWAWAY (Phase 0).+     *+     * Waits for the LAUNCH to resolve either way rather than assuming it succeeds, because a+     * refusal is the result the spike is most likely to produce and it has to be legible in the+     * log rather than showing up as an OFFER that never gets an answer.+     */+    private fun startSpike(+        activeChannel: CastChannel,+        activeSession: CastSession,+        appId: String,+    ) {+        activeSession.onWebrtcPayload = { Log.i(TAG, "spike $appId: webrtc <- $it") }+        spikeJob = scope.launch {+            val resolved = _sessionState.first {+                it.phase == CastPhase.Ready || it.phase == CastPhase.Failed+            }+            if (resolved.phase == CastPhase.Failed) {+                Log.w(TAG, "spike $appId: LAUNCH refused, reason=${resolved.failure}")+                return@launch+            }+            Log.i(+                TAG,+                "spike $appId: launched, sessionId=${resolved.sessionId} " ++                    "transportId=${resolved.transportId}",+            )+            val audioOnly = MirroringAppIds.isAudioOnly(appId)+            send(activeChannel, activeSession) { session ->+                session.sendSpikeOffer(audioOnly).onEach {+                    Log.i(TAG, "spike $appId: webrtc -> ${it.payload}")+                }+            }+        }+    }++    /** Stop the receiver app, close the channel and the file server, and drop the session. */+    fun disconnect(context: Context) {+        val appContext = context.applicationContext+        scope.launch {+            val activeChannel = channel+            val activeSession = session+            if (activeChannel != null && activeSession != null) {+                send(activeChannel, activeSession) { it.close() }+            }+            teardown()+            CastService.stop(appContext)+        }+    }++    /** Cast a remote URL. Nothing is served locally, so the file server stays out of it. */+    fun castUrl(url: String, mimeType: String, title: String?) {+        act { it.load(mediaInformation(url, mimeType, title)) }+    }++    /**+     * Cast a local `content://` URI by serving it over the LAN for the receiver to fetch.+     *+     * Says so and gives up when the file cannot be served: a receiver handed an unreachable URL+     * reports a generic load failure, which is a worse thing to show than the real reason.+     */+    fun castLocalFile(context: Context, uri: Uri, mimeType: String, title: String?) {+        val appContext = context.applicationContext+        scope.launch {+            // Checked before binding a port: starting the server for a session that does not+            // exist would leave the file readable on the LAN with nothing to tear it down.+            if (channel == null || session == null) return@launch+            val server = fileServer+                ?: MediaFileServer(appContext.contentResolver).also { fileServer = it }+            val url = server.start(uri, mimeType)+            if (url == null) {+                AppMessages.show(appContext.getString(R.string.cast_server_failed))+                return@launch+            }+            act { it.load(mediaInformation(url, mimeType, title)) }+        }+    }++    fun play() = act { it.play() }++    fun pause() = act { it.pause() }++    fun stopPlayback() = act { it.stopMedia() }++    fun seek(positionSec: Double) = act { it.seek(positionSec) }++    fun setVolume(level: Double) = act { it.setVolume(level) }++    fun setMuted(muted: Boolean) = act { it.setMuted(muted) }++    private fun mediaInformation(url: String, mimeType: String, title: String?) =+        CastMediaInformation(+            contentId = url,+            contentType = mimeType,+            metadata = title?.let { CastMediaMetadata(title = it) },+        )++    /** Run [block] against the live session, if there is one, and send what it produces. */+    private fun act(block: (CastSession) -> List<CastFrame>) {+        scope.launch {+            val activeChannel = channel ?: return@launch+            val activeSession = session ?: return@launch+            send(activeChannel, activeSession, block)+        }+    }++    private suspend fun send(+        activeChannel: CastChannel,+        activeSession: CastSession,+        block: (CastSession) -> List<CastFrame>,+    ) = mutex.withLock {+        val frames = block(activeSession)+        publish(activeSession)+        for (frame in frames) {+            try {+                activeChannel.send(frame)+            } catch (e: Exception) {+                Log.w(TAG, "send failed on ${frame.namespace}", e)+                break+            }+        }+    }++    private fun startPump(+        context: Context,+        activeChannel: CastChannel,+        activeSession: CastSession,+    ) {+        pumpJob = scope.launch {+            try {+                activeChannel.messages().collect { message ->+                    // THROWAWAY (Phase 0): a `tp.deviceauth` challenge would otherwise be+                    // dropped in silence - CastSession ignores namespaces it does not know and+                    // the payload is protobuf, not JSON, so it fails to parse before it is even+                    // routed. Whether one arrives decides whether mirroring needs a whole+                    // sub-project, so it has to be visible.+                    if (message.namespace !in HANDLED_NAMESPACES) {+                        Log.i(TAG, "unhandled namespace ${message.namespace}")+                    }+                    mutex.withLock {+                        val replies =+                            activeSession.onMessage(message.namespace, message.payloadUtf8)+                        publish(activeSession)+                        replies.forEach { activeChannel.send(it) }+                    }+                }+                Log.i(TAG, "channel closed by the receiver")+            } catch (e: CancellationException) {+                // Cancelled by teardown, which is already doing all of this - and by the time+                // we get here a *newer* channel and session may already be installed, so+                // tearing down again would wipe a session that has only just come up.+                throw e+            } catch (e: Exception) {+                Log.w(TAG, "channel read loop ended", e)+            }+            // The link died on its own. Clearing the reference first matters: teardown cancels+            // pumpJob, and this coroutine *is* pumpJob.+            pumpJob = null+            teardown()+            CastService.stop(context)+        }+    }++    private fun publish(activeSession: CastSession) {+        val state = activeSession.state+        _sessionState.value = state+        if (state.phase == CastPhase.Ready || state.phase == CastPhase.Failed) {+            _isConnecting.value = false+        }+    }++    /**+     * Drop everything.+     *+     * The socket and the file server are closed *before* [mutex] is taken, because closing is+     * what unblocks a reader or writer parked in the socket - and one of those may be the+     * coroutine currently holding the lock. The state reset then happens under the lock, so an+     * in-flight [send] cannot publish the dead session's state back over the cleared one.+     */+    private suspend fun teardown() {+        pumpJob?.cancel()+        heartbeatJob?.cancel()+        pollJob?.cancel()+        spikeJob?.cancel()+        channel?.close()+        fileServer?.stop()+        mutex.withLock {+            pumpJob = null+            heartbeatJob = null+            pollJob = null+            spikeJob = null+            fileServer = null+            channel = null+            session = null+            _device.value = null+            _isConnecting.value = false+            _sessionState.value = CastSessionState()+        }+    }+}
cast/src/main/java/com/vayunmathur/cast/platform/CastUiContract.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/platform/CastUiContract.kt b/cast/src/main/java/com/vayunmathur/cast/platform/CastUiContract.ktnew file mode 100644index 0000000000..46d905a64f--- /dev/null+++ b/cast/src/main/java/com/vayunmathur/cast/platform/CastUiContract.kt@@ -0,0 +1,90 @@+package com.vayunmathur.cast.platform++import com.vayunmathur.cast.domain.CastDevice+import com.vayunmathur.cast.domain.CastPlayerState++/**+ * Where the session is, from the point of view of a screen.+ *+ * Flatter than `CastPhase`: a screen does not care whether LAUNCH or the second CONNECT is+ * outstanding, only whether it can offer transport controls yet.+ */+enum class CastConnection { Disconnected, Connecting, Connected, Failed }++/** What the user has chosen to cast, before or after a device is picked. */+sealed interface CastSource {+    val label: String+    val mimeType: String++    /** A `content://` URI from the picker or the share sheet; served by `MediaFileServer`. */+    data class LocalFile(+        val uri: String,+        override val label: String,+        override val mimeType: String,+    ) : CastSource++    data class RemoteUrl(+        val url: String,+        override val label: String,+        override val mimeType: String,+    ) : CastSource+}++/**+ * Everything the Cast screens draw.+ *+ * Every field is defaulted so a `@Preview` can build one from the parts it cares about - which+ * is what the store-listing images are rendered from (see `src/screenshotTest`). It lives beside+ * the ViewModel so the dependency runs one way: `ui` depends on this, and the ViewModel+ * implements [CastActions].+ */+data class CastUiState(+    val devices: List<CastDevice> = emptyList(),+    val isScanning: Boolean = false,+    /**+     * Android 16+ blocked the mDNS browse. Distinct from an empty list, because the fix is a+     * permission rather than turning the TV on.+     */+    val localNetworkBlocked: Boolean = false,+    val connectedDevice: CastDevice? = null,+    val connection: CastConnection = CastConnection.Disconnected,+    /** Held until a device is picked, so choosing a file first is allowed. */+    val pendingSource: CastSource? = null,+    val playerState: CastPlayerState = CastPlayerState.Idle,+    val title: String? = null,+    val positionSec: Double = 0.0,+    /** Null for a live stream or until the receiver reports one. */+    val durationSec: Double? = null,+    val volumeLevel: Double = 1.0,+    val muted: Boolean = false,+) {+    /** Transport controls are meaningless without something loaded on the receiver. */+    val hasMedia: Boolean get() = playerState != CastPlayerState.Idle || title != null+}++interface CastActions {+    fun startScan() {}+    fun stopScan() {}+    fun connect(device: CastDevice) {}+    fun disconnect() {}+    fun pickLocalFile(uri: String) {}+    fun castUrl(url: String) {}+    fun clearPendingSource() {}+    fun play() {}+    fun pause() {}+    fun stopPlayback() {}+    fun seek(positionSec: Double) {}+    fun setVolume(level: Double) {}+    fun setMuted(muted: Boolean) {}+    fun openLocalNetworkSettings() {}++    /**+     * THROWAWAY (Phase 0): relaunch the connected device with a Cast Streaming app id and send+     * one OFFER, to find out whether an unregistered sender is allowed to do that.+     */+    fun spikeMirror(appId: String) {}++    companion object {+        val Noop: CastActions = object : CastActions {}+    }+}
cast/src/main/java/com/vayunmathur/cast/platform/CastViewModel.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/platform/CastViewModel.kt b/cast/src/main/java/com/vayunmathur/cast/platform/CastViewModel.ktnew file mode 100644index 0000000000..005e1c901f--- /dev/null+++ b/cast/src/main/java/com/vayunmathur/cast/platform/CastViewModel.kt@@ -0,0 +1,258 @@+package com.vayunmathur.cast.platform++import android.app.Application+import android.content.Context+import android.content.Intent+import android.net.Uri+import android.provider.OpenableColumns+import android.provider.Settings+import android.util.Log+import androidx.core.net.toUri+import androidx.lifecycle.AndroidViewModel+import androidx.lifecycle.ViewModel+import androidx.lifecycle.ViewModelProvider+import androidx.lifecycle.viewModelScope+import com.vayunmathur.cast.R+import com.vayunmathur.cast.domain.CastDevice+import com.vayunmathur.cast.domain.CastPhase+import com.vayunmathur.library.ui.ExternalIntents+import com.vayunmathur.library.util.AppMessages+import kotlinx.coroutines.Job+import kotlinx.coroutines.delay+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.SharingStarted+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.combine+import kotlinx.coroutines.flow.stateIn+import kotlinx.coroutines.launch++private const val TAG = "CastVM"++/** What the Default Media Receiver is given when the URI has no type of its own. */+private const val FALLBACK_MIME_TYPE = "video/mp4"++/**+ * How long the toolbar reports "searching".+ *+ * mDNS keeps answering for as long as it is asked, so there is no point at which discovery is+ * genuinely finished; this is just how long a receiver on the network takes to answer, after+ * which a still-empty list means something is wrong rather than slow.+ */+private const val SCAN_INDICATOR_MS = 6_000L++/**+ * ViewModel for the Cast app.+ *+ * Owns no session state: [CastController] does, because the session outlives this ViewModel and+ * is shared with `CastService`. What lives here is what belongs to the screen - whether a scan is+ * running and which source the user has chosen but not yet cast.+ *+ * A source picked before a device is deliberately kept rather than rejected: "choose a file, then+ * choose a screen" is the order the share sheet forces anyway, so both orders work and+ * [CastUiState.pendingSource] is cast automatically as soon as a receiver is joined.+ */+class CastViewModel(application: Application) : AndroidViewModel(application), CastActions {++    private val appContext: Context get() = getApplication()+    private val discovery get() = CastController.discovery(appContext)++    private val _isScanning = MutableStateFlow(false)+    private val _pendingSource = MutableStateFlow<CastSource?>(null)++    private var scanJob: Job? = null++    private val discoveryState = combine(+        discovery.devices,+        _isScanning,+        discovery.localNetworkBlocked,+    ) { devices, scanning, blocked ->+        // Sorted so the list does not reshuffle every time a device re-announces itself.+        Triple(devices.sortedBy { it.friendlyName.lowercase() }, scanning, blocked)+    }++    val uiState: StateFlow<CastUiState> = combine(+        discoveryState,+        CastController.device,+        CastController.isConnecting,+        CastController.sessionState,+        _pendingSource,+    ) { (devices, scanning, blocked), device, connecting, session, pending ->+        CastUiState(+            devices = devices,+            isScanning = scanning,+            localNetworkBlocked = blocked,+            connectedDevice = device,+            connection = when {+                session.phase == CastPhase.Failed -> CastConnection.Failed+                connecting -> CastConnection.Connecting+                device != null && session.phase == CastPhase.Ready -> CastConnection.Connected+                else -> CastConnection.Disconnected+            },+            pendingSource = pending,+            playerState = session.playerState,+            title = session.title,+            positionSec = session.currentTimeSec,+            durationSec = session.durationSec,+            volumeLevel = session.volumeLevel,+            muted = session.muted,+        )+    }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), CastUiState())++    init {+        // Cast whatever is waiting the moment a receiver is joined, so the two "pick" steps can+        // happen in either order.+        viewModelScope.launch {+            CastController.sessionState.collect { state ->+                if (state.phase != CastPhase.Ready) return@collect+                val source = _pendingSource.value ?: return@collect+                _pendingSource.value = null+                dispatchSource(source)+            }+        }+    }++    override fun startScan() {+        // Restart rather than ignore: the refresh button has to do something when the browse is+        // already running, and a second collector on the same manager would double every device.+        scanJob?.cancel()+        _isScanning.value = true+        discovery.clear()+        scanJob = viewModelScope.launch {+            // The browse itself keeps running for as long as the screen is open, so devices+            // appear and disappear as they are switched on and off. Only the "searching"+            // indicator is time-boxed - left on it would spin forever and the refresh button+            // would never come back.+            launch {+                delay(SCAN_INDICATOR_MS)+                _isScanning.value = false+            }+            try {+                discovery.discover().collect { }+            } catch (e: Exception) {+                Log.w(TAG, "discovery ended", e)+            }+            _isScanning.value = false+        }+    }++    override fun stopScan() {+        scanJob?.cancel()+        scanJob = null+        _isScanning.value = false+    }++    override fun connect(device: CastDevice) = CastController.connect(appContext, device)++    override fun disconnect() = CastController.disconnect(appContext)++    override fun pickLocalFile(uri: String) {+        val parsed = uri.toUri()+        val mimeType = appContext.contentResolver.getType(parsed) ?: FALLBACK_MIME_TYPE+        val label = displayName(appContext, parsed) ?: parsed.lastPathSegment ?: uri+        setSource(CastSource.LocalFile(uri, label, mimeType))+    }++    override fun castUrl(url: String) {+        val trimmed = url.trim()+        if (!trimmed.startsWith("http://") && !trimmed.startsWith("https://")) {+            AppMessages.show(appContext.getString(R.string.cast_url_invalid))+            return+        }+        val label = trimmed.toUri().lastPathSegment?.takeIf { it.isNotBlank() } ?: trimmed+        setSource(CastSource.RemoteUrl(trimmed, label, guessMimeType(trimmed)))+    }++    override fun clearPendingSource() {+        _pendingSource.value = null+    }++    override fun play() = CastController.play()++    override fun pause() = CastController.pause()++    override fun stopPlayback() = CastController.stopPlayback()++    override fun seek(positionSec: Double) = CastController.seek(positionSec)++    override fun setVolume(level: Double) = CastController.setVolume(level)++    override fun setMuted(muted: Boolean) = CastController.setMuted(muted)++    /**+     * There is no intent for the local-network toggle itself, so this opens the app's own+     * settings page, where the permission lives.+     */+    override fun openLocalNetworkSettings() {+        val intent = Intent(+            Settings.ACTION_APPLICATION_DETAILS_SETTINGS,+            "package:${appContext.packageName}".toUri(),+        ).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+        ExternalIntents.launch(appContext, intent)+    }++    /** THROWAWAY (Phase 0). Needs a device, so it reuses the one already selected. */+    override fun spikeMirror(appId: String) {+        // CastController rather than uiState: stateIn stops updating when nothing is collecting.+        val device = CastController.device.value ?: return+        CastController.spikeMirror(appContext, device, appId)+    }++    /** Cast now if a receiver is joined, otherwise hold it until one is. */+    private fun setSource(source: CastSource) {+        if (uiState.value.connection == CastConnection.Connected) {+            dispatchSource(source)+        } else {+            _pendingSource.value = source+        }+    }++    private fun dispatchSource(source: CastSource) {+        when (source) {+            is CastSource.LocalFile -> CastController.castLocalFile(+                appContext,+                source.uri.toUri(),+                source.mimeType,+                source.label,+            )+            is CastSource.RemoteUrl ->+                CastController.castUrl(source.url, source.mimeType, source.label)+        }+    }++    /**+     * Best guess from the extension, because a remote URL's real type is not known until the+     * receiver fetches it - and the receiver needs a `contentType` in the LOAD request.+     */+    private fun guessMimeType(url: String): String = when {+        url.endsWith(".mp3", ignoreCase = true) -> "audio/mpeg"+        url.endsWith(".m4a", ignoreCase = true) -> "audio/mp4"+        url.endsWith(".aac", ignoreCase = true) -> "audio/aac"+        url.endsWith(".flac", ignoreCase = true) -> "audio/flac"+        url.endsWith(".wav", ignoreCase = true) -> "audio/wav"+        url.endsWith(".webm", ignoreCase = true) -> "video/webm"+        url.endsWith(".mkv", ignoreCase = true) -> "video/x-matroska"+        url.endsWith(".jpg", ignoreCase = true) || url.endsWith(".jpeg", ignoreCase = true) ->+            "image/jpeg"+        url.endsWith(".png", ignoreCase = true) -> "image/png"+        url.endsWith(".m3u8", ignoreCase = true) -> "application/x-mpegurl"+        else -> FALLBACK_MIME_TYPE+    }+}++internal fun displayName(context: Context, uri: Uri): String? = try {+    context.contentResolver+        .query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)+        ?.use { cursor -> if (cursor.moveToFirst()) cursor.getString(0) else null }+} catch (_: Exception) {+    null+}++class CastViewModelFactory(private val application: Application) : ViewModelProvider.Factory {+    @Suppress("UNCHECKED_CAST")+    override fun <T : ViewModel> create(modelClass: Class<T>): T {+        require(modelClass.isAssignableFrom(CastViewModel::class.java)) {+            "Unknown ViewModel class $modelClass"+        }+        return CastViewModel(application) as T+    }+}
cast/src/main/java/com/vayunmathur/cast/platform/discovery/CastDiscoveryManager.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/platform/discovery/CastDiscoveryManager.kt b/cast/src/main/java/com/vayunmathur/cast/platform/discovery/CastDiscoveryManager.ktnew file mode 100644index 0000000000..5f37701045--- /dev/null+++ b/cast/src/main/java/com/vayunmathur/cast/platform/discovery/CastDiscoveryManager.kt@@ -0,0 +1,186 @@+package com.vayunmathur.cast.platform.discovery++import android.content.Context+import android.net.nsd.NsdManager+import android.net.nsd.NsdServiceInfo+import android.util.Log+import com.vayunmathur.cast.domain.CAST_PORT+import com.vayunmathur.cast.domain.CastDevice+import kotlinx.coroutines.channels.awaitClose+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.flow.callbackFlow+import kotlinx.coroutines.flow.update++private const val TAG = "CastDiscovery"++/** Every Cast receiver - Chromecast, Google TV, Nest speaker - registers this service type. */+const val CAST_SERVICE_TYPE = "_googlecast._tcp"++/** Friendly name, e.g. "Living Room TV". The instance name is a UUID and unreadable. */+private const val TXT_FRIENDLY_NAME = "fn"++/** Hardware model, e.g. "Chromecast Ultra". Shown as the list subtitle. */+private const val TXT_MODEL = "md"++/** The receiver's own UUID. Stable across renames, unlike the instance name. */+private const val TXT_ID = "id"++/** Capability bitmask; see [CastDevice.kind]. */+private const val TXT_CAPABILITIES = "ca"++/** Current status, e.g. "YouTube" or blank when idle. */+private const val TXT_STATUS = "rs"++/**+ * mDNS discovery of Cast receivers on the LAN.+ *+ * Browse-only - nothing is advertised, because a sender is not itself castable. Adapted from+ * `:share`'s `NsdDiscoveryManager`, including the Android 16 trap it documents: with Local+ * Network Protections, `discoverServices` throws `SecurityException` unless+ * `ACCESS_LOCAL_NETWORK` has been granted, and the failure is indistinguishable from "no+ * devices on this network" unless it is surfaced. [localNetworkBlocked] exists so the UI can+ * say which of the two happened instead of showing an empty list forever.+ */+class CastDiscoveryManager(context: Context) {++    private val nsdManager: NsdManager? =+        context.getSystemService(Context.NSD_SERVICE) as? NsdManager++    private var discoveryListener: NsdManager.DiscoveryListener? = null++    private val _devices = MutableStateFlow<List<CastDevice>>(emptyList())+    val devices: StateFlow<List<CastDevice>> = _devices.asStateFlow()++    /** True when the platform refused the browse, not when the network is simply empty. */+    private val _localNetworkBlocked = MutableStateFlow(false)+    val localNetworkBlocked: StateFlow<Boolean> = _localNetworkBlocked.asStateFlow()++    /**+     * Browse [CAST_SERVICE_TYPE] and emit each resolved receiver.+     *+     * Cancelling the collection stops the browse. Devices also accumulate in [devices], which+     * is what the list observes, so a caller that only wants the state can collect and drop.+     */+    fun discover(): Flow<CastDevice> = callbackFlow {+        val manager = nsdManager ?: run {+            Log.w(TAG, "NsdManager unavailable - cannot browse for receivers")+            close()+            return@callbackFlow+        }+        val listener = object : NsdManager.DiscoveryListener {+            override fun onDiscoveryStarted(serviceType: String) {+                _localNetworkBlocked.value = false+            }++            override fun onServiceFound(service: NsdServiceInfo) {+                try {+                    manager.resolveService(service, object : NsdManager.ResolveListener {+                        override fun onResolveFailed(info: NsdServiceInfo, errorCode: Int) {+                            Log.w(TAG, "resolve failed for ${info.serviceName}: $errorCode")+                        }++                        override fun onServiceResolved(info: NsdServiceInfo) {+                            val device = toCastDevice(info) ?: return+                            trySend(device)+                            // update, not value =: resolve callbacks arrive on several threads+                            // and a read-modify-write would drop devices found at once.+                            _devices.update { merge(it, device) }+                        }+                    })+                } catch (e: Exception) {+                    Log.w(TAG, "resolveService threw for ${service.serviceName}", e)+                }+            }++            override fun onServiceLost(service: NsdServiceInfo) {+                // Only the instance name is available here, so match on it rather than on the+                // UUID; the two are one-to-one for the lifetime of a registration.+                val name = service.serviceName ?: return+                _devices.update { devices -> devices.filterNot { it.instanceName == name } }+            }++            override fun onDiscoveryStopped(serviceType: String) = Unit++            override fun onStartDiscoveryFailed(serviceType: String, errorCode: Int) {+                Log.w(TAG, "startDiscovery failed: $errorCode")+                close()+            }++            override fun onStopDiscoveryFailed(serviceType: String, errorCode: Int) {+                Log.w(TAG, "stopDiscovery failed: $errorCode")+            }+        }+        discoveryListener = listener+        try {+            manager.discoverServices(CAST_SERVICE_TYPE, NsdManager.PROTOCOL_DNS_SD, listener)+        } catch (e: SecurityException) {+            // Android 16+ Local Network Protections. Nothing is wrong with the request; the+            // OS blocks mDNS outright until ACCESS_LOCAL_NETWORK is granted.+            Log.e(TAG, "mDNS browse blocked - ACCESS_LOCAL_NETWORK not granted", e)+            _localNetworkBlocked.value = true+            discoveryListener = null+            close()+            return@callbackFlow+        } catch (e: Exception) {+            Log.w(TAG, "discoverServices threw", e)+            discoveryListener = null+            close(e)+            return@callbackFlow+        }+        awaitClose {+            try {+                discoveryListener?.let { manager.stopServiceDiscovery(it) }+            } catch (_: Exception) {+            }+            discoveryListener = null+        }+    }++    fun clear() {+        _devices.value = emptyList()+    }++    private fun textAttribute(info: NsdServiceInfo, key: String): String? =+        runCatching { info.attributes[key]?.toString(Charsets.UTF_8) }+            .getOrNull()+            ?.takeIf { it.isNotBlank() }++    /**+     * Turn a resolved record into a [CastDevice], or null when it is not usable.+     *+     * A host is mandatory - the whole point of resolving is to get one - but everything else+     * has a sensible fallback, because a receiver with an odd TXT record is still castable.+     */+    private fun toCastDevice(info: NsdServiceInfo): CastDevice? {+        val host = info.host?.hostAddress ?: return null+        val instance = info.serviceName ?: return null+        val friendlyName = textAttribute(info, TXT_FRIENDLY_NAME)+            ?: textAttribute(info, TXT_MODEL)+            ?: instance+        return CastDevice(+            id = textAttribute(info, TXT_ID) ?: instance,+            instanceName = instance,+            friendlyName = friendlyName,+            host = host,+            port = if (info.port > 0) info.port else CAST_PORT,+            model = textAttribute(info, TXT_MODEL),+            statusText = textAttribute(info, TXT_STATUS),+            capabilities = textAttribute(info, TXT_CAPABILITIES)?.toIntOrNull() ?: 0,+        )+    }++    /**+     * Replace by [CastDevice.id] rather than append.+     *+     * A receiver re-announces itself when its status text changes, and every announcement+     * resolves, so appending would show the same TV three times.+     */+    private fun merge(current: List<CastDevice>, device: CastDevice): List<CastDevice> {+        val index = current.indexOfFirst { it.id == device.id }+        if (index < 0) return current + device+        return current.toMutableList().apply { this[index] = device }+    }+}
cast/src/main/java/com/vayunmathur/cast/service/CastService.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/service/CastService.kt b/cast/src/main/java/com/vayunmathur/cast/service/CastService.ktnew file mode 100644index 0000000000..ee32308b26--- /dev/null+++ b/cast/src/main/java/com/vayunmathur/cast/service/CastService.kt@@ -0,0 +1,184 @@+package com.vayunmathur.cast.service++import android.app.Notification+import android.app.NotificationManager+import android.app.PendingIntent+import android.app.Service+import android.content.Context+import android.content.Intent+import android.content.pm.ServiceInfo+import android.os.Build+import android.os.IBinder+import android.util.Log+import androidx.core.app.NotificationCompat+import androidx.core.content.getSystemService+import com.vayunmathur.cast.MainActivity+import com.vayunmathur.cast.R+import com.vayunmathur.cast.domain.CastPlayerState+import com.vayunmathur.cast.platform.CastController+import com.vayunmathur.library.util.ensureNotificationChannel+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.cancel+import kotlinx.coroutines.flow.combine+import kotlinx.coroutines.launch++private const val TAG = "CastService"++/**+ * `IMPORTANCE_LOW`: an open cast session is a status indicator, not an event, so it must never+ * make a sound. There is nothing else on this channel for a user who silences it to lose.+ */+private const val CHANNEL_ID = "cast_session"++private const val NOTIF_ID = 4201++/**+ * Keeps the cast session alive while the app is not in front.+ *+ * A lifecycle host with no session state of its own: [CastController] owns the socket, the file+ * server and the session, so this can be started and stopped freely. `START_NOT_STICKY` rather+ * than sticky, because a restarted service has nothing to restore - the TLS channel died with+ * the process and the receiver has already dropped it.+ *+ * The foreground type is `mediaPlayback`, which is what Android's own documentation lists for+ * casting. `dataSync` is unusable: Android 15 caps it at six cumulative hours per 24 h and then+ * calls `onTimeout()`, which for a long film would stop the service part-way through.+ */+class CastService : Service() {++    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main)++    /** Guards against a second onStartCommand registering the status collector twice. */+    private var collecting = false++    override fun onBind(intent: Intent?): IBinder? = null++    override fun onCreate() {+        super.onCreate()+        ensureNotificationChannel(+            CHANNEL_ID,+            getString(R.string.cast_notification_channel_name),+            importance = NotificationManager.IMPORTANCE_LOW,+            description = getString(R.string.cast_notification_channel_desc),+        )+    }++    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {+        // Before anything else: this is started with startForegroundService, and the platform+        // kills a process that does not honour that within a few seconds.+        enterForeground()+        if (intent?.action == ACTION_STOP) {+            CastController.disconnect(this)+            return START_NOT_STICKY+        }+        if (!collecting) {+            collecting = true+            // One collector for the lifetime of the service, so the notification tracks what is+            // playing instead of freezing on whatever was true when it started.+            scope.launch {+                CastController.device+                    .combine(CastController.sessionState) { device, state -> device to state }+                    .collect { (device, state) ->+                        if (device == null) return@collect+                        val text = state.title ?: when (state.playerState) {+                            CastPlayerState.Playing -> getString(R.string.cast_state_playing)+                            CastPlayerState.Paused -> getString(R.string.cast_state_paused)+                            CastPlayerState.Buffering -> getString(R.string.cast_state_buffering)+                            CastPlayerState.Idle -> getString(R.string.cast_notification_text_idle)+                        }+                        getSystemService<NotificationManager>()+                            ?.notify(NOTIF_ID, buildNotification(device.friendlyName, text))+                    }+            }+        }+        return START_NOT_STICKY+    }++    override fun onDestroy() {+        super.onDestroy()+        scope.cancel()+    }++    /**+     * Android 15's cumulative-runtime timeout. `mediaPlayback` is not capped, so this should+     * never fire; if a future platform version caps it anyway, tearing the session down cleanly+     * beats being killed with a socket open.+     */+    override fun onTimeout(startId: Int, fgsType: Int) {+        Log.w(TAG, "foreground service timed out (type $fgsType)")+        CastController.disconnect(this)+    }++    private fun enterForeground() {+        val device = CastController.device.value+        val notification = buildNotification(+            device?.friendlyName ?: getString(R.string.app_name),+            getString(R.string.cast_notification_text_idle),+        )+        try {+            if (Build.VERSION.SDK_INT >= 34) {+                startForeground(+                    NOTIF_ID,+                    notification,+                    ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK,+                )+            } else {+                @Suppress("DEPRECATION")+                startForeground(NOTIF_ID, notification)+            }+        } catch (e: Exception) {+            // A background start the platform refuses. Nothing to recover: the session itself is+            // unaffected, it just will not survive the app being backgrounded.+            Log.w(TAG, "could not enter the foreground", e)+        }+    }++    private fun buildNotification(deviceName: String, text: String): Notification {+        val open = PendingIntent.getActivity(+            this,+            0,+            Intent(this, MainActivity::class.java).apply {+                flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP+            },+            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,+        )+        val stop = PendingIntent.getService(+            this,+            1,+            Intent(this, CastService::class.java).setAction(ACTION_STOP),+            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,+        )+        return NotificationCompat.Builder(this, CHANNEL_ID)+            .setSmallIcon(R.drawable.ic_cast)+            .setContentTitle(getString(R.string.cast_notification_title, deviceName))+            .setContentText(text)+            .setOngoing(true)+            .setContentIntent(open)+            .addAction(R.drawable.ic_cast, getString(R.string.cast_notification_action_stop), stop)+            .build()+    }++    companion object {+        /** Ends the session from the notification's own action. */+        const val ACTION_STOP = "com.vayunmathur.cast.action.STOP"++        fun start(context: Context) {+            launch(context, Intent(context, CastService::class.java))+        }++        fun stop(context: Context) {+            context.stopService(Intent(context, CastService::class.java))+        }++        private fun launch(context: Context, intent: Intent) {+            try {+                context.startForegroundService(intent)+            } catch (_: Exception) {+                // Refused because the app is in the background with no exemption. The session+                // still works; it just will not outlive the Activity.+            }+        }+    }+}
cast/src/main/java/com/vayunmathur/cast/ui/CastContent.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/ui/CastContent.kt b/cast/src/main/java/com/vayunmathur/cast/ui/CastContent.ktnew file mode 100644index 0000000000..fcee71f5ae--- /dev/null+++ b/cast/src/main/java/com/vayunmathur/cast/ui/CastContent.kt@@ -0,0 +1,164 @@+package com.vayunmathur.cast.ui++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import com.vayunmathur.cast.R+import com.vayunmathur.cast.platform.CastActions+import com.vayunmathur.cast.platform.CastConnection+import com.vayunmathur.cast.platform.CastUiState+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.CircularProgressIndicator+import com.vayunmathur.library.ui.HorizontalDivider+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconRefresh+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton++/**+ * The whole app: pick a device, pick something to cast, control it.+ *+ * Stateless - state in, [CastActions] out - so the store-listing screenshots can render it from+ * a `@Preview`. [onPickFile] is separate from the actions interface because opening the system+ * document picker needs an `ActivityResultLauncher`, which only a composition inside an Activity+ * can own; a preview passes an empty lambda.+ */+@Composable+fun CastContent(+    state: CastUiState,+    actions: CastActions,+    modifier: Modifier = Modifier,+    onPickFile: () -> Unit = {},+) {+    AppScaffold(+        title = stringResource(R.string.cast_devices_title),+        modifier = modifier,+        actions = {+            if (state.isScanning) {+                CircularProgressIndicator(+                    modifier = Modifier.padding(horizontal = 16.dp).size(24.dp),+                )+            } else {+                IconButton(onClick = actions::startScan) { IconRefresh() }+            }+        },+    ) { padding ->+        LazyColumn(+            modifier = Modifier.fillMaxSize().padding(padding),+            contentPadding = PaddingValues(horizontal = 16.dp, vertical = 12.dp),+            verticalArrangement = Arrangement.spacedBy(12.dp),+        ) {+            if (state.connection == CastConnection.Connected) {+                item { CastNowPlayingCard(state, actions) }+            }+            item { CastSourceCard(state, actions, onPickFile) }+            item { SectionHeader(state, actions) }+            if (state.localNetworkBlocked) {+                item { LocalNetworkBlocked(actions) }+            } else if (state.devices.isEmpty()) {+                item { NoDevices(state) }+            } else {+                items(state.devices, key = { it.id }) { device ->+                    CastDeviceRow(+                        device = device,+                        isConnected = state.connectedDevice?.id == device.id,+                        onClick = { actions.connect(device) },+                    )+                }+            }+        }+    }+}++@Composable+private fun SectionHeader(state: CastUiState, actions: CastActions) {+    Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {+        HorizontalDivider()+        val connected = state.connectedDevice+        when (state.connection) {+            CastConnection.Connecting -> Text(+                stringResource(R.string.cast_connecting_to, connected?.friendlyName ?: ""),+                style = MaterialTheme.typography.titleSmall,+            )+            CastConnection.Connected -> Column {+                Text(+                    stringResource(R.string.cast_connected_to, connected?.friendlyName ?: ""),+                    style = MaterialTheme.typography.titleSmall,+                )+                TextButton(onClick = actions::disconnect) {+                    Text(stringResource(R.string.cast_disconnect))+                }+            }+            CastConnection.Failed -> Text(+                stringResource(R.string.cast_load_failed),+                style = MaterialTheme.typography.titleSmall,+                color = MaterialTheme.colorScheme.error,+            )+            CastConnection.Disconnected -> Text(+                stringResource(R.string.cast_devices_heading),+                style = MaterialTheme.typography.titleSmall,+            )+        }+    }+}++@Composable+private fun NoDevices(state: CastUiState) {+    Column(+        modifier = Modifier.fillMaxWidth().padding(24.dp),+        horizontalAlignment = Alignment.CenterHorizontally,+        verticalArrangement = Arrangement.spacedBy(4.dp),+    ) {+        Text(+            stringResource(+                if (state.isScanning) R.string.cast_searching else R.string.cast_no_devices,+            ),+            style = MaterialTheme.typography.titleMedium,+        )+        Text(+            stringResource(R.string.cast_no_devices_hint),+            style = MaterialTheme.typography.bodyMedium,+            color = MaterialTheme.colorScheme.onSurfaceVariant,+        )+    }+}++/**+ * Android 16 refused the mDNS browse. Called out rather than folded into "no devices found",+ * because nothing about the network or the TV will fix it - only a permission will.+ */+@Composable+private fun LocalNetworkBlocked(actions: CastActions) {+    Column(+        modifier = Modifier.fillMaxWidth().padding(24.dp),+        horizontalAlignment = Alignment.CenterHorizontally,+        verticalArrangement = Arrangement.spacedBy(8.dp),+    ) {+        Text(+            stringResource(R.string.cast_local_network_blocked),+            style = MaterialTheme.typography.titleMedium,+            color = MaterialTheme.colorScheme.error,+        )+        Text(+            stringResource(R.string.cast_local_network_blocked_hint),+            style = MaterialTheme.typography.bodyMedium,+            color = MaterialTheme.colorScheme.onSurfaceVariant,+        )+        Button(onClick = actions::openLocalNetworkSettings) {+            Text(stringResource(R.string.cast_open_settings))+        }+    }+}
cast/src/main/java/com/vayunmathur/cast/ui/CastDeviceRow.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/ui/CastDeviceRow.kt b/cast/src/main/java/com/vayunmathur/cast/ui/CastDeviceRow.ktnew file mode 100644index 0000000000..972bf76b7f--- /dev/null+++ b/cast/src/main/java/com/vayunmathur/cast/ui/CastDeviceRow.kt@@ -0,0 +1,50 @@+package com.vayunmathur.cast.ui++import androidx.compose.foundation.clickable+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import com.vayunmathur.cast.domain.CastDevice+import com.vayunmathur.cast.domain.CastDeviceKind+import com.vayunmathur.library.ui.IconCastConnected+import com.vayunmathur.library.ui.IconSpeaker+import com.vayunmathur.library.ui.IconTv+import com.vayunmathur.library.ui.ListItem+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text++/**+ * One discovered receiver.+ *+ * The leading icon is the device's own [CastDeviceKind], which comes out of the mDNS capability+ * bitmask - a Nest speaker and a Google TV look nothing alike to the user, and showing the same+ * icon for both makes the list unreadable in a house with several of each.+ */+@Composable+fun CastDeviceRow(+    device: CastDevice,+    isConnected: Boolean,+    onClick: () -> Unit,+    modifier: Modifier = Modifier,+) {+    ListItem(+        modifier = modifier.clickable(onClick = onClick),+        leadingContent = {+            when {+                isConnected -> IconCastConnected(tint = MaterialTheme.colorScheme.primary)+                device.kind == CastDeviceKind.Tv -> IconTv()+                else -> IconSpeaker()+            }+        },+        supportingContent = subtitle(device)?.let { { Text(it) } },+        content = { Text(device.friendlyName) },+    )+}++/**+ * Model plus status, but only the parts that exist: an idle receiver publishes no `rs`, and an+ * empty second line makes the rows different heights for no reason.+ */+private fun subtitle(device: CastDevice): String? = listOfNotNull(+    device.model?.takeIf { it.isNotBlank() },+    device.statusText?.takeIf { it.isNotBlank() },+).takeIf { it.isNotEmpty() }?.joinToString(" - ")
cast/src/main/java/com/vayunmathur/cast/ui/CastNowPlayingCard.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/ui/CastNowPlayingCard.kt b/cast/src/main/java/com/vayunmathur/cast/ui/CastNowPlayingCard.ktnew file mode 100644index 0000000000..f71b05413c--- /dev/null+++ b/cast/src/main/java/com/vayunmathur/cast/ui/CastNowPlayingCard.kt@@ -0,0 +1,147 @@+package com.vayunmathur.cast.ui++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import com.vayunmathur.cast.R+import com.vayunmathur.cast.domain.CastPlayerState+import com.vayunmathur.cast.platform.CastActions+import com.vayunmathur.cast.platform.CastUiState+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconPause+import com.vayunmathur.library.ui.IconPlay+import com.vayunmathur.library.ui.IconStop+import com.vayunmathur.library.ui.IconVolumeOff+import com.vayunmathur.library.ui.IconVolumeUp+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Slider+import com.vayunmathur.library.ui.Text++/**+ * Transport and volume for whatever is on the receiver.+ *+ * The scrub bar is driven locally while the thumb is held and only committed on release: the+ * receiver's position is polled once a second, so following it live would fight the user's+ * finger. Volume is the receiver's own volume, not the phone's.+ */+@Composable+fun CastNowPlayingCard(+    state: CastUiState,+    actions: CastActions,+    modifier: Modifier = Modifier,+) {+    Card(modifier = modifier.fillMaxWidth()) {+        Column(+            Modifier.padding(16.dp),+            verticalArrangement = Arrangement.spacedBy(8.dp),+        ) {+            Text(+                text = state.title ?: stringResource(R.string.cast_nothing_playing),+                style = MaterialTheme.typography.titleMedium,+                maxLines = 1,+                overflow = TextOverflow.Ellipsis,+            )+            Text(+                text = stringResource(playerStateLabel(state.playerState)),+                style = MaterialTheme.typography.bodySmall,+                color = MaterialTheme.colorScheme.onSurfaceVariant,+            )+            ScrubBar(state, actions)+            TransportRow(state, actions)+            VolumeRow(state, actions)+        }+    }+}++@Composable+private fun ScrubBar(state: CastUiState, actions: CastActions) {+    val duration = state.durationSec+    // A live stream has no end, so there is nothing to scrub along and the position alone is+    // the only honest thing to show.+    if (duration == null || duration <= 0.0) {+        Text(formatTime(state.positionSec), style = MaterialTheme.typography.bodySmall)+        return+    }+    var scrubbing by remember { mutableStateOf<Float?>(null) }+    val shown = scrubbing ?: state.positionSec.toFloat()+    Slider(+        value = shown.coerceIn(0f, duration.toFloat()),+        onValueChange = { scrubbing = it },+        onValueChangeFinished = {+            scrubbing?.let { actions.seek(it.toDouble()) }+            scrubbing = null+        },+        valueRange = 0f..duration.toFloat(),+    )+    Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {+        Text(formatTime(shown.toDouble()), style = MaterialTheme.typography.bodySmall)+        Text(formatTime(duration), style = MaterialTheme.typography.bodySmall)+    }+}++@Composable+private fun TransportRow(state: CastUiState, actions: CastActions) {+    Row(+        Modifier.fillMaxWidth(),+        horizontalArrangement = Arrangement.Center,+        verticalAlignment = Alignment.CenterVertically,+    ) {+        if (state.playerState == CastPlayerState.Playing) {+            IconButton(onClick = actions::pause) { IconPause() }+        } else {+            IconButton(onClick = actions::play, enabled = state.hasMedia) { IconPlay() }+        }+        IconButton(onClick = actions::stopPlayback, enabled = state.hasMedia) { IconStop() }+    }+}++@Composable+private fun VolumeRow(state: CastUiState, actions: CastActions) {+    Row(+        Modifier.fillMaxWidth(),+        horizontalArrangement = Arrangement.spacedBy(8.dp),+        verticalAlignment = Alignment.CenterVertically,+    ) {+        IconButton(onClick = { actions.setMuted(!state.muted) }) {+            if (state.muted) IconVolumeOff() else IconVolumeUp()+        }+        Slider(+            value = state.volumeLevel.toFloat(),+            onValueChange = { actions.setVolume(it.toDouble()) },+            enabled = !state.muted,+            modifier = Modifier.weight(1f),+        )+    }+}++private fun playerStateLabel(playerState: CastPlayerState): Int = when (playerState) {+    CastPlayerState.Buffering -> R.string.cast_state_buffering+    CastPlayerState.Playing -> R.string.cast_state_playing+    CastPla

Diff truncated.