sdk: cast clients can report playback and take remote commands
- Commit
b5d74c354a77285bdcacd54e3bb514e559502c3f- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-23 06:48 UTC (3 months ago)
- Parents
739aa6f
Diff
sdk/cast/src/main/java/com/vayunmathur/sdk/cast/CastClient.kt
diff --git a/sdk/cast/src/main/java/com/vayunmathur/sdk/cast/CastClient.kt b/sdk/cast/src/main/java/com/vayunmathur/sdk/cast/CastClient.ktindex 42cd98fb3c..4497798bf4 100644--- a/sdk/cast/src/main/java/com/vayunmathur/sdk/cast/CastClient.kt+++ b/sdk/cast/src/main/java/com/vayunmathur/sdk/cast/CastClient.kt@@ -81,6 +81,17 @@ class CastClient(context: Context) { */ var onEnded: ((Int) -> Unit)? = null + /**+ * Called when somebody presses a button on the television's remote.+ *+ * Optional: a client that leaves this null still casts, it simply has no remote - and the TV shows+ * no overlay either, because the overlay only appears once [reportPlaybackState] has been called.+ * So the two halves are opt-in together and there is no way to end up with dead buttons on screen.+ *+ * Runs on the main thread, like [onEnded], so it can drive a player directly.+ */+ var onCommand: ((PlaybackCommand) -> Unit)? = null+ private var service: Messenger? = null private var bound = false @@ -103,6 +114,12 @@ class CastClient(context: Context) { onSessionEnded(reason) true }+ CastContract.MSG_PLAYBACK_COMMAND -> {+ // Dropped rather than queued when the session is not live: a command that arrived+ // during teardown would drive a player the TV is no longer showing.+ if (open) PlaybackCommand.from(msg.data)?.let { onCommand?.invoke(it) }+ true+ } else -> false } },@@ -191,6 +208,30 @@ class CastClient(context: Context) { } } + /**+ * Tell the TV where playback is, so it can draw a seek bar for content only this app can see.+ *+ * Call it on any material change and otherwise at a slow heartbeat - twice a second is enough,+ * because the TV extrapolates between snapshots. Every field is absolute rather than a delta, so a+ * dropped one costs at most one heartbeat of staleness and needs no retry.+ *+ * Silent and non-throwing, unlike everything else here: this is called from a poll loop, so a+ * failure would be a failure per tick, and there is nothing a caller could usefully do about one.+ * It is also what mounts the TV's overlay - stop calling it and the remote goes away with it.+ */+ fun reportPlaybackState(state: PlaybackState) {+ if (!open) return+ val remote = service ?: return+ val message = Message.obtain(null, CastContract.MSG_PLAYBACK_STATE).apply {+ data = state.toBundle()+ }+ try {+ remote.send(message)+ } catch (_: RemoteException) {+ // Cast is gone; onServiceDisconnected is what says so, and it will.+ }+ }+ /** * End the session and unbind. Idempotent, and safe if [openSession] never succeeded. *@@ -198,6 +239,7 @@ class CastClient(context: Context) { */ fun close() { onEnded = null+ onCommand = null pending = null if (open) { try {
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 08565d026b..0b6cc5b263 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@@ -20,6 +20,8 @@ package com.vayunmathur.sdk.cast * bind the service, MSG_OPEN_SESSION ─► (width, height, wantAudio) * ◄── MSG_SESSION_READY (Surface, audio pipe, granted size) * … render into the Surface, write PCM into the pipe …+ * MSG_PLAYBACK_STATE ─► (position, duration, playing, …)+ * ◄── MSG_PLAYBACK_COMMAND (the TV remote was pressed) * unbind, or MSG_CLOSE_SESSION ─► * ◄── MSG_SESSION_ENDED (reason) * ```@@ -54,8 +56,15 @@ object CastContract { * Must stay in lockstep with the root `version.txt` value at the build that first shipped * [SERVICE_CLASS]. An older Cast has no such service, so binding would fail with nothing to say * why; probing the version code first is what turns that into an actionable "update Cast".+ *+ * **Bumped for the transport controls, and that is a deliberate refusal rather than a+ * degradation.** A Cast without [MSG_PLAYBACK_STATE] would stream perfectly and give the+ * television a remote whose every button did nothing, which is a worse failure than not casting:+ * 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. */- const val MIN_CAST_VERSION_CODE = 20260816L+ const val MIN_CAST_VERSION_CODE = 20260823L // ---- client → service ---- @@ -73,6 +82,17 @@ object CastContract { */ const val MSG_CLOSE_SESSION = 2 + /**+ * Where playback is, so the television can draw a seek bar for content only it can see.+ *+ * Carries [KEY_POSITION_MS] and its neighbours as an absolute snapshot rather than a delta, which+ * is what makes a dropped one cost nothing. Fire and forget: there is no reply, and a client that+ * stops sending simply leaves the TV's overlay stale until the session ends.+ *+ * Ignored unless a session is open, so a client may send it without tracking readiness itself.+ */+ const val MSG_PLAYBACK_STATE = 5+ // ---- service → client ---- /**@@ -84,6 +104,16 @@ object CastContract { /** The session is over, for the reason in [KEY_END_REASON]. The `Surface` is invalid from here. */ const val MSG_SESSION_ENDED = 4 + /**+ * Somebody pressed a button on the television's remote. Carries [KEY_ACTION] and maybe+ * [KEY_ACTION_VALUE].+ *+ * Delivered only for a session this client opened, and only for app content - screen mirroring has+ * no transport to control. A client that does not handle these is not broken: the TV's overlay+ * will simply never appear, because it is only mounted once state arrives.+ */+ const val MSG_PLAYBACK_COMMAND = 6+ // ---- MSG_OPEN_SESSION payload ---- /** Requested frame width in pixels. Clamped; read the granted size back, do not assume it. */@@ -136,6 +166,101 @@ object CastContract { /** One of the `REASON_` constants. */ const val KEY_END_REASON = "endReason" + // ---- MSG_PLAYBACK_STATE payload ----++ /**+ * Where playback is and where it ends, in milliseconds.+ *+ * A duration of zero or less means "no known end", which the TV renders without a bar rather than+ * as a zero-length one.+ */+ const val KEY_POSITION_MS = "positionMs"+ const val KEY_DURATION_MS = "durationMs"++ /**+ * Whether media is advancing, which is not the same as whether the user asked for it to.+ *+ * Report the player's own "is playing" rather than its play-when-ready flag: the TV extrapolates+ * position between snapshots, and a stall reported as playing would run its seek bar ahead of the+ * picture and then jerk it back.+ */+ const val KEY_PLAYING = "playing"++ /** For a spinner. Separate from [KEY_PLAYING] because a stall is not a pause. */+ const val KEY_BUFFERING = "buffering"++ /** Tempo multiplier, 1.0 being normal. */+ const val KEY_SPEED = "speed"++ /** Media volume as 0..1. The same level on both ends - see [ACTION_SET_VOLUME]. */+ const val KEY_VOLUME = "volume"++ /**+ * 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.+ */+ const val KEY_HAS_NEXT = "hasNext"+ const val KEY_HAS_PREVIOUS = "hasPrevious"++ // ---- MSG_PLAYBACK_COMMAND payload ----++ /** One of the `ACTION_` constants. Unknown values must be ignored, not treated as an error. */+ const val KEY_ACTION = "action"++ /**+ * The action's argument, for the actions that take one: milliseconds for [ACTION_SEEK_TO], a+ * multiplier for [ACTION_SET_SPEED], 0..1 for [ACTION_SET_VOLUME]. Absent otherwise.+ */+ const val KEY_ACTION_VALUE = "actionValue"++ /**+ * What the remote 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+ * dependency on the streaming protocol would hand every casting app the wire format, the crypto+ * and the RTP packetiser, which is the whole thing brokering exists to avoid. `:cast` depends on+ * both and owns the mapping between them, so the duplication is one file wide and one function+ * deep.+ *+ * Ints rather than an enum for the same reason [MSG_OPEN_SESSION] is: this crosses a `Bundle`,+ * and a `Serializable` enum in a `Bundle` is a class-loading problem waiting for a client built+ * against a different SDK version.+ */+ const val ACTION_PLAY = 0+ const val ACTION_PAUSE = 1++ /**+ * Whichever of play and pause the client 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.+ */+ const val ACTION_TOGGLE = 2++ /** [KEY_ACTION_VALUE] is an absolute position in milliseconds. */+ const val ACTION_SEEK_TO = 3++ /** The client's own skip interval, so the two ends cannot disagree about how far it is. */+ const val ACTION_SKIP_FORWARD = 4+ const val ACTION_SKIP_BACK = 5++ const val ACTION_NEXT = 6+ const val ACTION_PREVIOUS = 7++ /** [KEY_ACTION_VALUE] is a tempo multiplier. */+ const val ACTION_SET_SPEED = 8++ /**+ * [KEY_ACTION_VALUE] is 0..1, and is the level for *both* ends.+ *+ * The client is expected to move its own media volume to match, so that the level survives the+ * session ending and local playback resumes where the TV left it.+ */+ const val ACTION_SET_VOLUME = 9+ /** The app asked, via [MSG_CLOSE_SESSION] or by unbinding. */ const val REASON_CLIENT_CLOSED = 0
sdk/cast/src/main/java/com/vayunmathur/sdk/cast/Playback.kt
diff --git a/sdk/cast/src/main/java/com/vayunmathur/sdk/cast/Playback.kt b/sdk/cast/src/main/java/com/vayunmathur/sdk/cast/Playback.ktnew file mode 100644index 0000000000..7e941f14ea--- /dev/null+++ b/sdk/cast/src/main/java/com/vayunmathur/sdk/cast/Playback.kt@@ -0,0 +1,133 @@+package com.vayunmathur.sdk.cast++import android.os.Bundle++/**+ * Where playback is, for the television to draw a seek bar from.+ *+ * **A deliberate second definition of `:cast:protocol`'s message of the same name, not a reuse of+ * it.** This module is the public client contract: every app that casts compiles against it, and+ * giving it a dependency on `:cast:protocol` would hand each of them the wire format, the crypto and+ * the RTP packetiser - which is the entire thing brokering exists to avoid. `:cast` depends on both+ * sides and owns the translation, so the duplication is one file wide and two functions deep, and it+ * buys a public API that cannot leak the protocol.+ *+ * A snapshot rather than a delta: absolute in every field, so a lost one repairs itself on the next+ * heartbeat and there is no sequence number to get wrong.+ */+data class PlaybackState(+ val positionMs: Long,+ /** Zero or less for something with no known end, which the TV draws without a bar. */+ val durationMs: Long,+ /**+ * Whether media is actually advancing.+ *+ * Report the player's own "is playing" rather than its play-when-ready flag: the TV extrapolates+ * position between snapshots, and a stall reported as playing runs its seek bar ahead of the+ * picture and then snaps it back.+ */+ val playing: Boolean,+ /** For a spinner. Distinct from [playing], because a stall is not a pause. */+ val buffering: Boolean = false,+ /** Tempo multiplier, 1.0 being normal. */+ val speed: Float = 1f,+ /** Media volume as 0..1, the same level on both ends. */+ val volume: Float = 1f,+ /**+ * Whether there is anything to skip to.+ *+ * Carried because the TV cannot know - what comes next is this app's own idea of a queue - and a+ * remote offering a button that does nothing is worse than one offering none.+ */+ val hasNext: Boolean = false,+ val hasPrevious: Boolean = false,+) {+ internal fun toBundle(): Bundle = Bundle().apply {+ putLong(CastContract.KEY_POSITION_MS, positionMs)+ putLong(CastContract.KEY_DURATION_MS, durationMs)+ putBoolean(CastContract.KEY_PLAYING, playing)+ putBoolean(CastContract.KEY_BUFFERING, buffering)+ putFloat(CastContract.KEY_SPEED, speed)+ putFloat(CastContract.KEY_VOLUME, volume)+ putBoolean(CastContract.KEY_HAS_NEXT, hasNext)+ putBoolean(CastContract.KEY_HAS_PREVIOUS, hasPrevious)+ }+}++/**+ * A press on the television's remote.+ *+ * [value] is the action's argument for the actions that take one - milliseconds for+ * [PlaybackAction.SeekTo], a multiplier for [PlaybackAction.SetSpeed], 0..1 for+ * [PlaybackAction.SetVolume] - and null for the rest. One nullable field rather than three+ * mostly-absent ones, which cannot then disagree.+ */+data class PlaybackCommand(+ val action: PlaybackAction,+ val value: Double? = null,+) {+ companion object {+ /**+ * Read one back, or null for an action this build does not know.+ *+ * Null rather than an exception on purpose: a newer Cast gaining a button must not crash an+ * app built against an older SDK, and ignoring the press is the correct behaviour anyway.+ */+ internal fun from(data: Bundle?): PlaybackCommand? {+ if (data == null) return null+ val action = PlaybackAction.of(data.getInt(CastContract.KEY_ACTION, -1)) ?: return null+ val value = if (data.containsKey(CastContract.KEY_ACTION_VALUE)) {+ data.getDouble(CastContract.KEY_ACTION_VALUE)+ } else {+ null+ }+ return PlaybackCommand(action, value)+ }+ }+}++/**+ * What the remote asked for.+ *+ * The [wire] value is what crosses the `Bundle`; the Kotlin names are free to change. An enum is not+ * put in the `Bundle` directly because a `Serializable` enum there is a class-loading problem waiting+ * for a client compiled against a different SDK version.+ */+enum class PlaybackAction(internal val wire: Int) {+ Play(CastContract.ACTION_PLAY),+ Pause(CastContract.ACTION_PAUSE),++ /**+ * Whichever of the two the player is not currently doing.+ *+ * Its own action rather than the TV resolving it from the last snapshot: that snapshot can be half+ * a second old, and two quick presses resolved against it would both send the same thing.+ */+ Toggle(CastContract.ACTION_TOGGLE),++ /** Absolute position, in milliseconds. */+ SeekTo(CastContract.ACTION_SEEK_TO),++ /** The app's own skip interval, so the two ends cannot disagree about how far it is. */+ SkipForward(CastContract.ACTION_SKIP_FORWARD),+ SkipBack(CastContract.ACTION_SKIP_BACK),++ Next(CastContract.ACTION_NEXT),+ Previous(CastContract.ACTION_PREVIOUS),++ /** A tempo multiplier. */+ SetSpeed(CastContract.ACTION_SET_SPEED),++ /**+ * A 0..1 level for *both* ends.+ *+ * The app is expected to move its own media volume to match, so the level survives the session+ * ending and local playback resumes where the television left it.+ */+ SetVolume(CastContract.ACTION_SET_VOLUME),+ ;++ internal companion object {+ fun of(wire: Int): PlaybackAction? = entries.firstOrNull { it.wire == wire }+ }+}
sdk/cast/src/test/java/com/vayunmathur/sdk/cast/CastContractTest.kt
diff --git a/sdk/cast/src/test/java/com/vayunmathur/sdk/cast/CastContractTest.kt b/sdk/cast/src/test/java/com/vayunmathur/sdk/cast/CastContractTest.ktindex a1c8bd8998..45e8e926ec 100644--- a/sdk/cast/src/test/java/com/vayunmathur/sdk/cast/CastContractTest.kt+++ b/sdk/cast/src/test/java/com/vayunmathur/sdk/cast/CastContractTest.kt@@ -3,6 +3,7 @@ package com.vayunmathur.sdk.cast import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse+import kotlin.test.assertNull import kotlin.test.assertTrue /**@@ -39,6 +40,8 @@ class CastContractTest { CastContract.MSG_CLOSE_SESSION, CastContract.MSG_SESSION_READY, CastContract.MSG_SESSION_ENDED,+ CastContract.MSG_PLAYBACK_STATE,+ CastContract.MSG_PLAYBACK_COMMAND, ) assertEquals(codes.size, codes.toSet().size, "two Messenger `what` codes are the same") }@@ -58,6 +61,16 @@ class CastContractTest { CastContract.KEY_GRANTED_FRAME_RATE, CastContract.KEY_RECEIVER_NAME, CastContract.KEY_END_REASON,+ CastContract.KEY_POSITION_MS,+ CastContract.KEY_DURATION_MS,+ CastContract.KEY_PLAYING,+ CastContract.KEY_BUFFERING,+ CastContract.KEY_SPEED,+ CastContract.KEY_VOLUME,+ CastContract.KEY_HAS_NEXT,+ CastContract.KEY_HAS_PREVIOUS,+ CastContract.KEY_ACTION,+ CastContract.KEY_ACTION_VALUE, ) assertEquals(keys.size, keys.toSet().size, "two Bundle keys are the same string") assertFalse(keys.any { it.isBlank() })@@ -90,6 +103,39 @@ class CastContractTest { assertEquals(2, CastContract.AUDIO_CHANNELS) } + // ---- transport controls ----++ @Test+ fun `every action has its own code, and the enum covers all of them`() {+ // The enum is the SDK's face and the ints are what cross the Bundle. A collision would make+ // two buttons on the remote do the same thing, and a missing entry would make one do nothing -+ // both only visible with a television in the room.+ val codes = listOf(+ CastContract.ACTION_PLAY,+ CastContract.ACTION_PAUSE,+ CastContract.ACTION_TOGGLE,+ CastContract.ACTION_SEEK_TO,+ CastContract.ACTION_SKIP_FORWARD,+ CastContract.ACTION_SKIP_BACK,+ CastContract.ACTION_NEXT,+ CastContract.ACTION_PREVIOUS,+ CastContract.ACTION_SET_SPEED,+ CastContract.ACTION_SET_VOLUME,+ )+ assertEquals(codes.size, codes.toSet().size, "two actions are the same int")+ assertEquals(codes.toSet(), PlaybackAction.entries.map { it.wire }.toSet())+ }++ @Test+ fun `an action code this build does not know reads as nothing rather than as the first one`() {+ // A newer Cast gaining a button must not crash an app built against this SDK, and must not be+ // mistaken for PLAY - which is what an ordinal-indexed lookup would have done.+ assertNull(PlaybackAction.of(-1))+ assertNull(PlaybackAction.of(999))+ assertEquals(PlaybackAction.Play, PlaybackAction.of(CastContract.ACTION_PLAY))+ assertEquals(PlaybackAction.SetVolume, PlaybackAction.of(CastContract.ACTION_SET_VOLUME))+ }+ // ---- the capability probe ---- @Test
version.txt
diff --git a/version.txt b/version.txtindex 0b107c3ceb..7171078c54 100644--- a/version.txt+++ b/version.txt@@ -1,2 +1,2 @@-20260816-v2.6.7+20260823+v2.6.8