cast: protocol v5 and a TV player for media the phone serves
- Commit
6e24c09b2d83df28f2bbd9e4395afa520b5ea0dc- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-23 18:17 UTC (3 months ago)
- Parents
a421333
Diff
cast/protocol/src/main/java/com/vayunmathur/cast/protocol/HandshakeMessages.kt
diff --git a/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/HandshakeMessages.kt b/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/HandshakeMessages.ktindex 18d37b086f..05e62044e2 100644--- a/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/HandshakeMessages.kt+++ b/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/HandshakeMessages.kt@@ -19,8 +19,14 @@ import kotlinx.serialization.json.Json * phone on 3 would never send state, so the TV's overlay would be permanently empty, and a TV on 3 * would drop every command it was sent - both are silent failures, which is exactly what a refused * version check is for.+ *+ * 5 is where app content stopped being pixels. [ContentSession] and [PlayMedia] replace+ * `STREAM_CONFIG` for anything with a file behind it: the phone serves the original bytes over HTTPS+ * and the TV decodes them, so no video is encoded, seeking is a byte offset and audio-only becomes+ * expressible at all. Screen mirroring keeps the RTP path unchanged, because it has no file to serve.+ * [StreamConfig.videoCodec] became optional in the same bump, and [DecoderLimits] grew an audio half. */-const val PROTOCOL_VERSION = 4+const val PROTOCOL_VERSION = 5 /** The mDNS service type the TV registers and the phone browses for. */ const val MACAST_SERVICE_TYPE = "_macast._tcp"@@ -46,6 +52,17 @@ const val MACAST_SERVICE_TYPE = "_macast._tcp" * BYE ─────────────────────────────────► * ``` *+ * Screen mirroring takes that path. **App content takes a different one from `STREAM_CONFIG`+ * onward**, because it has a file behind it and does not need to be re-encoded:+ *+ * ```+ * CONTENT_SESSION ─────────────────────► (proxy host, port, cert fingerprint, token)+ * ◄───────────── CONTENT_READY (accepted, or refused with a reason)+ * PLAY_MEDIA ──────────────────────────► (which resource, and what is in it)+ * … the TV fetches byte ranges over HTTPS and decodes them itself …+ * BYE ─────────────────────────────────►+ * ```+ * * Everything from `PAIR_REQUIRED` onward is AES-256-GCM under the derived control key; the first * three messages cannot be, because they are what establishes it. Both ends install the cipher at * the same point in the sequence, so they can never disagree about which frames are encrypted.@@ -309,6 +326,81 @@ data class StreamReady( val videoSsrc: Long, ) : ControlMessage +/**+ * The phone is serving app content over HTTPS instead of encoding it. Everything the TV needs to+ * fetch it.+ *+ * This is what replaces [StreamConfig] for anything with a file behind it, and the reason the whole+ * pixel path can go away for app content: the TV fetches byte ranges of the original media and owns+ * its own decoder, clock and buffer. Seeking becomes an offset instead of a key-frame renegotiation,+ * a pause is the TV's business alone, and the phone neither decodes nor encodes a frame.+ *+ * **The fingerprint is why this can be TLS with no certificate authority.** It arrives here, on a+ * channel already AES-256-GCM under a key derived from the ML-KEM handshake and bound to the pairing+ * transcript - so pinning it is strictly stronger than trusting a CA to attest to a name on a LAN.+ * The TV must pin it and trust nothing else; a permissive trust manager would throw away the only+ * guarantee the pairing bought.+ *+ * [token] is a capability, not an identifier. It goes in the URL path so that it travels with a bare+ * URL handed to a player, and it is the only thing between another device on the LAN that has found+ * the port and the user's media.+ */+@Serializable+@SerialName("CONTENT_SESSION")+data class ContentSession(+ /** The phone's address on this network, as the TV should dial it. */+ val host: String,+ val port: Int,+ /** Base64 of SHA-256 over the proxy certificate's DER encoding. */+ val certificateFingerprint: String,+ val token: String,+ /**+ * False for an audio-only session, where there is no picture and the TV shows a now-playing+ * screen instead of a black surface.+ */+ val video: Boolean,+ /** The app whose content this is, resolved by `:cast` from the picker's `callingPackage`. */+ val appLabel: String = "",+) : ControlMessage++/**+ * Whether the TV can serve a [ContentSession], and if not, why.+ *+ * An answer rather than silence because the failures here are the kind that otherwise look like+ * success: a TV with no Opus decoder would accept an audio-only session and then play nothing, with+ * no picture to make the fault visible and nothing on screen to explain it. The phone refuses the+ * session instead and says so, which is the whole argument for the reply existing.+ */+@Serializable+@SerialName("CONTENT_READY")+data class ContentReady(+ val accepted: Boolean,+ /** For the log and for the phone's message to the user. Empty when accepted. */+ val detail: String = "",+) : ControlMessage++/**+ * Play this, from the proxy.+ *+ * [resourceId] is the app's own name for it, appended to the proxy's path; the phone maps it back to+ * a file descriptor when the TV asks. Sent again for each new item, which is how a queue advances -+ * the queue itself stays on the phone, because it owns the artwork, the metadata and the ordering.+ */+@Serializable+@SerialName("PLAY_MEDIA")+data class PlayMedia(+ val resourceId: String,+ /** What the TV should expect, so its player does not have to sniff before it can start. */+ val mimeType: String,+ /**+ * Length in milliseconds, or 0 when the phone does not know.+ *+ * Carried even though the container states it, because the TV's seek bar can then be drawn+ * before the first byte arrives rather than appearing a moment into playback.+ */+ val durationMs: Long = 0,+) : ControlMessage+ /** * The video decoder's configuration bytes, phone to TV, for a codec that cannot carry them in-band. *
cast/protocol/src/test/java/com/vayunmathur/cast/protocol/ContentSessionTest.kt
diff --git a/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/ContentSessionTest.kt b/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/ContentSessionTest.ktnew file mode 100644index 0000000000..5fc2f76870--- /dev/null+++ b/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/ContentSessionTest.kt@@ -0,0 +1,106 @@+package com.vayunmathur.cast.protocol++import kotlinx.serialization.encodeToString+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertIs+import kotlin.test.assertTrue++/**+ * Tests for the messages that set up a served content session.+ *+ * These three carry the whole of the new arrangement, so what matters is that every field survives+ * the trip. A dropped `certificateFingerprint` is a TV that trusts nothing and plays nothing; a+ * dropped `token` is a `403` from the phone's own proxy; a dropped `port` is a connection refused.+ * All three look identical from the sofa, so they are pinned here where they can be told apart.+ */+class ContentSessionTest {++ private val session = ContentSession(+ host = "192.168.0.14",+ port = 43_117,+ certificateFingerprint = ProtocolBase64.encode(ByteArray(32) { (it * 3).toByte() }),+ token = "Zm9vYmFyLXRva2VuLXRoYXQtaXMtdXJsLXNhZmU",+ video = false,+ appLabel = "Music",+ )++ @Test+ fun `a content session survives the trip with every field intact`() {+ val back = assertIs<ContentSession>(roundTrip(session))+ assertEquals(session, back)+ // Spelled out as well as compared, because an equals on a data class would pass just as+ // happily if two fields had swapped places in a hand-written encoder.+ assertEquals("192.168.0.14", back.host)+ assertEquals(43_117, back.port)+ assertEquals(session.certificateFingerprint, back.certificateFingerprint)+ assertEquals(session.token, back.token)+ assertFalse(back.video)+ assertEquals("Music", back.appLabel)+ }++ @Test+ fun `the fingerprint round-trips as the 32 bytes the TV has to pin`() {+ val raw = ByteArray(32) { (it * 3).toByte() }+ val back = assertIs<ContentSession>(roundTrip(session))+ val decoded = ProtocolBase64.decode(back.certificateFingerprint)+ assertTrue(raw.contentEquals(decoded), "the TV would pin the wrong certificate")+ }++ @Test+ fun `a video session says so`() {+ val back = assertIs<ContentSession>(roundTrip(session.copy(video = true)))+ assertTrue(back.video, "the TV decides whether to add a surface at all from this")+ }++ @Test+ fun `a refusal carries its reason`() {+ val back = assertIs<ContentReady>(+ roundTrip(ContentReady(accepted = false, detail = "no Opus decoder")),+ )+ assertFalse(back.accepted)+ assertEquals("no Opus decoder", back.detail)+ }++ @Test+ fun `an acceptance needs no reason`() {+ val back = assertIs<ContentReady>(roundTrip(ContentReady(accepted = true)))+ assertTrue(back.accepted)+ assertEquals("", back.detail)+ }++ @Test+ fun `a play request carries what to fetch and what is in it`() {+ val play = PlayMedia(resourceId = "251/17", mimeType = "audio/ogg", durationMs = 214_000)+ val back = assertIs<PlayMedia>(roundTrip(play))+ assertEquals(play, back)+ // Slashes are meaningful: everything after the token in the URL is the resource id, so a+ // segment addressed by itag and sequence number has to survive as one string.+ assertEquals("251/17", back.resourceId)+ }++ @Test+ fun `an unknown duration is zero rather than absent`() {+ val back = assertIs<PlayMedia>(roundTrip(PlayMedia("track-1", "audio/ogg")))+ assertEquals(0L, back.durationMs, "the TV draws no seek bar for a length it does not know")+ }++ @Test+ fun `the wire names are pinned`() {+ // Both ends switch on these strings, and a rename would be a message silently dropped by a+ // build that otherwise looks identical.+ assertTrue(ControlJson.encodeToString(session as ControlMessage).contains("\"CONTENT_SESSION\""))+ assertTrue(+ ControlJson.encodeToString(ContentReady(true) as ControlMessage)+ .contains("\"CONTENT_READY\""),+ )+ assertTrue(+ ControlJson.encodeToString(PlayMedia("a", "audio/ogg") as ControlMessage)+ .contains("\"PLAY_MEDIA\""),+ )+ }++ private fun roundTrip(message: ControlMessage): ControlMessage =+ ControlJson.decodeFromString(ControlJson.encodeToString(message))+}
cast/tv/build.gradle.kts
diff --git a/cast/tv/build.gradle.kts b/cast/tv/build.gradle.ktsindex 712d3a9998..84ff244bff 100644--- a/cast/tv/build.gradle.kts+++ b/cast/tv/build.gradle.kts@@ -31,6 +31,9 @@ android { dependencies { // The wire format, shared verbatim with the phone. Nothing in this app re-implements it. implementation(project(":cast:protocol"))- // PqcIdentity: the TV's long-term ML-KEM identity, which the phone seals the session secret to. implementation(project(":library:e2ee-p2p"))+ // App content arrives as media rather than as pixels now, so the TV needs a player. Not+ // `media3-session`: the TV already has a remote-control path through its own control channel,+ // and a MediaSession would be a second one competing with it.+ implementation(libs.androidx.media3.exoplayer) }
cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ContentPlayer.kt
diff --git a/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ContentPlayer.kt b/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ContentPlayer.ktnew file mode 100644index 0000000000..ed45bc437f--- /dev/null+++ b/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ContentPlayer.kt@@ -0,0 +1,165 @@+package com.vayunmathur.cast.tv.platform++import android.content.Context+import android.util.Log+import android.view.Surface+import androidx.annotation.OptIn+import androidx.media3.common.MediaItem+import androidx.media3.common.MimeTypes+import androidx.media3.common.PlaybackException+import androidx.media3.common.Player+import androidx.media3.common.util.UnstableApi+import androidx.media3.datasource.DefaultHttpDataSource+import androidx.media3.exoplayer.ExoPlayer+import androidx.media3.exoplayer.source.DefaultMediaSourceFactory+import com.vayunmathur.cast.protocol.ContentSession+import com.vayunmathur.cast.protocol.EphemeralTls+import com.vayunmathur.cast.protocol.MediaProxy+import com.vayunmathur.cast.protocol.PlayMedia+import com.vayunmathur.cast.protocol.ProtocolBase64+import javax.net.ssl.HttpsURLConnection++private const val TAG = "ContentPlayer"++/**+ * Plays app content the phone is serving, rather than decoding pixels it encoded.+ *+ * This is the other half of the change that removes the encoder from the phone. The TV fetches byte+ * ranges of the original media over HTTPS and hands them to its own decoder, so it owns the clock,+ * the buffer and the seeking - and every pathology of the RTP path stops applying rather than being+ * fixed. A pause is a pause. A seek is a byte offset. There is no picture-loss indicator because+ * there are no lost pictures to indicate.+ *+ * **Trust is the session's, not a PKI's.** The certificate fingerprint arrived over the control+ * channel, which the pairing already authenticated, so the player's data source trusts exactly that+ * one certificate. Nothing here is told to skip verification - the point of pinning is that it+ * verifies something stronger than a name.+ */+@OptIn(UnstableApi::class)+class ContentPlayer(+ private val context: Context,+ private val session: ContentSession,+) {++ private var player: ExoPlayer? = null++ /** Where playback is, for the phone. Null until the player has produced anything. */+ val position: Long get() = player?.currentPosition ?: 0L+ val duration: Long get() = player?.duration?.takeIf { it > 0 } ?: 0L+ val isPlaying: Boolean get() = player?.isPlaying == true+ val isBuffering: Boolean get() = player?.playbackState == Player.STATE_BUFFERING++ /**+ * Builds the player, or returns false if the fingerprint was unusable.+ *+ * [onError] is reported rather than swallowed: a failed load on this path used to be invisible,+ * and an expired resource that produces no error and no picture is the hardest kind of fault to+ * attribute.+ */+ fun start(onError: (String) -> Unit): Boolean {+ val fingerprint = ProtocolBase64.decode(session.certificateFingerprint)+ if (fingerprint == null || fingerprint.size != FINGERPRINT_BYTES) {+ Log.w(TAG, "the phone sent an unusable certificate fingerprint")+ return false+ }++ // Process-wide because `DefaultHttpDataSource` is `HttpURLConnection`-backed and takes its+ // socket factory from the default. Acceptable here and nowhere else: this app makes no other+ // HTTPS request, so there is nothing else whose trust could be narrowed by accident.+ HttpsURLConnection.setDefaultSSLSocketFactory(EphemeralTls.client(fingerprint).socketFactory)++ val http = DefaultHttpDataSource.Factory()+ .setConnectTimeoutMs(CONNECT_TIMEOUT_MS)+ .setReadTimeoutMs(READ_TIMEOUT_MS)+ // The proxy answers from a file descriptor the phone's app supplied, and can be slow to+ // get one. A redirect is never legitimate here.+ .setAllowCrossProtocolRedirects(false)++ val built = ExoPlayer.Builder(context)+ .setMediaSourceFactory(DefaultMediaSourceFactory(http))+ .build()+ built.addListener(object : Player.Listener {+ override fun onPlayerError(error: PlaybackException) {+ // Deliberately loud. The old path reported load errors as end-of-stream, so an+ // expired URL produced silence and no explanation at either end.+ Log.w(TAG, "playback failed: ${error.errorCodeName}", error)+ onError(error.errorCodeName)+ }+ })+ built.playWhenReady = true+ player = built+ Log.i(+ TAG,+ "content player up for ${session.host}:${session.port}, " ++ if (session.video) "audio and video" else "audio only",+ )+ return true+ }++ /** Points the player at a resource on the proxy and starts it. */+ fun play(media: PlayMedia) {+ val active = player ?: return+ val url = MediaProxy.url(session.host, session.port, session.token, media.resourceId)+ val item = MediaItem.Builder()+ .setUri(url)+ // Stated rather than sniffed: the phone knows what it is serving, and sniffing costs a+ // round trip before anything can start.+ .setMimeType(media.mimeType.ifBlank { MimeTypes.BASE_TYPE_AUDIO })+ .build()+ Log.i(TAG, "playing ${media.resourceId} (${media.mimeType})")+ active.setMediaItem(item)+ active.prepare()+ active.play()+ }++ /**+ * Hands the player a surface, or takes it away.+ *+ * Null is the audio-only case and the case where the TV's surface has gone - handing the player+ * a surface that has been destroyed is what makes the *next* session fail rather than this one.+ */+ fun setSurface(surface: Surface?) {+ player?.setVideoSurface(surface)+ }++ fun play() {+ player?.play()+ }++ fun pause() {+ player?.pause()+ }++ fun seekTo(positionMs: Long) {+ // A byte offset on this path, not a key-frame renegotiation. This is the line that used to+ // be a round trip to the phone and a wait for a fresh key frame.+ player?.seekTo(positionMs)+ }++ fun setSpeed(speed: Float) {+ player?.setPlaybackSpeed(speed)+ }++ fun setVolume(volume: Float) {+ player?.volume = volume.coerceIn(0f, 1f)+ }++ fun release() {+ runCatching { player?.release() }+ player = null+ }++ private companion object {+ const val FINGERPRINT_BYTES = 32++ /** The phone is on the same LAN, so a slow connect means something is wrong rather than far. */+ const val CONNECT_TIMEOUT_MS = 8_000++ /**+ * Longer than the connect timeout, because the proxy may be waiting on the app for a+ * descriptor - but bounded, so a phone that has stopped answering surfaces as a load error+ * rather than as a picture that never arrives.+ */+ const val READ_TIMEOUT_MS = 15_000+ }+}