Modern Apps git

← Modern-Apps.git

cast: route playback state to the TV and its commands back

Commit
3becf2f0c7fb96ffc68f90893eb54d59a77d9a58
Author
vayun-mathur <[email protected]>
When
2026-08-23 06:51 UTC (3 months ago)
Parents
b5d74c3

Diff

cast/src/main/java/com/vayunmathur/cast/platform/CastController.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/platform/CastController.kt b/cast/src/main/java/com/vayunmathur/cast/platform/CastController.ktindex 2a9fd492b6..5d3fa9ea1c 100644--- a/cast/src/main/java/com/vayunmathur/cast/platform/CastController.kt+++ b/cast/src/main/java/com/vayunmathur/cast/platform/CastController.kt@@ -25,6 +25,8 @@ import com.vayunmathur.cast.protocol.CodecNegotiation import com.vayunmathur.cast.protocol.CodecSelection import com.vayunmathur.cast.protocol.DecoderLimits import com.vayunmathur.cast.protocol.PROTOCOL_VERSION+import com.vayunmathur.cast.protocol.PlaybackCommand+import com.vayunmathur.cast.protocol.PlaybackState import com.vayunmathur.cast.protocol.StreamConstants import com.vayunmathur.cast.protocol.StreamingSession import com.vayunmathur.cast.protocol.VideoCodec@@ -167,6 +169,18 @@ object CastController {      */     var onContentSessionEnded: ((Int) -> Unit)? = null +    /**+     * Notified when the television's remote is pressed during an SDK session.+     *+     * Set and cleared by `ContentCastService` alongside [onContentSessionEnded], and for the same+     * reasons: one session, one callback, and a command has to reach the app once rather than be a+     * current value worth observing.+     *+     * Null during screen mirroring, which has no transport to control - and [startWatch] does not even+     * offer the dispatch in that case, so a stray command never reaches this far.+     */+    var onPlaybackCommand: ((PlaybackCommand) -> Unit)? = null+     /**      * The name of the app that last completed `CastPickerActivity`, resolved from its      * `callingPackage`.@@ -528,7 +542,7 @@ object CastController {         _sessionState.update {             it.copy(phase = ClientPhase.Streaming, negotiation = ready.negotiation)         }-        startWatch(appContext, activeClient, device, codec.codec)+        startWatch(appContext, activeClient, device, codec.codec, transportControls = true)         ContentSessionResult.Started(             surface = surface,             audioWriteEnd = newEngine.audioWriteEnd,@@ -546,15 +560,28 @@ object CastController {      * a request/response to do on it - a second reader would consume the `STREAM_READY` that      * negotiation is waiting for. Until this starts, a dead TV surfaces as a failed `configureStream`,      * which is just as prompt.+     *+     * [transportControls] is what gates the remote to app content. Screen mirroring has no transport+     * to control, so it is not merely that the overlay should not appear on the TV - there is nothing+     * a command could be applied to on this end either.      */     private fun startWatch(         appContext: Context,         activeClient: MirrorClient,         device: CastDevice,         codec: VideoCodec,+        transportControls: Boolean = false,     ) {         watchJob = scope.launch {-            val reason = activeClient.awaitEnd()+            // Read late rather than captured: `ContentCastService` registers its callback only after+            // `startContentSession` returns, which is after this job has already started - the same+            // ordering `onContentSessionEnded` has.+            val dispatch: ((PlaybackCommand) -> Unit)? = if (transportControls) {+                { command -> onPlaybackCommand?.invoke(command) }+            } else {+                null+            }+            val reason = activeClient.awaitEnd(dispatch)             // **Another path may already own this teardown.** Closing the socket is what unblocks the             // read above, and [endCodecConfigFailure] closes it deliberately - so a return from             // `awaitEnd` is not proof that the TV ended the session. Whoever cancelled this job is@@ -743,6 +770,21 @@ object CastController {         scope.launch { mutex.withLock { activeClient.sendCodecConfig(csd) } }     } +    /**+     * Put a playback snapshot on the control channel, so the TV can draw a seek bar.+     *+     * Under [mutex] for exactly the reason [sendCodecConfig] is, with one more writer to serialise+     * against than before: the encoder loop, the RTCP loop and now a twice-a-second heartbeat all write+     * to the one socket.+     *+     * Silently does nothing with no session, rather than reporting it. The caller is a poll loop that+     * cannot know precisely when the session ended, and there is nothing for it to do about the answer.+     */+    fun reportPlaybackState(state: PlaybackState) {+        val activeClient = client ?: return+        scope.launch { mutex.withLock { activeClient.sendPlaybackState(state) } }+    }+     private fun stopEngine() {         engine?.stop()         engine = null@@ -758,6 +800,7 @@ object CastController {     private fun endContentSession(reason: Int) {         val notify = onContentSessionEnded ?: return         onContentSessionEnded = null+        onPlaybackCommand = null         notify(reason)     } 
cast/src/main/java/com/vayunmathur/cast/platform/MirrorClient.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/platform/MirrorClient.kt b/cast/src/main/java/com/vayunmathur/cast/platform/MirrorClient.ktindex 1390320514..4e5ad3e27a 100644--- a/cast/src/main/java/com/vayunmathur/cast/platform/MirrorClient.kt+++ b/cast/src/main/java/com/vayunmathur/cast/platform/MirrorClient.kt@@ -15,6 +15,8 @@ import com.vayunmathur.cast.protocol.PairFailed import com.vayunmathur.cast.protocol.PairOk import com.vayunmathur.cast.protocol.PairProof import com.vayunmathur.cast.protocol.PairRequired+import com.vayunmathur.cast.protocol.PlaybackCommand+import com.vayunmathur.cast.protocol.PlaybackState import com.vayunmathur.cast.protocol.ProtocolBase64 import com.vayunmathur.cast.protocol.SealedSecret import com.vayunmathur.cast.protocol.SecretSealing@@ -266,7 +268,22 @@ class MirrorClient(     }      /**-     * Wait for the TV to say goodbye, or for the socket to die.+     * Put a playback snapshot on the control channel, for the TV's seek bar.+     *+     * Follows [sendCodecConfig] in being non-throwing, and for the same kind of reason: this is called+     * from a poll loop, so a failure would recur every tick and there is nothing useful to do about+     * one. A socket that has actually died is [awaitEnd]'s business and it will say so.+     *+     * Not logged per send. Two of these a second would bury everything else in the log, which is the+     * opposite of what the logging in this class is for.+     */+    fun sendPlaybackState(state: PlaybackState) {+        runCatching { socket.send(state) }+            .onFailure { Log.w(TAG, "could not send the playback state", it) }+    }++    /**+     * Wait for the TV to say goodbye, or for the socket to die, acting on anything else it sends.      *      * Held open for the whole session so that a TV going away is noticed at once, rather than only      * when UDP starts failing - a control channel nobody reads is a control channel that cannot report@@ -275,14 +292,34 @@ class MirrorClient(      * Returns the `BYE` reason, or null when the socket died without one. The reason is carried back      * rather than only logged because one of them - [ByeReason.MISSING_CODEC_CONFIG] - is a decision      * the caller has to act on, not a note for a human.+     *+     * **A dispatch loop rather than a drain.** This used to discard everything that was not a `Bye`,+     * which was right while the TV had nothing else to say. It has a remote now, and its+     * [PlaybackCommand]s arrive on this same socket - and cannot arrive anywhere else, because there+     * is one socket with one read position and this is already the only reader.+     *+     * [onCommand] is null for screen mirroring, which has no transport to control. A command that+     * turns up anyway is logged and dropped rather than acted on.      */-    fun awaitEnd(): String? {+    fun awaitEnd(onCommand: ((PlaybackCommand) -> Unit)? = null): String? {         while (true) {             val next = socket.receive() ?: return null-            val message = next.message-            if (message is Bye) {-                Log.i(TAG, "'$receiverName' said goodbye: ${message.reason.ifBlank { "no reason" }}")-                return message.reason+            when (val message = next.message) {+                is Bye -> {+                    Log.i(TAG, "'$receiverName' said goodbye: ${message.reason.ifBlank { "no reason" }}")+                    return message.reason+                }+                is PlaybackCommand -> {+                    val argument = message.value?.let { " $it" }.orEmpty()+                    if (onCommand == null) {+                        Log.w(TAG, "'$receiverName' asked for ${message.action}$argument, " ++                            "but there is no transport to control")+                    } else {+                        Log.i(TAG, "'$receiverName' asked for ${message.action}$argument")+                        onCommand(message)+                    }+                }+                else -> {}             }         }     }
cast/src/main/java/com/vayunmathur/cast/service/ContentCastService.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/service/ContentCastService.kt b/cast/src/main/java/com/vayunmathur/cast/service/ContentCastService.ktindex 00ebfe4039..6e0fde31f4 100644--- a/cast/src/main/java/com/vayunmathur/cast/service/ContentCastService.kt+++ b/cast/src/main/java/com/vayunmathur/cast/service/ContentCastService.kt@@ -13,6 +13,9 @@ import android.os.RemoteException import android.util.Log import com.vayunmathur.cast.platform.CastController import com.vayunmathur.cast.platform.ContentSessionResult+import com.vayunmathur.cast.protocol.PlaybackAction+import com.vayunmathur.cast.protocol.PlaybackCommand+import com.vayunmathur.cast.protocol.PlaybackState import com.vayunmathur.sdk.cast.CastContract import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers@@ -45,7 +48,7 @@ class ContentCastService : Service() {      private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main) -    /** Where [CastContract.MSG_SESSION_READY] and `MSG_SESSION_ENDED` go. */+    /** Where `MSG_SESSION_READY`, `MSG_SESSION_ENDED` and `MSG_PLAYBACK_COMMAND` go. */     private var client: Messenger? = null      /** True between a successful open and the session ending, so nothing is reported twice. */@@ -62,6 +65,14 @@ class ContentCastService : Service() {                     closeSession(CastContract.REASON_CLIENT_CLOSED, notify = true)                     true                 }+                CastContract.MSG_PLAYBACK_STATE -> {+                    // Dropped rather than queued with no session: there is no TV to draw it on, and a+                    // client is free to keep polling for a tick or two after the session ended.+                    if (sessionOpen) {+                        msg.data?.let { CastController.reportPlaybackState(it.toPlaybackState()) }+                    }+                    true+                }                 else -> false             }         },@@ -116,6 +127,11 @@ class ContentCastService : Service() {                     CastController.onContentSessionEnded = { reason ->                         scope.launch { closeSession(reason, notify = true) }                     }+                    CastController.onPlaybackCommand = { command ->+                        // Hopped to the main thread because `awaitEnd` runs on IO and the client's+                        // callback drives a player.+                        scope.launch { send(playbackCommand(command)) }+                    }                     sendReady(result)                 }             }@@ -152,6 +168,7 @@ class ContentCastService : Service() {         if (!sessionOpen) return         sessionOpen = false         CastController.onContentSessionEnded = null+        CastController.onPlaybackCommand = null         // Back to a paired-but-idle TV rather than a dropped session: the pairing is per device and         // worth keeping, and the user may well cast again straight away.         CastController.stopMirroring(this)@@ -178,3 +195,55 @@ class ContentCastService : Service() {         runCatching { pfd?.close() }     } }++/**+ * The `Bundle` a client sent, as the message the TV understands.+ *+ * **This is the whole of the deliberate duplication between `:sdk:cast` and `:cast:protocol`, and it+ * lives here because this is the only place that depends on both.** `:sdk:cast` is what every casting+ * app compiles against, so it must not pull in the wire format, the crypto or the packetiser; the+ * protocol module is what the TV shares. Two definitions and one translation is the price, and this+ * file is where it is paid.+ *+ * Defaults rather than refusals for the optional fields: a client that never sets a speed is playing+ * at 1x, and a TV drawing 0x would be wrong in a way nothing would explain.+ */+private fun Bundle.toPlaybackState(): PlaybackState = PlaybackState(+    positionMs = getLong(CastContract.KEY_POSITION_MS),+    durationMs = getLong(CastContract.KEY_DURATION_MS),+    playing = getBoolean(CastContract.KEY_PLAYING),+    buffering = getBoolean(CastContract.KEY_BUFFERING),+    speed = getFloat(CastContract.KEY_SPEED, 1f),+    volume = getFloat(CastContract.KEY_VOLUME, 1f),+    hasNext = getBoolean(CastContract.KEY_HAS_NEXT),+    hasPrevious = getBoolean(CastContract.KEY_HAS_PREVIOUS),+)++/** The command the TV sent, as the `Message` the SDK reads. See [Bundle.toPlaybackState]. */+private fun playbackCommand(command: PlaybackCommand): Message =+    Message.obtain(null, CastContract.MSG_PLAYBACK_COMMAND).apply {+        data = Bundle().apply {+            putInt(CastContract.KEY_ACTION, command.action.sdkAction)+            command.value?.let { putDouble(CastContract.KEY_ACTION_VALUE, it) }+        }+    }++/**+ * The SDK's int for a protocol action.+ *+ * Exhaustive with no else branch on purpose: adding an action to the protocol enum should fail to+ * compile here rather than silently arrive at the client as whatever the fallback was.+ */+private val PlaybackAction.sdkAction: Int+    get() = when (this) {+        PlaybackAction.Play -> CastContract.ACTION_PLAY+        PlaybackAction.Pause -> CastContract.ACTION_PAUSE+        PlaybackAction.Toggle -> CastContract.ACTION_TOGGLE+        PlaybackAction.SeekTo -> CastContract.ACTION_SEEK_TO+        PlaybackAction.SkipForward -> CastContract.ACTION_SKIP_FORWARD+        PlaybackAction.SkipBack -> CastContract.ACTION_SKIP_BACK+        PlaybackAction.Next -> CastContract.ACTION_NEXT+        PlaybackAction.Previous -> CastContract.ACTION_PREVIOUS+        PlaybackAction.SetSpeed -> CastContract.ACTION_SET_SPEED+        PlaybackAction.SetVolume -> CastContract.ACTION_SET_VOLUME+    }