Modern Apps git

← Modern-Apps.git

cast: protocol v4 carries playback state and remote commands

Commit
739aa6f16fbe950ea86168ab1c6f52b0b7e8d051
Author
vayun-mathur <[email protected]>
When
2026-08-23 06:45 UTC (3 months ago)
Parents
aa7d13a

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 6b7157a76c..acdc83beb2 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@@ -14,8 +14,13 @@ import kotlinx.serialization.json.Json  * 3 is where H.264 stopped being the only codec. [DecoderLimits] became a per-codec list and  * [StreamConfig] gained a required codec, both reshaped rather than extended with compatibility  * defaults - a mismatch is refused outright anyway, so the bump is the honest signal.+ *+ * 4 adds [PlaybackState] and [PlaybackCommand], which turn the TV from a display into a remote. A+ * 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.  */-const val PROTOCOL_VERSION = 3+const val PROTOCOL_VERSION = 4  /** The mDNS service type the TV registers and the phone browses for. */ const val MACAST_SERVICE_TYPE = "_macast._tcp"@@ -36,6 +41,8 @@ const val MACAST_SERVICE_TYPE = "_macast._tcp"  *                          ◄───────────── STREAM_READY  (udp port + receiver SSRCs)  *        VIDEO_CODEC_CONFIG ─────────────────►          (AV1 only, and repeated on every PLI)  *        … RTP over UDP …+ *        PLAYBACK_STATE ─────────────────────►          (app content only, ~2/s while it plays)+ *                          ◄───────────── PLAYBACK_COMMAND (the TV remote, whenever it is pressed)  *        BYE ─────────────────────────────────►  * ```  *@@ -283,6 +290,136 @@ data class StreamReady( @SerialName("VIDEO_CODEC_CONFIG") 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.+ *+ * **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.+ *+ * [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.+ */+@Serializable+@SerialName("PLAYBACK_STATE")+data class PlaybackState(+    val positionMs: Long,+    /** Zero or negative for a stream with no known end, which the TV renders without a bar. */+    val durationMs: Long,+    val playing: Boolean,+    val buffering: Boolean,+    /** The tempo multiplier, 1.0 being normal. */+    val speed: Float = 1f,+    /** Media volume as 0..1, the same level on both ends - see `PLAYBACK_COMMAND`'s `SET_VOLUME`. */+    val volume: Float = 1f,+    val hasNext: Boolean = false,+    val hasPrevious: 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.+     *+     * 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.+     */+    fun interpolated(elapsedMs: Long): Long {+        if (!playing || elapsedMs <= 0) return positionMs.coerceAtLeast(0)+        val advanced = positionMs + (elapsedMs * speed.toDouble()).toLong()+        return if (durationMs > 0) advanced.coerceIn(0, durationMs) else advanced.coerceAtLeast(0)+    }+}++/**+ * A press on the television's remote, TV to phone.+ *+ * **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.+ *+ * 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.+ */+@Serializable+@SerialName("PLAYBACK_COMMAND")+data class PlaybackCommand(+    val action: PlaybackAction,+    /**+     * The action's argument, or null for the ones that take none.+     *+     * One nullable `Double` rather than a field per type: milliseconds for [PlaybackAction.SeekTo], a+     * multiplier for [PlaybackAction.SetSpeed], 0..1 for [PlaybackAction.SetVolume]. A `Double`+     * represents every millisecond of a plausible video exactly, so nothing is lost by not having a+     * `Long` here, and the alternative is three mostly-null fields that can disagree.+     */+    val value: Double? = null,+) : ControlMessage++/**+ * What the remote asked for.+ *+ * Serial names are pinned because these cross the wire; the Kotlin identifiers are free to change.+ */+@Serializable+enum class PlaybackAction {+    @SerialName("PLAY")+    Play,++    @SerialName("PAUSE")+    Pause,++    /**+     * Whichever of the two the phone 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+     * doing nothing.+     */+    @SerialName("TOGGLE")+    Toggle,++    /** [PlaybackCommand.value] is an absolute position in milliseconds. */+    @SerialName("SEEK_TO")+    SeekTo,++    /** The phone's own skip interval, so the two ends cannot disagree about how far ten seconds is. */+    @SerialName("SKIP_FORWARD")+    SkipForward,++    @SerialName("SKIP_BACK")+    SkipBack,++    @SerialName("NEXT")+    Next,++    @SerialName("PREVIOUS")+    Previous,++    /** [PlaybackCommand.value] is a tempo multiplier. */+    @SerialName("SET_SPEED")+    SetSpeed,++    /** [PlaybackCommand.value] is 0..1, and moves the phone's media volume as well as the TV's. */+    @SerialName("SET_VOLUME")+    SetVolume,+}+ /**  * Either end, at any point after the secret is established.  *
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.ktnew file mode 100644index 0000000000..a07668f649--- /dev/null+++ b/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/PlaybackTest.kt@@ -0,0 +1,135 @@+package com.vayunmathur.cast.protocol++import kotlin.test.Test+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 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+ * is otherwise only visible by watching a television.+ */+class PlaybackTest {++    private val codec = ControlCodec()++    @Test+    fun `both playback messages round-trip through the codec`() {+        val messages = listOf<ControlMessage>(+            PlaybackState(+                positionMs = 42_500,+                durationMs = 600_000,+                playing = true,+                buffering = false,+                speed = 1.5f,+                volume = 0.4f,+                hasNext = true,+                hasPrevious = false,+            ),+            // Every default at once, which is the case `encodeDefaults` could quietly eat.+            PlaybackState(positionMs = 0, durationMs = 0, playing = false, buffering = true),+            PlaybackCommand(PlaybackAction.Toggle),+            PlaybackCommand(PlaybackAction.SeekTo, value = 125_000.0),+            PlaybackCommand(PlaybackAction.SetSpeed, value = 2.0),+            PlaybackCommand(PlaybackAction.SetVolume, value = 0.0),+        )+        for (message in messages) {+            assertEquals(message, codec.decode(codec.encode(message)), "$message did not round-trip")+        }+    }++    @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.+        for ((action, wire) in mapOf(+            PlaybackAction.Play to "PLAY",+            PlaybackAction.Pause to "PAUSE",+            PlaybackAction.Toggle to "TOGGLE",+            PlaybackAction.SeekTo to "SEEK_TO",+            PlaybackAction.SkipForward to "SKIP_FORWARD",+            PlaybackAction.SkipBack to "SKIP_BACK",+            PlaybackAction.Next to "NEXT",+            PlaybackAction.Previous to "PREVIOUS",+            PlaybackAction.SetSpeed to "SET_SPEED",+            PlaybackAction.SetVolume to "SET_VOLUME",+        )) {+            val body = codec.encode(PlaybackCommand(action)).toString(Charsets.UTF_8)+            assertTrue(body.contains("\"action\":\"$wire\""), body)+        }+        assertTrue(+            codec.encode(PlaybackCommand(PlaybackAction.Play))+                .toString(Charsets.UTF_8)+                .contains("\"type\":\"PLAYBACK_COMMAND\""),+        )+        assertTrue(+            codec.encode(PlaybackState(0, 0, playing = false, buffering = false))+                .toString(Charsets.UTF_8)+                .contains("\"type\":\"PLAYBACK_STATE\""),+        )+    }++    @Test+    fun `an argumentless command carries no value rather than a null one`() {+        val body = codec.encode(PlaybackCommand(PlaybackAction.Next)).toString(Charsets.UTF_8)+        assertTrue(!body.contains("value"), body)+    }++    @Test+    fun `a paused snapshot holds still however long it is held`() {+        val paused = PlaybackState(30_000, 600_000, playing = false, buffering = false)+        assertEquals(30_000, paused.interpolated(0))+        assertEquals(30_000, paused.interpolated(5_000))+        assertEquals(30_000, paused.interpolated(600_000))+    }++    @Test+    fun `a playing snapshot advances with elapsed wall-clock time`() {+        val playing = PlaybackState(30_000, 600_000, playing = true, buffering = false)+        assertEquals(30_000, playing.interpolated(0))+        assertEquals(30_500, playing.interpolated(500))+        assertEquals(31_000, playing.interpolated(1_000))+    }++    @Test+    fun `speed scales the advance, so a 2x video does not lag its own bar`() {+        val fast = PlaybackState(0, 600_000, playing = true, buffering = false, speed = 2f)+        assertEquals(1_000, fast.interpolated(500))+        val slow = PlaybackState(0, 600_000, playing = true, buffering = false, speed = 0.5f)+        assertEquals(250, slow.interpolated(500))+    }++    @Test+    fun `a fresh snapshot re-anchors rather than compounding the last estimate`() {+        // What makes drift bounded by one heartbeat: the phone's number always wins, even when it+        // moves backwards because the user scrubbed on the phone.+        val first = PlaybackState(10_000, 600_000, playing = true, buffering = false)+        assertEquals(10_500, first.interpolated(500))+        val second = PlaybackState(3_000, 600_000, playing = true, buffering = false)+        assertEquals(3_500, second.interpolated(500))+    }++    @Test+    fun `interpolation stops at the end rather than running past it`() {+        val nearEnd = PlaybackState(599_800, 600_000, playing = true, buffering = false)+        assertEquals(600_000, nearEnd.interpolated(5_000))+    }++    @Test+    fun `an unknown duration still advances, because a live stream has no end to stop at`() {+        val live = PlaybackState(1_000, 0, playing = true, buffering = false)+        assertEquals(6_000, live.interpolated(5_000))+    }++    @Test+    fun `nonsense inputs produce a position rather than a negative one`() {+        // A clock that went backwards, and a phone that reported a position before the start. Both+        // are drawable as zero; neither should put a bar off the left of the screen.+        val playing = PlaybackState(1_000, 600_000, playing = true, buffering = false)+        assertEquals(1_000, playing.interpolated(-500))+        assertEquals(0, PlaybackState(-5, 600_000, playing = false, buffering = false).interpolated(0))+    }+}