cast: strip the media path down to screen mirroring
- Commit
22fbc4af12dbaa6cbeb56a564716eeb8ed443f45- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-21 06:25 UTC (3 months ago)
- Parents
089c4b2
Diff
cast/src/main/AndroidManifest.xml
diff --git a/cast/src/main/AndroidManifest.xml b/cast/src/main/AndroidManifest.xmlindex c9824c14d8..253026f91a 100644--- a/cast/src/main/AndroidManifest.xml+++ b/cast/src/main/AndroidManifest.xml@@ -2,8 +2,7 @@ <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. -->+ _googlecast._tcp and a TLS socket to port 8009 for the control plane. --> <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" />@@ -16,16 +15,14 @@ <!-- 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). -->+ calls onTimeout(), which for a long session would stop the service part-way through+ (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. -->+ <!-- Deliberately NO storage or media permissions: nothing is read from the device's+ storage. --> <uses-feature android:name="android.hardware.wifi" android:required="false" /> @@ -47,20 +44,10 @@ <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. -->+ <!-- Holds the cast channel up while the app is not in front, so backgrounding the app+ does not stop mirroring. --> <service android:name=".service.CastService" android:exported="false"
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.ktindex 12efc972af..832e622453 100644--- a/cast/src/main/java/com/vayunmathur/cast/MainActivity.kt+++ b/cast/src/main/java/com/vayunmathur/cast/MainActivity.kt@@ -1,23 +1,19 @@ 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.+ * The app's only Activity. *- * `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.+ * Has to survive the move to a Quick Settings tile whatever else changes: it is the host the+ * screen-capture consent dialog needs, and the tile's long-press target. */ class MainActivity : ComponentActivity() { @@ -26,27 +22,10 @@ class MainActivity : ComponentActivity() { 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/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.ktindex 45fd8dc64c..420b62a155 100644--- a/cast/src/main/java/com/vayunmathur/cast/domain/CastPayloads.kt+++ b/cast/src/main/java/com/vayunmathur/cast/domain/CastPayloads.kt@@ -4,21 +4,19 @@ import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json /**- * The CastV2 namespaces this app speaks.+ * The CastV2 namespaces this app deals in. * * 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.+ * routing table. There is no registration or discovery step: every receiver implements all of+ * them. Only the first three are spoken today; [WEBRTC] is where mirroring gets negotiated. */ 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].+ * OFFER/ANSWER - where mirroring is negotiated. * * openscreen `cast/streaming/message_fields.h`, `kCastWebrtcNamespace`. The name is * historical; nothing about it is WebRTC.@@ -27,41 +25,25 @@ object CastNamespaces { } /**- * The Default Media Receiver.+ * The Cast Streaming receiver app ids, which are what mirroring launches. *- * 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.+ * Four exist - openscreen names a desktop/Chrome pair and an Android pair - but only the Android+ * pair is used here, because that is what Phase 0 proved works from an unregistered sender on+ * real hardware. **Which one is picked is a correctness boundary, not a preference:** a mismatched+ * pair is refused at LAUNCH, with `NOT_FOUND` for audio-only against a TV and `SYSTEM_ERROR` for+ * A/V against a speaker. * * 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()`. For a device with a screen. */+ const val AUDIO_VIDEO = "674A0243" - /** `GetAndroidMirroringAudioVideoAppId()`. */- const val ANDROID_AUDIO_VIDEO = "674A0243"+ /** `GetAndroidMirroringAudioOnlyAppId()`. For a speaker or a speaker group. */+ const val AUDIO_ONLY = "8E6C866D" - /** `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+ fun forKind(kind: CastDeviceKind): String =+ if (kind == CastDeviceKind.Tv) AUDIO_VIDEO else AUDIO_ONLY } /** Every sender is `sender-0`; the platform receiver is always `receiver-0`. */@@ -86,11 +68,11 @@ data class CastFrame( /** * 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.+ * `ignoreUnknownKeys` is not optional: receiver status carries a large, versioned object graph+ * and a firmware update adding a field must not break a session. `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@@ -103,7 +85,7 @@ val CastJson: Json = Json { data class CastEnvelope( val type: String = "", val requestId: Int? = null,- /** Present on LAUNCH_ERROR / LOAD_FAILED, e.g. `CANCELLED` or `NOT_AVAILABLE`. */+ /** Present on LAUNCH_ERROR, e.g. `NOT_FOUND` or `SYSTEM_ERROR`. */ val reason: String? = null, ) @@ -120,8 +102,11 @@ data class ReceiverApplication( 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.+ * The id to address the *running app* at, which is not [RECEIVER_ID].+ *+ * For the mirroring receivers this is a UUID and happens to equal [sessionId], where the+ * media receiver used `web-N` - so nothing may assume either shape. A frame sent anywhere+ * else is silently dropped. */ val transportId: String = "", val isIdleScreen: Boolean = false,@@ -140,52 +125,10 @@ data class ReceiverStatusMessage( 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,@@ -206,29 +149,3 @@ data class SetVolumeRequest( 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.ktindex 71fe673e93..f74b8e69d7 100644--- a/cast/src/main/java/com/vayunmathur/cast/domain/CastSession.kt+++ b/cast/src/main/java/com/vayunmathur/cast/domain/CastSession.kt@@ -1,6 +1,6 @@ package com.vayunmathur.cast.domain -/** How far along the CONNECT -> LAUNCH -> join -> LOAD sequence the session is. */+/** How far along the CONNECT -> LAUNCH -> join sequence the session is. */ enum class CastPhase { /** No channel, or the receiver closed it. */ Idle,@@ -15,81 +15,16 @@ enum class CastPhase { 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.- */+/** Everything the session knows, as one value. */ 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. *@@ -99,41 +34,26 @@ private const val SPIKE_VIDEO_STREAM = """ * * 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+ * 3. CONNECT again, to that `transportId` - a frame sent to the app 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.+ * 4. Only then is the `webrtc` namespace addressable, which is where mirroring is negotiated. * * `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.+ * [appId] is what gets launched and what a RECEIVER_STATUS is matched against. It comes from+ * [MirroringAppIds.forKind] and is not a free choice: a receiver refuses the wrong one outright. */-class CastSession(private val appId: String = DEFAULT_MEDIA_RECEIVER_APP_ID) {+class CastSession(private val appId: String) { 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. */+ /** CONNECT to the platform receiver and launch the mirroring receiver on it. */ fun open(): List<CastFrame> { state = CastSessionState(phase = CastPhase.Launching) return listOf(@@ -144,7 +64,7 @@ class CastSession(private val appId: String = DEFAULT_MEDIA_RECEIVER_APP_ID) { /** * 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.+ * so this has to be sent on a timer whether or not anything is being mirrored. */ fun heartbeat(): CastFrame = frame(CastNamespaces.HEARTBEAT, RECEIVER_ID, CastSimpleMessage("PING"))@@ -152,8 +72,9 @@ class CastSession(private val appId: String = DEFAULT_MEDIA_RECEIVER_APP_ID) { /** * 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.+ * Anything unrecognised is ignored rather than treated as an error - receivers send status+ * types and namespaces this app has no interest in, and a speaker emits a steady stream of+ * `com.google.cast.multizone` traffic that is none of our business. */ fun onMessage(namespace: String, payload: String): List<CastFrame> { val envelope = runCatching { CastJson.decodeFromString<CastEnvelope>(payload) }.getOrNull()@@ -170,99 +91,13 @@ class CastSession(private val appId: String = DEFAULT_MEDIA_RECEIVER_APP_ID) { 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.+ * Volume is the *receiver's* volume, so it goes to [RECEIVER_ID] on the receiver namespace+ * rather than to the running app. */ fun setVolume(level: Double): List<CastFrame> { val clamped = level.coerceIn(0.0, 1.0)@@ -291,7 +126,7 @@ class CastSession(private val appId: String = DEFAULT_MEDIA_RECEIVER_APP_ID) { * 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.+ * mirroring receiver on screen with the last frame frozen. */ fun close(): List<CastFrame> { val frames = buildList {@@ -314,7 +149,6 @@ class CastSession(private val appId: String = DEFAULT_MEDIA_RECEIVER_APP_ID) { } private fun onClosed() {- pendingLoad = null state = CastSessionState(phase = CastPhase.Idle) } @@ -340,14 +174,12 @@ class CastSession(private val appId: String = DEFAULT_MEDIA_RECEIVER_APP_ID) { } 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.+ // Not a failure, but there is nothing left to mirror to. if (state.phase == CastPhase.Ready) { state = state.copy( phase = CastPhase.Idle, sessionId = null, transportId = null,- mediaSessionId = null,- playerState = CastPlayerState.Idle, ) } return emptyList()@@ -363,53 +195,8 @@ class CastSession(private val appId: String = DEFAULT_MEDIA_RECEIVER_APP_ID) { 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),- ),+ frame(CastNamespaces.CONNECTION, app.transportId, CastSimpleMessage("CONNECT")), ) }
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.ktdeleted file mode 100644index bd03dcc5e4..0000000000--- a/cast/src/main/java/com/vayunmathur/cast/network/ByteRange.kt+++ /dev/null@@ -1,71 +0,0 @@-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/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.ktdeleted file mode 100644index bf6851057b..0000000000--- a/cast/src/main/java/com/vayunmathur/cast/network/MediaFileServer.kt+++ /dev/null@@ -1,318 +0,0 @@-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.ktindex 05ef2aefb9..d8d4e9e014 100644--- a/cast/src/main/java/com/vayunmathur/cast/platform/CastController.kt+++ b/cast/src/main/java/com/vayunmathur/cast/platform/CastController.kt@@ -1,22 +1,15 @@ 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@@ -29,7 +22,6 @@ 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@@ -42,21 +34,6 @@ private const val TAG = "CastController" */ 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. *@@ -76,13 +53,8 @@ object CastController { 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 @@ -101,39 +73,27 @@ object CastController { .also { discoveryManager = it } /**- * Open a channel to [device] and launch the media receiver on it.+ * Open a channel to [device] and launch the mirroring 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.+ * first, since a sender holds one session at a time. The app id follows from+ * [CastDevice.kind] and is not negotiable - a receiver refuses the wrong one at LAUNCH. *- * 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.+ * A [CastPhase.Failed] session is *not* treated as live, so tapping the same device again+ * retries rather than doing nothing. A refusal is a routine outcome here - the receiver says+ * no whenever the capability bitmask and the app id disagree - so a dead end would be a bug. */- fun spikeMirror(context: Context, device: CastDevice, appId: String) {- openSession(context, device, appId)- }-- private fun openSession(context: Context, device: CastDevice, appId: String) {+ fun connect(context: Context, device: CastDevice) {+ val phase = _sessionState.value.phase+ val live = phase != CastPhase.Idle && phase != CastPhase.Failed+ if (_device.value?.id == device.id && live) return val appContext = context.applicationContext scope.launch { teardown() _device.value = device _isConnecting.value = true val newChannel = CastChannel(device.host, device.port)- val newSession = CastSession(appId)+ val newSession = CastSession(MirroringAppIds.forKind(device.kind)) try { newChannel.connect() } catch (e: Exception) {@@ -147,7 +107,6 @@ object CastController { } channel = newChannel session = newSession- fileServer = MediaFileServer(appContext.contentResolver) startPump(appContext, newChannel, newSession) send(newChannel, newSession) { it.open() } heartbeatJob = scope.launch {@@ -156,58 +115,13 @@ object CastController { 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. */+ /** Stop the receiver app, close the channel and drop the session. */ fun disconnect(context: Context) { val appContext = context.applicationContext scope.launch {@@ -221,53 +135,10 @@ object CastController { } } - /** 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 {@@ -302,14 +173,6 @@ object CastController { 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)@@ -345,24 +208,18 @@ object CastController { /** * 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.+ * The socket is closed *before* [mutex] is taken, because closing is what unblocks a reader+ * or writer parked in it - 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
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.ktindex 46d905a64f..3b486d3ff4 100644--- a/cast/src/main/java/com/vayunmathur/cast/platform/CastUiContract.kt+++ b/cast/src/main/java/com/vayunmathur/cast/platform/CastUiContract.kt@@ -1,37 +1,17 @@ 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.+ * outstanding, only whether the receiver is joined 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.+ * Everything the Cast screen draws. * * 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@@ -48,42 +28,28 @@ data class CastUiState( 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,+ /**+ * True when the target has no screen, so only audio can be sent to it.+ *+ * Derived from the mDNS capability bitmask, which is known before anything is negotiated -+ * that is what lets the UI say "audio only" while the receiver is still being joined.+ */+ val audioOnly: Boolean = false, 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-}+ /** Why the receiver refused, already turned into something worth showing a user. */+ val failure: String? = 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.ktindex 005e1c901f..4777e623fa 100644--- a/cast/src/main/java/com/vayunmathur/cast/platform/CastViewModel.kt+++ b/cast/src/main/java/com/vayunmathur/cast/platform/CastViewModel.kt@@ -3,8 +3,6 @@ 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@@ -14,9 +12,9 @@ import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.viewModelScope import com.vayunmathur.cast.R import com.vayunmathur.cast.domain.CastDevice+import com.vayunmathur.cast.domain.CastDeviceKind 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@@ -28,9 +26,6 @@ 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". *@@ -45,11 +40,7 @@ private const val SCAN_INDICATOR_MS = 6_000L * * 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.+ * running. */ class CastViewModel(application: Application) : AndroidViewModel(application), CastActions { @@ -57,7 +48,6 @@ class CastViewModel(application: Application) : AndroidViewModel(application), C private val discovery get() = CastController.discovery(appContext) private val _isScanning = MutableStateFlow(false)- private val _pendingSource = MutableStateFlow<CastSource?>(null) private var scanJob: Job? = null @@ -75,8 +65,7 @@ class CastViewModel(application: Application) : AndroidViewModel(application), C CastController.device, CastController.isConnecting, CastController.sessionState,- _pendingSource,- ) { (devices, scanning, blocked), device, connecting, session, pending ->+ ) { (devices, scanning, blocked), device, connecting, session -> CastUiState( devices = devices, isScanning = scanning,@@ -88,29 +77,16 @@ class CastViewModel(application: Application) : AndroidViewModel(application), C 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,+ // A speaker or a group has no screen, so only audio can go to it. Known from the+ // mDNS capability bitmask before anything is negotiated, which is what lets the UI+ // say "audio only" while the receiver is still being joined.+ audioOnly = device != null && device.kind != CastDeviceKind.Tv, volumeLevel = session.volumeLevel, muted = session.muted,+ failure = failureMessage(session.failure), ) }.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.@@ -145,39 +121,25 @@ class CastViewModel(application: Application) : AndroidViewModel(application), C 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) + /**+ * Turn a `LAUNCH_ERROR` reason into something worth reading.+ *+ * The reasons are wire constants and must not reach the screen. `NOT_FOUND` is what a TV+ * answers when asked for the audio-only receiver and `SYSTEM_ERROR` is what a speaker answers+ * when asked for the audio-video one, so in practice both mean "this device will not run what+ * we asked it to" - which is the same sentence to a user either way.+ */+ private fun failureMessage(reason: String?): String? = when (reason) {+ null -> null+ "NOT_FOUND", "INVALID_APP_ID" -> appContext.getString(R.string.cast_launch_unsupported)+ "CANCELLED" -> appContext.getString(R.string.cast_launch_cancelled)+ else -> appContext.getString(R.string.cast_launch_failed)+ }+ /** * There is no intent for the local-network toggle itself, so this opens the app's own * settings page, where the permission lives.@@ -189,62 +151,6 @@ class CastViewModel(application: Application) : AndroidViewModel(application), C ).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 {
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.ktindex ee32308b26..f581100020 100644--- a/cast/src/main/java/com/vayunmathur/cast/service/CastService.kt+++ b/cast/src/main/java/com/vayunmathur/cast/service/CastService.kt@@ -14,7 +14,7 @@ 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.domain.CastPhase import com.vayunmathur.cast.platform.CastController import com.vayunmathur.library.util.ensureNotificationChannel import kotlinx.coroutines.CoroutineScope@@ -37,14 +37,14 @@ 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.+ * A lifecycle host with no session state of its own: [CastController] owns the socket 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.+ * calls `onTimeout()`. */ class CastService : Service() { @@ -82,11 +82,16 @@ class CastService : Service() { .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)+ val text = when (state.phase) {+ CastPhase.Launching ->+ getString(R.string.cast_notification_text_connecting)+ CastPhase.Ready -> getString(R.string.cast_notification_text_ready)+ // Not the raw LAUNCH_ERROR reason: those are wire constants, and the+ // screen is where the explanation belongs.+ CastPhase.Failed -> getString(R.string.cast_notification_text_failed)+ // The receiver app exited on its own - the channel is still up, so+ // this is a real resting state rather than a transient one.+ CastPhase.Idle -> getString(R.string.cast_notification_text_idle) } getSystemService<NotificationManager>() ?.notify(NOTIF_ID, buildNotification(device.friendlyName, text))@@ -115,7 +120,7 @@ class CastService : Service() { val device = CastController.device.value val notification = buildNotification( device?.friendlyName ?: getString(R.string.app_name),- getString(R.string.cast_notification_text_idle),+ getString(R.string.cast_notification_text_connecting), ) try { if (Build.VERSION.SDK_INT >= 34) {
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.ktindex fcee71f5ae..3fdb4d89e6 100644--- a/cast/src/main/java/com/vayunmathur/cast/ui/CastContent.kt+++ b/cast/src/main/java/com/vayunmathur/cast/ui/CastContent.kt@@ -29,19 +29,16 @@ import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.TextButton /**- * The whole app: pick a device, pick something to cast, control it.+ * The whole app: pick a device to mirror to. * * 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.+ * a `@Preview`. */ @Composable fun CastContent( state: CastUiState, actions: CastActions, modifier: Modifier = Modifier,- onPickFile: () -> Unit = {}, ) { AppScaffold( title = stringResource(R.string.cast_devices_title),@@ -61,10 +58,6 @@ fun CastContent( 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) }@@ -95,18 +88,34 @@ private fun SectionHeader(state: CastUiState, actions: CastActions) { ) CastConnection.Connected -> Column { Text(- stringResource(R.string.cast_connected_to, connected?.friendlyName ?: ""),+ stringResource(+ if (state.audioOnly) {+ R.string.cast_connected_audio_only+ } else {+ 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.Failed -> Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {+ Text(+ state.failure ?: stringResource(R.string.cast_launch_failed),+ style = MaterialTheme.typography.titleSmall,+ color = MaterialTheme.colorScheme.error,+ )+ // Tapping the device row again also retries, but a refusal leaves the row looking+ // unchanged, so there has to be something obvious to press.+ if (connected != null) {+ TextButton(onClick = { actions.connect(connected) }) {+ Text(stringResource(R.string.cast_retry))+ }+ }+ } CastConnection.Disconnected -> Text( stringResource(R.string.cast_devices_heading), style = MaterialTheme.typography.titleSmall,
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.ktdeleted file mode 100644index f71b05413c..0000000000--- a/cast/src/main/java/com/vayunmathur/cast/ui/CastNowPlayingCard.kt+++ /dev/null@@ -1,147 +0,0 @@-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- CastPlayerState.Paused -> R.string.cast_state_paused- CastPlayerState.Idle -> R.string.cast_state_idle-}--private fun formatTime(seconds: Double): String {- val total = seconds.coerceAtLeast(0.0).toLong()- val hours = total / 3600- val minutes = (total % 3600) / 60- val secs = total % 60- return if (hours > 0) {- "%d:%02d:%02d".format(hours, minutes, secs)- } else {- "%d:%02d".format(minutes, secs)- }-}
cast/src/main/java/com/vayunmathur/cast/ui/CastScreen.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/ui/CastScreen.kt b/cast/src/main/java/com/vayunmathur/cast/ui/CastScreen.ktindex 5e0e19b3a1..b8c2797fb3 100644--- a/cast/src/main/java/com/vayunmathur/cast/ui/CastScreen.kt+++ b/cast/src/main/java/com/vayunmathur/cast/ui/CastScreen.kt@@ -15,13 +15,8 @@ import com.vayunmathur.cast.platform.CastViewModel @Composable fun CastScreen(viewModel: CastViewModel) { val state by viewModel.uiState.collectAsState()- // OpenDocument, not GetContent: it returns a URI the app can read for as long as it holds- // it, which is what the local HTTP server needs, and it needs no storage permission.- val picker = rememberLauncherForActivityResult(- ActivityResultContracts.OpenDocument(),- ) { uri -> if (uri != null) viewModel.pickLocalFile(uri.toString()) } // Asked for plainly and never insisted on: without it the session still works, it just- // loses the notification that is the only way to stop casting from outside the app.+ // loses the notification that is the only way to stop mirroring from outside the app. val notifications = rememberLauncherForActivityResult( ActivityResultContracts.RequestPermission(), ) { }@@ -36,9 +31,5 @@ fun CastScreen(viewModel: CastViewModel) { viewModel.startScan() onDispose { viewModel.stopScan() } }- CastContent(- state = state,- actions = viewModel,- onPickFile = { picker.launch(arrayOf("video/*", "audio/*", "image/*")) },- )+ CastContent(state = state, actions = viewModel) }
cast/src/main/java/com/vayunmathur/cast/ui/CastSourceCard.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/ui/CastSourceCard.kt b/cast/src/main/java/com/vayunmathur/cast/ui/CastSourceCard.ktdeleted file mode 100644index 1f1bd83c55..0000000000--- a/cast/src/main/java/com/vayunmathur/cast/ui/CastSourceCard.kt+++ /dev/null@@ -1,146 +0,0 @@-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.foundation.text.KeyboardOptions-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.input.KeyboardType-import androidx.compose.ui.text.style.TextOverflow-import androidx.compose.ui.unit.dp-import com.vayunmathur.cast.R-import com.vayunmathur.cast.domain.MirroringAppIds-import com.vayunmathur.cast.platform.CastActions-import com.vayunmathur.cast.platform.CastUiState-import com.vayunmathur.library.ui.Button-import com.vayunmathur.library.ui.Card-import com.vayunmathur.library.ui.HorizontalDivider-import com.vayunmathur.library.ui.IconButton-import com.vayunmathur.library.ui.IconClose-import com.vayunmathur.library.ui.IconFolder-import com.vayunmathur.library.ui.MaterialTheme-import com.vayunmathur.library.ui.OutlinedButton-import com.vayunmathur.library.ui.OutlinedTextField-import com.vayunmathur.library.ui.Text--/**- * Choosing what to cast: a local file through the system picker, or a link.- *- * A chosen source is shown even before a device is picked, because [CastUiState.pendingSource]- * is cast automatically once a receiver is joined - so the user can start from either end.- */-@Composable-fun CastSourceCard(- state: CastUiState,- actions: CastActions,- onPickFile: () -> Unit,- modifier: Modifier = Modifier,-) {- Card(modifier = modifier.fillMaxWidth()) {- Column(- Modifier.padding(16.dp),- verticalArrangement = Arrangement.spacedBy(8.dp),- ) {- val pending = state.pendingSource- if (pending != null) {- Row(- Modifier.fillMaxWidth(),- horizontalArrangement = Arrangement.spacedBy(8.dp),- verticalAlignment = Alignment.CenterVertically,- ) {- Text(- text = pending.label,- style = MaterialTheme.typography.bodyLarge,- maxLines = 1,- overflow = TextOverflow.Ellipsis,- modifier = Modifier.weight(1f),- )- IconButton(onClick = actions::clearPendingSource) { IconClose() }- }- }- OutlinedButton(onClick = onPickFile, modifier = Modifier.fillMaxWidth()) {- IconFolder()- Text(- stringResource(R.string.cast_pick_file),- modifier = Modifier.padding(start = 8.dp),- )- }- UrlField(actions)- SpikeRow(state, actions)- }- }-}--/**- * THROWAWAY (Phase 0): one button per Cast Streaming app id.- *- * All four are here because openscreen names two pairs - a desktop/Chrome pair and an Android- * pair - and which of them tolerates an unregistered sender is exactly what is unknown. The- * result is in logcat under `CastController`, not on screen; this is a probe, not a feature.- *- * Lands in this file deliberately: it is the file Phase 1 deletes, so the throwaway UI goes- * away with it whichever way the spike lands.- */-@Composable-private fun SpikeRow(state: CastUiState, actions: CastActions) {- HorizontalDivider()- Text(- stringResource(R.string.cast_spike_heading),- style = MaterialTheme.typography.titleSmall,- )- val device = state.connectedDevice- if (device == null) {- Text(- stringResource(R.string.cast_spike_needs_device),- style = MaterialTheme.typography.bodySmall,- color = MaterialTheme.colorScheme.onSurfaceVariant,- )- return- }- for (appId in MirroringAppIds.all) {- OutlinedButton(- onClick = { actions.spikeMirror(appId) },- modifier = Modifier.fillMaxWidth(),- ) {- Text(stringResource(R.string.cast_spike_launch, appId))- }- }-}--@Composable-private fun UrlField(actions: CastActions) {- var url by remember { mutableStateOf("") }- Row(- Modifier.fillMaxWidth(),- horizontalArrangement = Arrangement.spacedBy(8.dp),- verticalAlignment = Alignment.CenterVertically,- ) {- OutlinedTextField(- value = url,- onValueChange = { url = it },- label = { Text(stringResource(R.string.cast_cast_url)) },- placeholder = { Text(stringResource(R.string.cast_url_hint)) },- singleLine = true,- keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri),- modifier = Modifier.weight(1f),- )- Button(- onClick = {- actions.castUrl(url)- url = ""- },- enabled = url.isNotBlank(),- ) {- Text(stringResource(R.string.cast_start))- }- }-}
cast/src/main/res/values/strings.xml
diff --git a/cast/src/main/res/values/strings.xml b/cast/src/main/res/values/strings.xmlindex adb660bf85..86f94ed8ff 100644--- a/cast/src/main/res/values/strings.xml+++ b/cast/src/main/res/values/strings.xml@@ -13,35 +13,24 @@ <string name="cast_disconnect">Disconnect</string> <string name="cast_connecting_to">Connecting to %1$s.</string> <string name="cast_connected_to">Connected to %1$s</string>+ <string name="cast_connected_audio_only">Connected to %1$s \u2014 audio only</string> <string name="cast_connect_failed">Could not connect to %1$s</string> - <!-- Source picker -->- <string name="cast_pick_file">Choose a file</string>- <string name="cast_cast_url">Cast a link</string>- <string name="cast_url_hint">https://example.com/video.mp4</string>- <string name="cast_url_invalid">Enter an http or https link</string>- <string name="cast_start">Cast</string>-- <!-- Phase 0 spike: throwaway, deleted in Phase 1 -->- <string name="cast_spike_heading">Mirroring spike</string>- <string name="cast_spike_needs_device">Tap a device above first. Results appear in logcat under CastController.</string>- <string name="cast_spike_launch">Launch %1$s</string>-- <!-- Now playing -->- <string name="cast_nothing_playing">Nothing playing</string>- <string name="cast_load_failed">The device could not play that</string>- <string name="cast_server_failed">Could not serve the file to the device</string>-- <!-- Player states -->- <string name="cast_state_buffering">Buffering</string>- <string name="cast_state_playing">Playing</string>- <string name="cast_state_paused">Paused</string>- <string name="cast_state_idle">Idle</string>+ <!-- Launch failures. The receiver answers with a wire constant (NOT_FOUND when a device does+ not host the receiver we asked for, SYSTEM_ERROR when it cannot run it); these are what+ gets shown instead. -->+ <string name="cast_launch_unsupported">This device cannot be mirrored to</string>+ <string name="cast_launch_cancelled">The device declined the request</string>+ <string name="cast_launch_failed">Could not start mirroring on this device</string>+ <string name="cast_retry">Try again</string> <!-- Foreground service --> <string name="cast_notification_channel_name">Casting</string> <string name="cast_notification_channel_desc">Shown while a cast session is open</string> <string name="cast_notification_title">Casting to %1$s</string>- <string name="cast_notification_text_idle">Session open</string>+ <string name="cast_notification_text_connecting">Connecting</string>+ <string name="cast_notification_text_ready">Ready to mirror</string>+ <string name="cast_notification_text_idle">Not mirroring</string>+ <string name="cast_notification_text_failed">Could not start mirroring</string> <string name="cast_notification_action_stop">Stop</string> </resources>
cast/src/screenshotTest/kotlin/com/vayunmathur/cast/ui/MetadataPreviews.kt
diff --git a/cast/src/screenshotTest/kotlin/com/vayunmathur/cast/ui/MetadataPreviews.kt b/cast/src/screenshotTest/kotlin/com/vayunmathur/cast/ui/MetadataPreviews.ktindex fb3c64a064..28dcb163c1 100644--- a/cast/src/screenshotTest/kotlin/com/vayunmathur/cast/ui/MetadataPreviews.kt+++ b/cast/src/screenshotTest/kotlin/com/vayunmathur/cast/ui/MetadataPreviews.kt@@ -4,10 +4,8 @@ import androidx.compose.runtime.Composable import androidx.compose.ui.tooling.preview.Preview import com.android.tools.screenshot.PreviewTest import com.vayunmathur.cast.domain.CastDevice-import com.vayunmathur.cast.domain.CastPlayerState import com.vayunmathur.cast.platform.CastActions import com.vayunmathur.cast.platform.CastConnection-import com.vayunmathur.cast.platform.CastSource import com.vayunmathur.cast.platform.CastUiState import com.vayunmathur.library.ui.DynamicTheme @@ -23,6 +21,14 @@ private val LivingRoomTv = CastDevice( capabilities = 1, ) +private val WholeHome = CastDevice(+ id = "c07e15",+ friendlyName = "Whole home",+ host = "192.168.1.60",+ model = "Speaker group",+ capabilities = 1 shl 5,+)+ private val Receivers = listOf( LivingRoomTv, CastDevice(@@ -32,20 +38,14 @@ private val Receivers = listOf( model = "Google Nest Mini", capabilities = 4, ),- CastDevice(- id = "c07e15",- friendlyName = "Whole home",- host = "192.168.1.60",- model = "Speaker group",- capabilities = 1 shl 5,- ),+ WholeHome, ) /** * Store-listing screenshots. *- * Driven through [CastContent], which is stateless by design, so no socket, no mDNS browse and- * no local HTTP server has to exist for these to render - none of which Layoutlib could provide.+ * Driven through [CastContent], which is stateless by design, so no socket and no mDNS browse has+ * to exist for these to render - neither of which Layoutlib could provide. * * Each preview needs @PreviewTest as well as @Preview: @Preview alone renders in Studio but is * not collected as a screenshot test. They must also be class members rather than top-level@@ -66,18 +66,15 @@ class MetadataPreviews { } @PreviewTest- @Preview(name = "2-picked", device = PHONE, showSystemUi = true)+ @Preview(name = "2-connecting", device = PHONE, showSystemUi = true) @Composable- fun Preview2Picked() {+ fun Preview2Connecting() { DynamicTheme(darkTheme = true) { CastContent( state = CastUiState( devices = Receivers,- pendingSource = CastSource.LocalFile(- uri = "content://media/external/video/media/2041",- label = "holiday-2024.mp4",- mimeType = "video/mp4",- ),+ connectedDevice = LivingRoomTv,+ connection = CastConnection.Connecting, ), actions = CastActions.Noop, )@@ -85,19 +82,15 @@ class MetadataPreviews { } @PreviewTest- @Preview(name = "3-playing", device = PHONE, showSystemUi = true)+ @Preview(name = "3-connected-tv", device = PHONE, showSystemUi = true) @Composable- fun Preview3Playing() {+ fun Preview3ConnectedTv() { DynamicTheme(darkTheme = true) { CastContent( state = CastUiState( devices = Receivers, connectedDevice = LivingRoomTv, connection = CastConnection.Connected,- playerState = CastPlayerState.Playing,- title = "holiday-2024.mp4",- positionSec = 184.0,- durationSec = 742.0, volumeLevel = 0.55, ), actions = CastActions.Noop,@@ -106,19 +99,17 @@ class MetadataPreviews { } @PreviewTest- @Preview(name = "4-paused", device = PHONE, showSystemUi = true)+ @Preview(name = "4-connected-group", device = PHONE, showSystemUi = true) @Composable- fun Preview4Paused() {+ fun Preview4ConnectedGroup() { DynamicTheme(darkTheme = true) { CastContent( state = CastUiState( devices = Receivers,- connectedDevice = LivingRoomTv,+ connectedDevice = WholeHome, connection = CastConnection.Connected,- playerState = CastPlayerState.Paused,- title = "Sur les toits de Paris",- positionSec = 96.0,- durationSec = 305.0,+ // A group has no screen, so only audio can go to it.+ audioOnly = true, volumeLevel = 0.3, muted = true, ),
cast/src/test/java/com/vayunmathur/cast/domain/CastSessionTest.kt
diff --git a/cast/src/test/java/com/vayunmathur/cast/domain/CastSessionTest.kt b/cast/src/test/java/com/vayunmathur/cast/domain/CastSessionTest.ktindex 5d28391c65..1f045bfc7d 100644--- a/cast/src/test/java/com/vayunmathur/cast/domain/CastSessionTest.kt+++ b/cast/src/test/java/com/vayunmathur/cast/domain/CastSessionTest.kt@@ -6,12 +6,18 @@ import kotlin.test.assertFalse import kotlin.test.assertNull import kotlin.test.assertTrue -private const val TRANSPORT_ID = "web-5"-+private const val TRANSPORT_ID = "691b2c09-797c-4699-adf3-3f7f4d781448"++/**+ * A real RECEIVER_STATUS from a Google TV, captured during the Phase 0 spike.+ *+ * Note `transportId` equals `sessionId` and both are UUIDs - the media receiver used `web-N`, so+ * this shape is what the join logic actually has to cope with.+ */ private val RECEIVER_STATUS_RUNNING = """ {"type":"RECEIVER_STATUS","requestId":1,"status":{- "applications":[{"appId":"CC1AD845","displayName":"Default Media Receiver",- "sessionId":"S1","statusText":"Ready To Cast","transportId":"$TRANSPORT_ID"}],+ "applications":[{"appId":"674A0243","displayName":"Android Mirroring",+ "sessionId":"$TRANSPORT_ID","statusText":"Mirroring","transportId":"$TRANSPORT_ID"}], "volume":{"level":0.4,"muted":false}}} """.trimIndent() @@ -22,41 +28,38 @@ private val RECEIVER_STATUS_IDLE = """ "volume":{"level":0.4,"muted":false}}} """.trimIndent() -private val MEDIA_STATUS_PLAYING = """- {"type":"MEDIA_STATUS","requestId":0,"status":[{"mediaSessionId":7,- "playerState":"PLAYING","currentTime":12.5,- "media":{"contentId":"http://192.168.1.9:41234/x","contentType":"video/mp4",- "streamType":"BUFFERED","duration":300.0,- "metadata":{"metadataType":0,"title":"Clip"}}}]}-""".trimIndent()--/** The periodic status the receiver sends after the first one: no `media` object. */-private val MEDIA_STATUS_TICK = """- {"type":"MEDIA_STATUS","status":[{"mediaSessionId":7,"playerState":"PLAYING",- "currentTime":19.0}]}+/** A real ANSWER from a TV, kept as the shape Phase 2 has to parse. */+private val ANSWER_TV = """+ {"answer":{"display":{"dimensions":{"frameRate":"60","height":2160,"width":3840},+ "scaling":"sender"},"sendIndexes":[0,1],"ssrcs":[20002,50002],"udpPort":47505},+ "result":"ok","seqNum":2,"type":"ANSWER"} """.trimIndent() -private fun media(url: String, title: String? = null) = CastMediaInformation(- contentId = url,- contentType = "video/mp4",- metadata = title?.let { CastMediaMetadata(title = it) },-)- private fun CastFrame.type(): String = CastJson.decodeFromString<CastEnvelope>(payload).type class CastSessionTest { - /** Drives a session to the point where media commands are legal. */- private fun readySession(): CastSession = CastSession().apply {+ private fun session(appId: String = MirroringAppIds.AUDIO_VIDEO) = CastSession(appId)++ /** Drives a session to the point where the app is joined and addressable. */+ private fun readySession(): CastSession = session().apply { open() onMessage(CastNamespaces.RECEIVER, RECEIVER_STATUS_RUNNING)- onMessage(CastNamespaces.MEDIA, MEDIA_STATUS_PLAYING) } @Test- fun `open connects to the platform receiver and launches the default media receiver`() {- val frames = CastSession().open()+ fun `a device with a screen gets the audio-video app id and a speaker the audio-only one`() {+ // Not a preference: Phase 0 established that a receiver refuses the wrong one at LAUNCH,+ // with NOT_FOUND for audio-only against a TV and SYSTEM_ERROR for A/V against a speaker.+ assertEquals(MirroringAppIds.AUDIO_VIDEO, MirroringAppIds.forKind(CastDeviceKind.Tv))+ assertEquals(MirroringAppIds.AUDIO_ONLY, MirroringAppIds.forKind(CastDeviceKind.Speaker))+ assertEquals(MirroringAppIds.AUDIO_ONLY, MirroringAppIds.forKind(CastDeviceKind.Group))+ }++ @Test+ fun `open connects to the platform receiver and launches the app it was given`() {+ val frames = session(MirroringAppIds.AUDIO_ONLY).open() assertEquals(2, frames.size) assertEquals(CastNamespaces.CONNECTION, frames[0].namespace) assertEquals(RECEIVER_ID, frames[0].destinationId)@@ -64,14 +67,27 @@ class CastSessionTest { assertEquals(CastNamespaces.RECEIVER, frames[1].namespace) assertEquals(RECEIVER_ID, frames[1].destinationId) assertEquals("LAUNCH", frames[1].type())- assertTrue(frames[1].payload.contains(DEFAULT_MEDIA_RECEIVER_APP_ID))+ assertTrue(frames[1].payload.contains(MirroringAppIds.AUDIO_ONLY))+ }++ @Test+ fun `a receiver status for a different app id is not joined`() {+ // The audio-only receiver running on a device we asked for A/V is somebody else's+ // session, and joining it would address frames at an app that cannot use them.+ val session = session(MirroringAppIds.AUDIO_VIDEO)+ session.open()+ assertEquals(+ emptyList(),+ session.onMessage(CastNamespaces.RECEIVER, RECEIVER_STATUS_IDLE),+ )+ assertNull(session.state.transportId) } @Test fun `request ids start at one and never repeat`() { // Zero means "no response expected", so it must never be handed out, and a repeat // would make two responses indistinguishable.- val session = CastSession()+ val session = session() val ids = listOf( session.allocateRequestId(), session.allocateRequestId(),@@ -82,15 +98,15 @@ class CastSessionTest { @Test fun `receiver status names the transport and the session joins it`() {- val session = CastSession()+ val session = session() session.open() val frames = session.onMessage(CastNamespaces.RECEIVER, RECEIVER_STATUS_RUNNING) assertEquals(CastPhase.Ready, session.state.phase)- assertEquals("S1", session.state.sessionId)+ assertEquals(TRANSPORT_ID, session.state.sessionId) assertEquals(TRANSPORT_ID, session.state.transportId) assertEquals(0.4, session.state.volumeLevel)- // The second CONNECT, to the app rather than to receiver-0. Without it every media- // command is dropped with no error.+ // The second CONNECT, to the app rather than to receiver-0. Without it every frame on+ // the webrtc namespace is dropped with no error. assertEquals(1, frames.size) assertEquals(CastNamespaces.CONNECTION, frames[0].namespace) assertEquals(TRANSPORT_ID, frames[0].destinationId)@@ -99,97 +115,21 @@ class CastSessionTest { @Test fun `a repeated receiver status does not rejoin`() {- val session = CastSession()- session.open()- session.onMessage(CastNamespaces.RECEIVER, RECEIVER_STATUS_RUNNING)+ val session = readySession() assertEquals( emptyList(), session.onMessage(CastNamespaces.RECEIVER, RECEIVER_STATUS_RUNNING), ) } - @Test- fun `a load before the app is ready is held and replayed on join`() {- val session = CastSession()- session.open()- // The user picks a file while LAUNCH is still in flight. Rejecting this would make- // "pick a device" and "pick a file" order-dependent for no reason.- assertEquals(emptyList(), session.load(media("http://h/v.mp4", "Held")))- val frames = session.onMessage(CastNamespaces.RECEIVER, RECEIVER_STATUS_RUNNING)- assertEquals(listOf("CONNECT", "LOAD"), frames.map { it.type() })- val load = frames[1]- assertEquals(CastNamespaces.MEDIA, load.namespace)- assertEquals(TRANSPORT_ID, load.destinationId)- assertTrue(load.payload.contains("http://h/v.mp4"))- assertTrue(load.payload.contains("\"sessionId\":\"S1\""))- }-- @Test- fun `a load while ready goes straight out`() {- val session = CastSession()- session.open()- session.onMessage(CastNamespaces.RECEIVER, RECEIVER_STATUS_RUNNING)- val frames = session.load(media("http://h/v.mp4"))- assertEquals(listOf("LOAD"), frames.map { it.type() })- assertEquals(CastPlayerState.Buffering, session.state.playerState)- }- @Test fun `ping is answered with pong`() {- val frames = CastSession().onMessage(CastNamespaces.HEARTBEAT, """{"type":"PING"}""")+ val frames = session().onMessage(CastNamespaces.HEARTBEAT, """{"type":"PING"}""") assertEquals(1, frames.size) assertEquals("PONG", frames[0].type()) assertEquals(CastNamespaces.HEARTBEAT, frames[0].namespace) } - @Test- fun `media status supplies the media session id that commands need`() {- val session = readySession()- assertEquals(7, session.state.mediaSessionId)- assertEquals(CastPlayerState.Playing, session.state.playerState)- assertEquals(12.5, session.state.currentTimeSec)- assertEquals(300.0, session.state.durationSec)- assertEquals("Clip", session.state.title)- val pause = session.pause().single()- assertEquals(CastNamespaces.MEDIA, pause.namespace)- assertEquals(TRANSPORT_ID, pause.destinationId)- assertTrue(pause.payload.contains("\"mediaSessionId\":7"))- }-- @Test- fun `a periodic status without a media object keeps the title and duration`() {- val session = readySession()- session.onMessage(CastNamespaces.MEDIA, MEDIA_STATUS_TICK)- assertEquals(19.0, session.state.currentTimeSec)- assertEquals("Clip", session.state.title)- assertEquals(300.0, session.state.durationSec)- }-- @Test- fun `an empty media status clears what is playing`() {- val session = readySession()- session.onMessage(CastNamespaces.MEDIA, """{"type":"MEDIA_STATUS","status":[]}""")- assertNull(session.state.mediaSessionId)- assertNull(session.state.title)- assertEquals(CastPlayerState.Idle, session.state.playerState)- }-- @Test- fun `media commands are dropped when there is nothing to command`() {- val session = CastSession()- assertEquals(emptyList(), session.play())- assertEquals(emptyList(), session.seek(10.0))- }-- @Test- fun `seek moves the reported position without waiting for the receiver`() {- val session = readySession()- val seek = session.seek(42.0).single()- assertEquals("SEEK", seek.type())- assertTrue(seek.payload.contains("\"currentTime\":42.0"))- assertEquals(42.0, session.state.currentTimeSec)- }- @Test fun `volume goes to the platform receiver not the app`() { val session = readySession()@@ -223,14 +163,16 @@ class CastSessionTest { @Test fun `a launch error reports the receiver's reason`() {- val session = CastSession()+ // NOT_FOUND is what a TV answers when asked for the audio-only receiver, and+ // SYSTEM_ERROR is what a speaker answers when asked for the A/V one.+ val session = session() session.open() session.onMessage( CastNamespaces.RECEIVER,- """{"type":"LAUNCH_ERROR","requestId":1,"reason":"CANCELLED"}""",+ """{"type":"LAUNCH_ERROR","requestId":1,"reason":"NOT_FOUND"}""", ) assertEquals(CastPhase.Failed, session.state.phase)- assertEquals("CANCELLED", session.state.failure)+ assertEquals("NOT_FOUND", session.state.failure) } @Test@@ -255,7 +197,21 @@ class CastSessionTest { @Test fun `an unparseable payload is ignored`() { val session = readySession()- assertEquals(emptyList(), session.onMessage(CastNamespaces.MEDIA, "not json"))- assertEquals(CastPlayerState.Playing, session.state.playerState)+ assertEquals(emptyList(), session.onMessage(CastNamespaces.RECEIVER, "not json"))+ assertEquals(CastPhase.Ready, session.state.phase)+ }++ @Test+ fun `a namespace with no branch is ignored`() {+ // A speaker emits com.google.cast.multizone continuously, and the webrtc namespace has+ // no handler until there is a streaming session to hand it to. Neither may disturb the+ // control plane.+ val session = readySession()+ assertEquals(+ emptyList(),+ session.onMessage("urn:x-cast:com.google.cast.multizone", """{"type":"WHATEVER"}"""),+ )+ assertEquals(emptyList(), session.onMessage(CastNamespaces.WEBRTC, ANSWER_TV))+ assertEquals(CastPhase.Ready, session.state.phase) } }
cast/src/test/java/com/vayunmathur/cast/network/ByteRangeTest.kt
diff --git a/cast/src/test/java/com/vayunmathur/cast/network/ByteRangeTest.kt b/cast/src/test/java/com/vayunmathur/cast/network/ByteRangeTest.ktdeleted file mode 100644index a734fa2934..0000000000--- a/cast/src/test/java/com/vayunmathur/cast/network/ByteRangeTest.kt+++ /dev/null@@ -1,86 +0,0 @@-package com.vayunmathur.cast.network--import kotlin.test.Test-import kotlin.test.assertEquals--class ByteRangeTest {-- @Test- fun `no range header means the whole entity`() {- assertEquals(ByteRangeResult.Whole, parseByteRange(null, 100))- }-- @Test- fun `a closed range is taken literally and is inclusive`() {- val result = parseByteRange("bytes=0-99", 1000)- assertEquals(ByteRangeResult.Partial(ByteRange(0, 99)), result)- assertEquals(100, (result as ByteRangeResult.Partial).range.length)- }-- @Test- fun `an open ended range runs to the last byte`() {- // What a player sends when the user seeks: everything from here on.- assertEquals(- ByteRangeResult.Partial(ByteRange(500, 999)),- parseByteRange("bytes=500-", 1000),- )- }-- @Test- fun `a suffix range counts back from the end`() {- assertEquals(- ByteRangeResult.Partial(ByteRange(900, 999)),- parseByteRange("bytes=-100", 1000),- )- }-- @Test- fun `a suffix longer than the entity is the whole entity`() {- assertEquals(- ByteRangeResult.Partial(ByteRange(0, 99)),- parseByteRange("bytes=-500", 100),- )- }-- @Test- fun `a last byte position past the end is clamped`() {- assertEquals(- ByteRangeResult.Partial(ByteRange(90, 99)),- parseByteRange("bytes=90-100000", 100),- )- }-- @Test- fun `a first byte position past the end is unsatisfiable`() {- assertEquals(ByteRangeResult.Unsatisfiable, parseByteRange("bytes=100-200", 100))- assertEquals(ByteRangeResult.Unsatisfiable, parseByteRange("bytes=100-", 100))- }-- @Test- fun `a reversed range is unsatisfiable`() {- assertEquals(ByteRangeResult.Unsatisfiable, parseByteRange("bytes=50-10", 100))- }-- @Test- fun `a zero length suffix is unsatisfiable`() {- assertEquals(ByteRangeResult.Unsatisfiable, parseByteRange("bytes=-0", 100))- }-- @Test- fun `an unparseable or unsupported header is ignored rather than rejected`() {- // RFC 9110 6.1: a Range the server cannot parse must be ignored, which means- // answering 200 with the whole body - never 416.- assertEquals(ByteRangeResult.Whole, parseByteRange("bytes=abc-def", 100))- assertEquals(ByteRangeResult.Whole, parseByteRange("items=0-10", 100))- assertEquals(ByteRangeResult.Whole, parseByteRange("bytes=0-9,20-29", 100))- assertEquals(ByteRangeResult.Whole, parseByteRange("bytes=", 100))- }-- @Test- fun `whitespace and case in the header are tolerated`() {- assertEquals(- ByteRangeResult.Partial(ByteRange(0, 9)),- parseByteRange(" Bytes= 0 - 9 ", 100),- )- }-}
metadata_data/cast.md
diff --git a/metadata_data/cast.md b/metadata_data/cast.mdindex f4702d9a8f..46319ca984 100644--- a/metadata_data/cast.md+++ b/metadata_data/cast.md@@ -1,3 +1,3 @@-Cast to your TV and speakers-Send a video, a song, a photo or a link to any Chromecast, Google TV or Nest speaker on your Wi-Fi, with play, pause, seek and volume control.-The Cast protocol is implemented from scratch over a plain TLS socket, so there is no Google Play Services and no Cast SDK - and no storage permission either, because a file you pick is read straight from the URI you chose and served only to the device you picked.+Mirror your screen to your TV+Find any Chromecast, Google TV or Nest speaker on your Wi-Fi and mirror your screen to it, with volume control from the phone.+The Cast protocol is implemented from scratch over a plain TLS socket, so there is no Google Play Services and no Cast SDK - and no storage permission either, because nothing is read from your device.
metadata_data/photos/cast/1.png
diff --git a/metadata_data/photos/cast/1.png b/metadata_data/photos/cast/1.pngindex 647bba47dc..642a8e9d23 100644Binary files a/metadata_data/photos/cast/1.png and b/metadata_data/photos/cast/1.png differ
metadata_data/photos/cast/2.png
diff --git a/metadata_data/photos/cast/2.png b/metadata_data/photos/cast/2.pngindex d770626e0b..d90393d1c3 100644Binary files a/metadata_data/photos/cast/2.png and b/metadata_data/photos/cast/2.png differ
metadata_data/photos/cast/3.png
diff --git a/metadata_data/photos/cast/3.png b/metadata_data/photos/cast/3.pngindex d43cf1d774..86d04d029d 100644Binary files a/metadata_data/photos/cast/3.png and b/metadata_data/photos/cast/3.png differ
metadata_data/photos/cast/4.png
diff --git a/metadata_data/photos/cast/4.png b/metadata_data/photos/cast/4.pngindex edd9a793c1..e6dcd68a64 100644Binary files a/metadata_data/photos/cast/4.png and b/metadata_data/photos/cast/4.png differ