cast: report and obey playback on the TV in a served session
- Commit
58a3124522a90e7831d791c55c439ad0c5b578a8- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-24 00:21 UTC (3 months ago)
- Parents
15836df
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 a0b93e52df..131c1b6ead 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@@ -27,8 +27,16 @@ import kotlinx.serialization.json.Json * [StreamConfig.videoCodec] became optional in the same bump, and [DecoderLimits] grew an audio half. * [Ping] arrived in the same version, once a served session turned out to be able to go quiet for * longer than either end's read timeout allows.+ *+ * 6 turns a served session's transport the right way round. [PlaybackState] and [PlaybackCommand]+ * are unchanged and reused in the reverse direction - see [ControlMessage] - because for a file the+ * TV holds the media, the clock and the buffer, so the phone was reporting a player that makes no+ * sound and commanding one that cannot be heard. [ContentEnded], [PlaybackState.ended] and+ * [PlayMedia.startPositionMs] arrive with it. A version-5 TV would drop every command and report no+ * state: a session that streams perfectly with a dead remote, which is worse than a refusal for+ * exactly the reason `MIN_CAST_VERSION_CODE`'s own KDoc gives. */-const val PROTOCOL_VERSION = 5+const val PROTOCOL_VERSION = 6 /** The mDNS service type the TV registers and the phone browses for. */ const val MACAST_SERVICE_TYPE = "_macast._tcp"@@ -60,13 +68,25 @@ const val MACAST_SERVICE_TYPE = "_macast._tcp" * ``` * 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)+ * PLAY_MEDIA ──────────────────────────► (which resource, and from what position) * … the TV fetches byte ranges over HTTPS and decodes them itself …+ * PLAYBACK_COMMAND ───────────────────► (the phone's transport, wherever it was pressed)+ * ◄───────────── PLAYBACK_STATE (the TV's own player, ~2/s while it plays) * PING ────────────────────────────────► (every 20 s, so neither read deadline expires) * ◄───────────── PING (echoed straight back)+ * CONTENT_ENDED ───────────────────────► (release the player, keep the channel) * BYE ─────────────────────────────────► * ``` *+ * **The two transport messages run the other way here, and that is the point.** [PlaybackState] is+ * phone→TV and [PlaybackCommand] is TV→phone for mirroring, which is right when the phone's player is+ * what makes the sound. For a served session the television holds the media, the clock and the+ * buffer, so it is the only end that can report the truth - and the only end a command can usefully+ * be applied to. The messages already carry exactly the right fields and [ControlCodec] is+ * symmetric, so they are reused rather than duplicated. [PlaybackState.hasNext] and+ * [PlaybackState.hasPrevious] stay phone-owned and are ignored when the TV sends them: the queue is+ * only visible on the phone.+ * * 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.@@ -403,8 +423,33 @@ data class PlayMedia( * before the first byte arrives rather than appearing a moment into playback. */ val durationMs: Long = 0,+ /**+ * Where to start, so handing playback over keeps the position instead of restarting the track.+ *+ * Defaulted because every other use of this message is a fresh item, which starts at zero. It is+ * a request rather than a guarantee: a resource still being written has no length and cannot be+ * seeked, so the TV will begin at the start whatever this says - which is a limit of a growing+ * stream, not of this field.+ */+ val startPositionMs: Long = 0, ) : ControlMessage +/**+ * Stop playing and let go of the player - but keep this connection, phone to TV.+ *+ * **Distinct from [Bye], which ends the *connection*.** The phone stops a content session far more+ * often than it disconnects from a television: closing one app's cast should leave the TV paired,+ * connected and ready for the next, because that pairing is exactly what the user just spent time+ * on. Sending [Bye] instead would throw it away.+ *+ * Sent rather than inferred, and sent **before the proxy stops**. Nothing else tells the TV: it owns+ * its own clock and buffer, so it would carry on playing what it had already fetched and then fail+ * its next request against a port that has gone - an error card where the idle screen belongs.+ */+@Serializable+@SerialName("CONTENT_ENDED")+data object ContentEnded : ControlMessage+ /** * The video decoder's configuration bytes, phone to TV, for a codec that cannot carry them in-band. *@@ -422,20 +467,22 @@ data class PlayMedia( data class VideoCodecConfig(val csd: String) : ControlMessage /**- * Where playback is, phone to TV, so a television can draw a seek bar for something it is only- * decoding.+ * Where playback is, so the end that cannot see the player can draw a seek bar for it. * * **A snapshot, never a delta.** Sent on any material change and otherwise at a slow heartbeat, and * every field is absolute - so a lost message costs at most one heartbeat of staleness and repairs * itself, with no sequence numbers, no acknowledgements and no resynchronisation path to get wrong. *- * **The phone owns the truth.** The TV cannot compute [positionMs] for itself: what it holds is a- * 150 ms RTP jitter buffer, which is a smoothing device and not a content clock. Between snapshots it- * interpolates from the last one it received, and every fresh snapshot re-anchors that estimate.+ * **Which end owns the truth depends on which end owns the player.** For screen mirroring this is+ * phone→TV: the phone encodes pixels, so its player *is* the content clock, and what the TV holds is+ * a 150 ms RTP jitter buffer - a smoothing device, not a clock. For a served session it runs the+ * other way, because there the television fetched the file and owns the decoder, the buffer and the+ * position. Either way the receiver of this message interpolates from the last one it was sent, and+ * every fresh snapshot re-anchors that estimate. *- * [hasNext] and [hasPrevious] are carried because the TV must not offer a button that does nothing -- * and it has no way to know whether there is anything to skip to, since the queue is a list of- * related videos that only the phone can see.+ * [hasNext] and [hasPrevious] are **always the phone's**, in both directions, and ignored when the TV+ * sends them: the queue is a list only the phone can see, and a remote must not offer a button that+ * does nothing. */ @Serializable @SerialName("PLAYBACK_STATE")@@ -451,22 +498,32 @@ data class PlaybackState( val volume: Float = 1f, val hasNext: Boolean = false, val hasPrevious: Boolean = false,+ /**+ * The item finished on its own, so the other end can advance the queue.+ *+ * Its own field rather than a `positionMs ≈ durationMs && !playing` reading, which is+ * indistinguishable from a pause at the end of a track - and has nothing to compare against at+ * all while a transcode is still growing, because such a stream states no duration.+ *+ * Defaulted, so it means what it always meant coming from a sender that never sets it.+ */+ val ended: Boolean = false, ) : ControlMessage { /** * Where playback will be [elapsedMs] after this snapshot arrived. *- * The TV redraws at its display's rate from snapshots that land twice a second, so a bar plotted- * at [positionMs] would visibly step. It records the wall-clock time each snapshot arrived and- * asks this for the position now; every fresh snapshot re-anchors, so the estimate can drift for- * at most one heartbeat and never accumulates.+ * The receiver redraws at its display's rate from snapshots that land twice a second, so a bar+ * plotted at [positionMs] would visibly step. It records the wall-clock time each snapshot+ * arrived and asks this for the position now; every fresh snapshot re-anchors, so the estimate+ * can drift for at most one heartbeat and never accumulates. * * A pure function of two numbers on purpose - it is the one piece of this feature that can be * pinned down without a television in the room. * * Paused holds still, [speed] scales the advance, and the result never runs past [durationMs].- * Buffering needs no case of its own: the phone reports [playing] from the player's own- * `isPlaying`, which is already false while it stalls.+ * Buffering needs no case of its own: [playing] is the player's own `isPlaying`, which is already+ * false while it stalls. */ fun interpolated(elapsedMs: Long): Long { if (!playing || elapsedMs <= 0) return positionMs.coerceAtLeast(0)@@ -476,16 +533,20 @@ data class PlaybackState( } /**- * A press on the television's remote, TV to phone.+ * A press on whichever transport the user reached for, sent to whichever end owns the player.+ *+ * TV→phone for screen mirroring, where the phone's player is what makes the sound; phone→TV for a+ * served session, where the television's is. See [ControlMessage]. * * **One message with an action enum rather than ten message types.** The set of things a remote can * ask for is going to grow, and a TV that needed a protocol bump to gain a button would mean shipping- * both apps again for a change that is entirely on one side. The phone ignores an action it does not- * recognise, which is the only forward compatibility this needs.+ * both apps again for a change that is entirely on one side. The receiver ignores an action it does+ * not recognise, which is the only forward compatibility this needs. *- * The phone is free to refuse any of these. A [PlaybackAction.Next] with nothing to play next is- * dropped rather than answered, and the TV finds out the ordinary way - the next [PlaybackState]- * simply does not change.+ * The receiver is free to refuse any of these. A [PlaybackAction.Next] with nothing to play next is+ * dropped rather than answered, and the sender finds out the ordinary way - the next [PlaybackState]+ * simply does not change. [PlaybackAction.Next] and [PlaybackAction.Previous] arriving at a *TV* are+ * always dropped, because only the phone can see the queue. */ @Serializable @SerialName("PLAYBACK_COMMAND")@@ -516,10 +577,10 @@ enum class PlaybackAction { Pause, /**- * Whichever of the two the phone is not currently doing.+ * Whichever of the two the player is not currently doing. * * Distinct from [Play] and [Pause] on purpose: a D-pad centre press means "the other one", and- * asking the TV to decide from its own possibly-stale snapshot is how a double press ends up+ * asking the sender to decide from its own possibly-stale snapshot is how a double press ends up * doing nothing. */ @SerialName("TOGGLE")@@ -529,13 +590,14 @@ enum class PlaybackAction { @SerialName("SEEK_TO") SeekTo, - /** The phone's own skip interval, so the two ends cannot disagree about how far ten seconds is. */+ /** A discrete skip, by whatever interval the end holding the player uses for one. */ @SerialName("SKIP_FORWARD") SkipForward, @SerialName("SKIP_BACK") SkipBack, + /** Always answered by the phone, whichever direction it arrived from: the queue is the phone's. */ @SerialName("NEXT") Next, @@ -587,6 +649,9 @@ const val PING_INTERVAL_MS = 20_000L * * Sent rather than just closing the socket, so the TV can return to its idle screen instead of * holding the last frame while it waits for a read to time out.+ *+ * Ends the *connection*, and the pairing state that goes with being connected. [ContentEnded] is what+ * ends a content session while keeping it. */ @Serializable @SerialName("BYE")
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.ktindex a6254d213c..9883fbc741 100644--- a/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/ContentSessionTest.kt+++ b/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/ContentSessionTest.kt@@ -80,6 +80,29 @@ class ContentSessionTest { assertEquals("251/17", back.resourceId) } + @Test+ fun `handing playback over carries the position it was at`() {+ // Without this the track restarts every time a cast begins, which is the one thing a handover+ // is supposed not to do.+ val play = PlayMedia("track-1", "audio/ogg", durationMs = 214_000, startPositionMs = 91_500)+ val back = assertIs<PlayMedia>(roundTrip(play))+ assertEquals(91_500L, back.startPositionMs)+ }++ @Test+ fun `a fresh item starts at the beginning without saying so`() {+ val back = assertIs<PlayMedia>(roundTrip(PlayMedia("track-1", "audio/ogg")))+ assertEquals(0L, back.startPositionMs)+ }++ @Test+ fun `ending a content session is not the same message as ending the connection`() {+ // A TV that took one for the other would drop the pairing the user had just established, and+ // the next cast would ask them to pick the television again.+ assertIs<ContentEnded>(roundTrip(ContentEnded))+ assertIs<Bye>(roundTrip(Bye(reason = "user disconnected")))+ }+ @Test fun `an unknown duration is zero rather than absent`() { val back = assertIs<PlayMedia>(roundTrip(PlayMedia("track-1", "audio/ogg")))@@ -99,6 +122,7 @@ class ContentSessionTest { ControlJson.encodeToString(PlayMedia("a", "audio/ogg") as ControlMessage) .contains("\"PLAY_MEDIA\""), )+ assertTrue(ControlJson.encodeToString(ContentEnded as ControlMessage).contains("\"CONTENT_ENDED\"")) assertTrue(ControlJson.encodeToString(Ping as ControlMessage).contains("\"PING\"")) }
cast/protocol/src/test/java/com/vayunmathur/cast/protocol/PlaybackTest.kt
diff --git a/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/PlaybackTest.kt b/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/PlaybackTest.ktindex a07668f649..077858833f 100644--- a/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/PlaybackTest.kt+++ b/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/PlaybackTest.kt@@ -5,8 +5,8 @@ import kotlin.test.assertEquals import kotlin.test.assertTrue /**- * The two messages that turn the television into a remote, and the one piece of arithmetic behind- * its seek bar.+ * The two messages that carry a transport in either direction, and the one piece of arithmetic behind+ * a seek bar. * * The interpolation is here rather than in `:cast:tv` deliberately: it is a pure function of a * snapshot and an elapsed time, so it is provable on the JVM, and a seek bar that drifts or overshoots@@ -31,6 +31,8 @@ class PlaybackTest { ), // Every default at once, which is the case `encodeDefaults` could quietly eat. PlaybackState(positionMs = 0, durationMs = 0, playing = false, buffering = true),+ // A track that finished on its own, which is what makes the other end advance its queue.+ PlaybackState(positionMs = 214_000, durationMs = 214_000, playing = false, buffering = false, ended = true), PlaybackCommand(PlaybackAction.Toggle), PlaybackCommand(PlaybackAction.SeekTo, value = 125_000.0), PlaybackCommand(PlaybackAction.SetSpeed, value = 2.0),@@ -41,10 +43,19 @@ class PlaybackTest { } } + @Test+ fun `an item still playing is not reported as ended`() {+ // Defaulted, so a sender written against the older contract still means what it meant - and a+ // spurious `ended` would skip the track it was describing.+ val playing = PlaybackState(1_000, 214_000, playing = true, buffering = false)+ val back = codec.decode(codec.encode(playing)) as PlaybackState+ assertTrue(!back.ended)+ }+ @Test fun `action names on the wire are the stable ones, not the Kotlin identifiers`() { // Renaming `Toggle` or `SkipBack` must not change the wire format: the failure would be a- // remote whose buttons stop working while both ends agree they are on version 4.+ // transport whose buttons stop working while both ends agree they are on version 6. for ((action, wire) in mapOf( PlaybackAction.Play to "PLAY", PlaybackAction.Pause to "PAUSE",
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.ktindex ed45bc437f..a375785741 100644--- 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.kt@@ -16,6 +16,9 @@ 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.PlaybackAction+import com.vayunmathur.cast.protocol.PlaybackCommand+import com.vayunmathur.cast.protocol.PlaybackState import com.vayunmathur.cast.protocol.ProtocolBase64 import javax.net.ssl.HttpsURLConnection @@ -34,6 +37,11 @@ private const val TAG = "ContentPlayer" * 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.+ *+ * **This player is the truth about a served session**, which is what [snapshot] and [apply] are for.+ * The phone has no player running - it deliberately paused its own before the cast started - so it+ * neither knows where playback is nor could usefully be asked to move it. Everything the phone shows+ * and everything it commands passes through here. */ @OptIn(UnstableApi::class) class ContentPlayer(@@ -43,12 +51,83 @@ class ContentPlayer( private var player: ExoPlayer? = null + /**+ * Called whenever something about playback changed, so a snapshot can go out at once.+ *+ * A pause that took half a second to reach the phone's notification reads as a dropped button+ * press. The heartbeat behind this exists for position, which changes constantly and would make+ * "changed" mean "always".+ *+ * Runs on the player's own thread, which is the main thread.+ */+ var onChanged: (() -> Unit)? = null++ /**+ * What the phone said the item runs for, used until the player works it out for itself.+ *+ * This is the whole reason `PLAY_MEDIA` carries a duration. A resource still being encoded has no+ * length in its container either, so ExoPlayer reports none - and a seek bar that appears only once+ * a track has finished encoding is a seek bar that never appears on a first play.+ */+ private var statedDurationMs: Long = 0+ /** 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 duration: Long get() = player?.duration?.takeIf { it > 0 } ?: statedDurationMs val isPlaying: Boolean get() = player?.isPlaying == true val isBuffering: Boolean get() = player?.playbackState == Player.STATE_BUFFERING + /**+ * The item played to its end on its own, which is what lets the phone advance its queue.+ *+ * A flag rather than something inferred from position against duration: those are+ * indistinguishable from a pause at the end of a track, and a growing transcode has no duration to+ * compare against at all.+ */+ val isEnded: Boolean get() = player?.playbackState == Player.STATE_ENDED++ val speed: Float get() = player?.playbackParameters?.speed ?: 1f++ val volume: Float get() = player?.volume ?: 1f++ /**+ * Everything the phone needs to draw this player, as an absolute snapshot.+ *+ * `hasNext` and `hasPrevious` are left at their defaults deliberately: the queue is a list only+ * the phone can see, so it owns them in both directions and ignores whatever arrives from here.+ */+ fun snapshot(): PlaybackState = PlaybackState(+ positionMs = position,+ durationMs = duration,+ playing = isPlaying,+ buffering = isBuffering,+ speed = speed,+ volume = volume,+ ended = isEnded,+ )++ /**+ * Do what a transport asked, wherever it was pressed.+ *+ * [PlaybackAction.Next] and [PlaybackAction.Previous] are refused rather than handled, and must+ * be: there is no queue here to advance, and the phone answers them by sending a fresh+ * `PLAY_MEDIA`. Returns whether this player owned the command, so a caller can pass the rest on.+ */+ fun apply(command: PlaybackCommand): Boolean {+ when (command.action) {+ PlaybackAction.Play -> play()+ PlaybackAction.Pause -> pause()+ PlaybackAction.Toggle -> if (isPlaying) pause() else play()+ PlaybackAction.SeekTo -> command.value?.let { seekTo(it.toLong()) }+ PlaybackAction.SkipForward -> seekTo(position + SKIP_MS)+ PlaybackAction.SkipBack -> seekTo((position - SKIP_MS).coerceAtLeast(0))+ PlaybackAction.SetSpeed -> command.value?.let { setSpeed(it.toFloat()) }+ PlaybackAction.SetVolume -> command.value?.let { setVolume(it.toFloat()) }+ PlaybackAction.Next, PlaybackAction.Previous -> return false+ }+ return true+ }+ /** * Builds the player, or returns false if the fingerprint was unusable. *@@ -85,6 +164,12 @@ class ContentPlayer( Log.w(TAG, "playback failed: ${error.errorCodeName}", error) onError(error.errorCodeName) }++ // Everything at once rather than a callback per field: the reporter's job is to notice+ // that *something* changed, and it compares snapshots itself to decide whether to send.+ override fun onEvents(player: Player, events: Player.Events) {+ onChanged?.invoke()+ } }) built.playWhenReady = true player = built@@ -106,8 +191,12 @@ class ContentPlayer( // 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)+ Log.i(TAG, "playing ${media.resourceId} (${media.mimeType}) from ${media.startPositionMs}ms")+ statedDurationMs = media.durationMs+ // A position rather than the start, so handing playback over from the phone keeps it. A+ // resource still being written cannot honour it - there is no length to seek against - and+ // ExoPlayer then begins at the beginning, which is the honest outcome rather than a failure.+ active.setMediaItem(item, media.startPositionMs) active.prepare() active.play() }@@ -145,6 +234,7 @@ class ContentPlayer( } fun release() {+ onChanged = null runCatching { player?.release() } player = null }@@ -152,6 +242,14 @@ class ContentPlayer( private companion object { const val FINGERPRINT_BYTES = 32 + /**+ * How far a discrete skip moves, now that this end applies one.+ *+ * Its own constant rather than a number the phone supplies: the press is applied here so that+ * it acts at once, and a round trip to ask how far ten seconds is would defeat that.+ */+ const val SKIP_MS = 10_000L+ /** 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
cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverController.kt
diff --git a/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverController.kt b/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverController.ktindex 0f754ea3f1..5160ced8a7 100644--- a/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverController.kt+++ b/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverController.kt@@ -6,6 +6,7 @@ import android.util.Log import android.view.Surface import com.vayunmathur.cast.protocol.Bye import com.vayunmathur.cast.protocol.ByeReason+import com.vayunmathur.cast.protocol.ContentEnded import com.vayunmathur.cast.protocol.ContentReady import com.vayunmathur.cast.protocol.ContentSession import com.vayunmathur.cast.protocol.DecodableFrame@@ -41,14 +42,19 @@ import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.currentCoroutineContext+import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.flow.distinctUntilChanged+import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.update import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import kotlinx.coroutines.NonCancellable+import kotlinx.coroutines.delay import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext import java.net.DatagramSocket@@ -95,6 +101,15 @@ private const val RECEIVE_BUFFER_BYTES = 2 * 1024 * 1024 /** One press of the remote's volume key. Sixteen steps end to end, which is what a TV usually offers. */ private const val VOLUME_STEP = 1f / 16f +/**+ * How often a served session's playback goes to the phone even when nothing changed.+ *+ * Matches the cadence the phone used to report at, and for the same reason: every message is an+ * absolute snapshot, so this is the longest anything can be stale for, and the receiving end+ * interpolates position between them precisely so it does not need them faster.+ */+private const val REPORT_HEARTBEAT_MS = 500L+ /** * The single owner of the live receiving session. *@@ -185,10 +200,28 @@ object ReceiverController { private var channel: ControlChannel? = null /**- * Ask the phone to do something. Dropped silently with no session, which is the honest answer:- * the remote was pressed at a screen with nothing playing on it.+ * Do what the remote asked, wherever the player for it happens to be.+ *+ * **A served session applies the press here**, because that is where the player is: the phone+ * paused its own before the cast started, so a round trip to it would move nothing and take a+ * LAN's latency doing it. The phone finds out from the next snapshot, half a second later at+ * worst. Screen mirroring is the other way round - the phone's player is the one making the+ * sound - so the command goes to it, unchanged.+ *+ * [PlaybackAction.Next] and [PlaybackAction.Previous] always go to the phone, whichever kind of+ * session it is: the queue is a list only the phone can see. Dropped silently with no session,+ * which is the honest answer - the remote was pressed at a screen with nothing playing on it. */ fun send(command: PlaybackCommand) {+ val served = contentPlayer+ // On the main thread already, which is where ExoPlayer must be touched: every caller is+ // `MirrorActivity`'s key handling.+ if (served != null && served.apply(command)) {+ // A press has to be visible before the reporter's next tick, or the overlay lags the+ // sound coming out of this very box.+ onPlaybackState(served.snapshot())+ return+ } val live = channel ?: return scope.launch { runCatching { live.send(command) }@@ -196,7 +229,7 @@ object ReceiverController { } } - /** Skip forward or back by the phone's own interval, which is the phone's to decide. */+ /** Skip forward or back by whichever interval the end holding the player uses. */ fun skip(forward: Boolean) { send(PlaybackCommand(if (forward) PlaybackAction.SkipForward else PlaybackAction.SkipBack)) }@@ -204,10 +237,10 @@ object ReceiverController { /** * Nudge the shared volume level up or down by one step. *- * Sent to the phone rather than applied here, even though the sound comes out of this end. The- * phone owns the level - it stores it, it reports it, and it keeps it for local playback once the- * cast is over - so the round trip is what makes the two ends agree. The gain follows about half a- * second later when the next snapshot arrives, which is faster than a hand leaves a button.+ * The level is read from the last snapshot rather than held separately, so there is one answer to+ * "how loud is it" however the session is arranged. [send] then puts the new level wherever the+ * player is: on this box's own player for a served session, or on the phone for screen mirroring,+ * where the phone owns the level, stores it, and keeps it for local playback afterwards. * * Returns false with no session, so the key falls through to the box's own volume control. */@@ -418,30 +451,60 @@ object ReceiverController { if (!authenticate(channel, store, keys, transcriptValue, greeting)) return _state.update { it.copy(phase = ReceiverPhase.Connected(greeting.senderName)) } - val configured = channel.receive() ?: return- // The fork between the two kinds of session. Screen mirroring has no file behind it and keeps- // the RTP path; anything with a file is served over HTTPS and decoded here, which is why- // seeking becomes an offset and a pause is nobody's business but this end's.- val config = when (val first = configured.message) {- is StreamConfig -> first- is ContentSession -> {- serveContent(context, channel, first, greeting.senderName)- return+ // **A loop rather than one configuration, because a content session gives the channel back.**+ // Ending a cast is far more common than disconnecting a television, and the pairing is exactly+ // what the user just spent time on - so `CONTENT_ENDED` returns here and the next cast starts+ // without re-picking the TV. Screen mirroring never comes back: its session lives in the UDP+ // loop until the socket dies.+ while (true) {+ val configured = channel.receive() ?: return+ // The fork between the two kinds of session. Screen mirroring has no file behind it and+ // keeps the RTP path; anything with a file is served over HTTPS and decoded here, which is+ // why seeking becomes an offset and a pause is nobody's business but this end's.+ when (val first = configured.message) {+ is StreamConfig -> {+ startStreaming(channel, keys, first, greeting.senderName)+ mirrorSession(channel, first, greeting.senderName)+ return+ }+ is ContentSession -> {+ if (!serveContent(context, channel, first, greeting.senderName)) return+ _state.update { it.copy(phase = ReceiverPhase.Connected(greeting.senderName)) }+ forgetPlayback()+ }+ is Bye -> {+ Log.i(TAG, "'${greeting.senderName}' said goodbye")+ return+ }+ // Echoed rather than treated as a surprise, so a keep-alive cannot end the very channel+ // it exists to preserve. A snapshot or a command still in flight from the session that+ // just ended is dropped for the same reason: there is no longer a player for either.+ is Ping -> runCatching { channel.send(Ping) }+ is PlaybackState, is PlaybackCommand -> Unit+ else -> return }- else -> return }- startStreaming(channel, keys, config, greeting.senderName)+ } - // The session now lives in the UDP loop; this coroutine stays here so a BYE or a dropped- // socket tears everything down through the same path. It is also where the codec configuration- // arrives, which for AV1 is what the media loop is waiting on before it can start a decoder at- // all - it is repeated on every key-frame request, so this handles it more than once. And it is- // where playback snapshots arrive, twice a second, for as long as an app is casting content.+ /**+ * The rest of a screen-mirroring session: everything that arrives while the UDP loop runs.+ *+ * The session now lives in that loop; this coroutine stays here so a BYE or a dropped socket tears+ * everything down through the same path. It is also where the codec configuration arrives, which+ * for AV1 is what the media loop is waiting on before it can start a decoder at all - it is+ * repeated on every key-frame request, so this handles it more than once. And it is where playback+ * snapshots arrive, twice a second, for as long as an app is casting encoded content.+ */+ private suspend fun mirrorSession(+ channel: ControlChannel,+ config: StreamConfig,+ senderName: String,+ ) { while (true) { val next = channel.receive() ?: break when (val message = next.message) { is Bye -> {- Log.i(TAG, "'${greeting.senderName}' said goodbye")+ Log.i(TAG, "'$senderName' said goodbye") return } is VideoCodecConfig -> onVideoCodecConfig(message, config)@@ -461,23 +524,31 @@ object ReceiverController { * key frame, and there is no picture-loss indicator to send because there are no lost pictures. * What is left is a URL, a pinned certificate and a player that owns its own clock. *+ * **And because it owns the clock, it owns the truth.** A reporting coroutine puts this player's+ * state on the channel - immediately when something changes, and otherwise at+ * [REPORT_HEARTBEAT_MS] - which is what lets every surface on the phone show what is actually+ * playing. `PLAYBACK_COMMAND` arrives here rather than leaving, for the same reason.+ * * ExoPlayer must be built and driven from the thread whose looper it took, so every call into it * hops to the main thread. The control channel stays on this coroutine, because it is the same * blocking read it always was.+ *+ * Returns true when the phone ended the *session* and wants to keep the connection, so the caller+ * can go back to waiting for the next configuration. */ private suspend fun serveContent( context: Context, channel: ControlChannel, session: ContentSession, senderName: String,- ) {+ ): Boolean { if (!session.video && AudioPlayer.limits().isEmpty()) { // The failure that used to be silence. A TV with no Opus decoder and no picture to fall // back on has to say so, and the phone has to be told rather than left streaming into it. Log.w(TAG, "refusing an audio-only session: this TV has no Opus decoder") channel.send(ContentReady(accepted = false, detail = "this TV has no Opus decoder")) _state.update { it.copy(phase = ReceiverPhase.Failed(ReceiverFailure.NoAudioDecoder)) }- return+ return false } val player = withContext(Dispatchers.Main) { ContentPlayer(context, session) }@@ -488,7 +559,7 @@ object ReceiverController { channel.send(ContentReady(accepted = false, detail = "the player could not be built")) _state.update { it.copy(phase = ReceiverPhase.Failed(ReceiverFailure.Handshake)) } withContext(NonCancellable + Dispatchers.Main) { player.release() }- return+ return false } contentPlayer = player@@ -511,16 +582,33 @@ object ReceiverController { } Log.i(TAG, "serving content from ${session.host}:${session.port} for '${session.appLabel}'") + // A third writer on this channel, alongside the ping echo and this coroutine's own sends.+ // Nothing guards it here because nothing needs to: `ControlChannel.send` encodes and writes+ // under one lock, so a frame cannot interleave with another and the cipher's nonce cannot+ // advance twice for one message. What a mutex would add is ordering between *sequences*, and+ // there are none here - every send is a single message.+ val reporting = scope.launch { report(player, channel) } try { while (true) {- val next = channel.receive() ?: break+ val next = channel.receive() ?: return false when (val message = next.message) { is Bye -> { Log.i(TAG, "'$senderName' said goodbye")- return+ return false+ }+ // The phone is done casting but not done with us. Distinct from a `Bye`, and the+ // difference is the pairing: this leaves the TV connected and ready for the next+ // cast rather than back at its idle screen waiting to be picked again.+ is ContentEnded -> {+ Log.i(TAG, "'$senderName' ended the content session")+ return true } is PlayMedia -> withContext(Dispatchers.Main) { player.play(message) }- is PlaybackState -> onPlaybackState(message)+ // The phone's transport, wherever it was pressed - its own screen, a notification,+ // a headset button, a car. Applied to the player that is actually making the+ // sound. `Next` and `Previous` are refused by the player and arrive as a fresh+ // `PLAY_MEDIA` instead, because only the phone can see the queue.+ is PlaybackCommand -> withContext(Dispatchers.Main) { player.apply(message) } // Echoed straight back, which is the whole of the keep-alive. Reading it has // already pushed this end's deadline out; replying is what pushes the phone's, // since a read timeout is not reset by anything that end sends.@@ -529,6 +617,11 @@ object ReceiverController { } } } finally {+ // Cancelled **and joined**, under NonCancellable because this runs on the teardown path a+ // cancelled session takes. A publish already past its last suspension point would+ // otherwise land after the caller has cleared the overlay, putting a stale 0:00 snapshot+ // back on the idle screen and making `nudgeVolume` answer for a session that has gone.+ withContext(NonCancellable) { reporting.cancelAndJoin() } contentPlayer = null // NonCancellable because this is the teardown path a cancelled session takes, and an // ExoPlayer left unreleased holds a codec the next session will ask for.@@ -537,11 +630,64 @@ object ReceiverController { } /**- * Take a playback snapshot, and stamp it with the moment it arrived.+ * Keep the phone's copy of this player current, for as long as the session lasts.+ *+ * Two cadences, because they answer different needs. Anything the phone *renders* differently goes+ * out the instant it changes - a pause that took half a second to reach a notification reads as a+ * dropped button press. Position is deliberately excluded from that test: it moves constantly, so+ * "changed" would mean "always", and the phone interpolates between snapshots precisely so it does+ * not need them faster.+ *+ * The heartbeat underneath is what makes the whole thing self-repairing: every message is an+ * absolute snapshot, so a lost one costs at most one interval of staleness and needs no+ * acknowledgement, no sequence number and no retry.+ *+ * Each snapshot is also published locally, because this box draws its own overlay from the same+ * numbers - it is the source of them now, so there is nothing else to draw from.+ */+ private suspend fun report(player: ContentPlayer, channel: ControlChannel) {+ // Built on the main thread, because every getter behind `snapshot` asserts the player's own+ // looper - reading them from this coroutine would throw rather than report a stale number.+ val latest = withContext(Dispatchers.Main) {+ MutableStateFlow(player.snapshot()).also { flow ->+ player.onChanged = { flow.value = player.snapshot() }+ }+ }+ try {+ coroutineScope {+ launch {+ latest+ .map { it.copy(positionMs = 0) }+ .distinctUntilChanged()+ .collect { publish(latest.value, channel) }+ }+ while (isActive) {+ delay(REPORT_HEARTBEAT_MS)+ latest.value = withContext(Dispatchers.Main) { player.snapshot() }+ publish(latest.value, channel)+ }+ }+ } finally {+ withContext(NonCancellable + Dispatchers.Main) { player.onChanged = null }+ }+ }++ /** One snapshot, to this box's own overlay and to the phone. */+ private fun publish(snapshot: PlaybackState, channel: ControlChannel) {+ onPlaybackState(snapshot)+ runCatching { channel.send(snapshot) }+ .onFailure { Log.w(TAG, "could not report playback", it) }+ }++ /**+ * Take a playback snapshot, and stamp it with the moment it became true.+ *+ * The timestamp is taken here rather than in the UI because this is the closest thing to "when it+ * was so" that exists - anything later would fold recomposition delay into the seek bar's anchor. *- * The timestamp is taken here rather than in the UI because this is the closest thing to "when the- * phone said so" that exists on this side - anything later would fold recomposition delay into the- * seek bar's anchor.+ * Fed from the phone for screen mirroring and from this box's own player for a served session,+ * which is the whole of the direction change: the overlay is drawn from whichever end owns the+ * clock, through one field either way. * * Not logged. Two of these a second would drown the once-a-second throughput line that everything * else about a session is diagnosed from.
sdk/cast/src/main/java/com/vayunmathur/sdk/cast/CastContract.kt
diff --git a/sdk/cast/src/main/java/com/vayunmathur/sdk/cast/CastContract.kt b/sdk/cast/src/main/java/com/vayunmathur/sdk/cast/CastContract.ktindex 10682ad73c..b5997423f2 100644--- a/sdk/cast/src/main/java/com/vayunmathur/sdk/cast/CastContract.kt+++ b/sdk/cast/src/main/java/com/vayunmathur/sdk/cast/CastContract.kt@@ -37,6 +37,15 @@ package com.vayunmathur.sdk.cast * … Cast serves byte ranges of that fd to the TV, which decodes them itself … * ``` *+ * **And it reverses the transport, because the television owns the player.** There is nothing playing+ * on the phone in a content session - the app paused its own player before the cast began - so the TV+ * is the only end that knows where playback is, and the only end a command can be applied to:+ *+ * ```+ * ◄── MSG_TV_PLAYBACK_STATE (the TV's player, ~2/s)+ * MSG_SEND_PLAYBACK_COMMAND ─► (whatever the user pressed, wherever)+ * ```+ * * A resource may also be offered while it is still being written, with a negative length - which * is what lets an app start playback before it has finished encoding: *@@ -86,8 +95,13 @@ object CastContract { * the user has no way to tell it apart from a broken TV. So the old app blocks the cast and says * to update, in the same breath as the protocol version bump that already forces both halves to * ship together.+ *+ * **Bumped again for a served session's reversed transport**, on the same argument in the other+ * direction: a Cast that cannot carry the television's own playback state back to the app reports+ * nothing while the TV plays, so every surface on the phone shows a paused player and every button+ * on it drives a player nobody can hear. */- const val MIN_CAST_VERSION_CODE = 20260823L+ const val MIN_CAST_VERSION_CODE = 20260824L // ---- client → service ---- @@ -151,6 +165,21 @@ object CastContract { */ const val MSG_RESOURCE_COMPLETE = 10 + /**+ * Ask the television to do something, in a content session.+ *+ * Carries [KEY_ACTION] and maybe [KEY_ACTION_VALUE] - the same payload as+ * [MSG_PLAYBACK_COMMAND], travelling the other way.+ *+ * **A new id rather than [MSG_PLAYBACK_COMMAND] reused in reverse.** The *types* are deliberately+ * shared, because the set of things a transport can ask for does not depend on which end is asked;+ * a constant that meant opposite things depending on which `Messenger` delivered it would make the+ * sequence above a lie, and there is no reader of this file who could tell which was meant.+ *+ * Ignored without a session, so a client need not track readiness itself.+ */+ const val MSG_SEND_PLAYBACK_COMMAND = 12+ // ---- service → client ---- /**@@ -184,6 +213,22 @@ object CastContract { */ const val MSG_RESOURCE_REQUEST = 7 + /**+ * Where the *television's* playback is, in a content session.+ *+ * The inverse of [MSG_PLAYBACK_STATE], and its own id for the reason+ * [MSG_SEND_PLAYBACK_COMMAND] gives. Carries the same keys, plus [KEY_ENDED].+ *+ * An absolute snapshot on the same terms: sent on any material change and otherwise at a slow+ * heartbeat, so a dropped one costs at most one heartbeat of staleness. [KEY_HAS_NEXT] and+ * [KEY_HAS_PREVIOUS] are meaningless here and should be ignored - the queue is the client's, and+ * the TV has never been able to see it.+ *+ * A client that leaves [CastClient.onPlaybackState] null still casts; it simply shows a player+ * that does not move, which is what this exists to fix.+ */+ const val MSG_TV_PLAYBACK_STATE = 11+ // ---- MSG_OPEN_SESSION payload ---- /** Requested frame width in pixels. Clamped; read the granted size back, do not assume it. */@@ -306,12 +351,21 @@ object CastContract { */ const val KEY_MEDIA_DURATION_MS = "mediaDurationMs" + /**+ * Where the TV should start the item, in milliseconds. Absent means the beginning.+ *+ * What makes handing playback over keep its place instead of restarting the track. A request+ * rather than a guarantee: a resource offered with a negative [KEY_RESOURCE_LENGTH] has nothing+ * to seek against, so the TV begins at the start whatever this says.+ */+ const val KEY_START_POSITION_MS = "startPositionMs"+ // ---- MSG_SESSION_ENDED payload ---- /** One of the `REASON_` constants. */ const val KEY_END_REASON = "endReason" - // ---- MSG_PLAYBACK_STATE payload ----+ // ---- MSG_PLAYBACK_STATE / MSG_TV_PLAYBACK_STATE payload ---- /** * Where playback is and where it ends, in milliseconds.@@ -344,12 +398,22 @@ object CastContract { * Whether there is anything to skip to. * * Carried because the TV cannot know: what is next is the client's own idea of a queue, and a- * remote that offers a button doing nothing is worse than one that offers none.+ * remote that offers a button doing nothing is worse than one that offers none. Meaningless in a+ * [MSG_TV_PLAYBACK_STATE], where the client is the one who knows. */ const val KEY_HAS_NEXT = "hasNext" const val KEY_HAS_PREVIOUS = "hasPrevious" - // ---- MSG_PLAYBACK_COMMAND payload ----+ /**+ * The item finished on its own, in a [MSG_TV_PLAYBACK_STATE]. Absent means it did not.+ *+ * What lets a client advance its queue. Its own key rather than a position-against-duration+ * reading, which is indistinguishable from a pause at the end of a track - and has no duration to+ * compare against at all while a resource is still being written.+ */+ const val KEY_ENDED = "ended"++ // ---- MSG_PLAYBACK_COMMAND / MSG_SEND_PLAYBACK_COMMAND payload ---- /** One of the `ACTION_` constants. Unknown values must be ignored, not treated as an error. */ const val KEY_ACTION = "action"@@ -361,7 +425,7 @@ object CastContract { const val KEY_ACTION_VALUE = "actionValue" /**- * What the remote asked for.+ * What the transport asked for. * * **Deliberately a second definition of `:cast:protocol`'s `PlaybackAction`, not a reuse of it.** * This module is the public client contract and every consumer compiles against it; giving it a@@ -378,10 +442,10 @@ object CastContract { const val ACTION_PAUSE = 1 /**- * Whichever of play and pause the client is not currently doing.+ * Whichever of play and pause the end holding the player is not currently doing. *- * Its own action rather than the TV choosing from its last snapshot: that snapshot can be half a- * second old, and two quick presses resolved against it would both send the same thing.+ * Its own action rather than the sender choosing from its last snapshot: that snapshot can be half+ * a second old, and two quick presses resolved against it would both send the same thing. */ const val ACTION_TOGGLE = 2 @@ -392,6 +456,7 @@ object CastContract { const val ACTION_SKIP_FORWARD = 4 const val ACTION_SKIP_BACK = 5 + /** Always answered by the *client*, whichever way it arrived: the queue is the client's. */ const val ACTION_NEXT = 6 const val ACTION_PREVIOUS = 7
version.txt
diff --git a/version.txt b/version.txtindex 7171078c54..b063b9f87f 100644--- a/version.txt+++ b/version.txt@@ -1,2 +1,2 @@-20260823-v2.6.8+20260824+v2.6.9