Modern Apps git

← Modern-Apps.git

cast: re-casting after a stop no longer races the surviving socket reader

Commit
dfece183d6a86698a4a8fd7533fa77399e9ecbfe
Author
Vayun Mathur <[email protected]>
When
2026-12-01 04:42 UTC (5 days ago)
Parents
047d7f9
Stream stop deliberately keeps the control channel and the
session watch (awaitEnd) alive. The next session's
configureStream/openContentSession then did their own
socket.receive() โ€” a second concurrent reader on the same
unsynchronized stream. awaitEnd had no armed hand-off for
those replies: STREAM_READY hit its dropped branch,
CONTENT_READY hit else -> {}, and startWatch would launch a
second watcher on restart. The negotiation returned
StreamRefused ('the TV did not answer') while the TV had
answered on time, and the whole connection then died at the
idle read timeout. The single-reader invariant was enforced
only for desktop reconfiguration (pendingStreamReady) โ€” the
one path someone had already raced.

configureStream/openContentSession now arm a pending reply
before sending and receive it through awaitEnd when a watch
is active (direct read only pre-watch), via a shared
streamReadyOutcome(); startWatch records the surviving
watch's client/device/codec and never launches a second
reader. Two regression tests park a watch and negotiate on
the same client against a real-socket fake TV โ€” both failed
pre-fix, reproducing the refusal. Verified: :cast,
:cast:tv and :cast:protocol test suites pass (226/178/149;
one timing-flaky engine test passed isolated and on re-run);
detekt passes, ktlint is pre-existing backlog, and the one
lint error is pre-existing on an untouched file.

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 457f2b2583..297b9606c3 100644--- a/cast/src/main/java/com/vayunmathur/cast/platform/CastController.kt+++ b/cast/src/main/java/com/vayunmathur/cast/platform/CastController.kt@@ -57,6 +57,20 @@ object CastController {     internal var client: MirrorClient? = null     internal var watchJob: Job? = null +    /** The client [watchJob] is reading for, so a restarted session does not spawn a second reader. */+    internal var watchClient: MirrorClient? = null++    /** Device/codec of the latest `startWatch`, read by the surviving watcher when it ends. */+    internal var watchDevice: CastDevice? = null+    internal var watchCodec: VideoCodec? = null++    /**+     * Whether the running watch forwards transport commands/state, updated by every+     * `startWatch` call. Read at dispatch time, because the single surviving watcher may+     * have been launched by a session with a different answer than the current one.+     */+    internal var watchTransportControls: Boolean = false+     /**      * The keep-alive on a served session's control channel.      *@@ -327,6 +341,10 @@ object CastController {         socket?.close()         mutex.withLock {             watchJob = null+            watchClient = null+            watchDevice = null+            watchCodec = null+            watchTransportControls = false             socket = null             client = null             isConnectingMutable.value = false
cast/src/main/java/com/vayunmathur/cast/platform/CastSessionWatch.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/platform/CastSessionWatch.kt b/cast/src/main/java/com/vayunmathur/cast/platform/CastSessionWatch.ktindex 6d83f68e9b..fbbcc8bad5 100644--- a/cast/src/main/java/com/vayunmathur/cast/platform/CastSessionWatch.kt+++ b/cast/src/main/java/com/vayunmathur/cast/platform/CastSessionWatch.kt@@ -49,20 +49,28 @@ internal fun CastController.startWatch(      */     keepAlive: Boolean = false, ) {+    // Recorded even when the watcher below is reused: a session restarted on this channel+    // may differ from the one that launched the watcher in codec and in transport gating.+    watchTransportControls = transportControls+    watchCodec = codec+    watchDevice = device     if (keepAlive) startKeepAlive(activeClient)+    // One reader per socket, ever. A session restarted after `stopMirroring` kept this+    // channel deliberately, so its watch is still parked in `awaitEnd`; launching a second+    // one would put two readers on one framed stream and replies would go to whichever+    // happened to read them. The survivor reads the fields above at dispatch time.+    if (watchJob?.isActive == true && watchClient == activeClient) return+    watchClient = activeClient     watchJob = scope.launch {         // 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+        // ordering `onContentSessionEnded` has. The transport gate is read the same way, in+        // case this watcher outlived the session that launched it into a restarted one.+        val dispatch: (PlaybackCommand) -> Unit = { command ->+            if (watchTransportControls) onPlaybackCommand?.invoke(command)         }-        val states: ((PlaybackState) -> Unit)? = if (transportControls) {-            { state -> onTvPlaybackState?.invoke(state) }-        } else {-            null+        val states: (PlaybackState) -> Unit = { state ->+            if (watchTransportControls) onTvPlaybackState?.invoke(state)         }         val reason = activeClient.awaitEnd(dispatch, states)         // **Another path may already own this teardown.** Closing the socket is what unblocks the@@ -71,19 +79,22 @@ internal fun CastController.startWatch(         // publishing its own failure, and a second teardown here would clear it.         if (!isActive) return@launch         Log.status(TAG, "the control channel closed")-        val receiverId = activeClient.receiverId ?: device.id+        val endedDevice = watchDevice ?: device+        val endedCodec = watchCodec ?: codec+        val receiverId = activeClient.receiverId ?: endedDevice.id         // Read before the teardown clears it, so a failure already on screen survives a socket that         // then closed without a reason of its own - otherwise the message a user has to read would         // be replaced by a blank idle state.         val standing = failureMutable.value         // Cleared first: teardown cancels watchJob, and this coroutine *is* watchJob.         watchJob = null+        watchClient = null         teardown()         // Published *after* the teardown, which resets the phase and clears the failure - the         // order matters, and setting either first would only have it wiped.-        val message = if (reason == ByeReason.MISSING_CODEC_CONFIG && codec != null) {-            Log.status(TAG, "'${device.friendlyName}' never got ${codec.label}'s codec config")-            MirrorPreferences.demoteCodec(appContext, receiverId, codec)+        val message = if (reason == ByeReason.MISSING_CODEC_CONFIG && endedCodec != null) {+            Log.status(TAG, "'${endedDevice.friendlyName}' never got ${endedCodec.label}'s codec config")+            MirrorPreferences.demoteCodec(appContext, receiverId, endedCodec)             appContext.getString(R.string.cast_mirror_codec_config_failed)         } else {             standing@@ -106,10 +117,9 @@ internal fun CastController.startWatch(  * down a minute in while a track was still being encoded.  *  * **Stopped when the session is, even though `ContentEnded` hands the channel back rather than- * closing it.** Keeping it running would hold that channel open indefinitely - and a second- * content session on a channel whose [watchJob] is still parked in a blocking read has two readers- * of one socket, so the reply to its `CONTENT_SESSION` goes to the wrong one. Letting the idle- * channel lapse at the read timeout is what bounds that window to a minute rather than for ever.+ * closing it.** Keeping it running would hold that channel open indefinitely. A second session+ * on this channel is safe regardless: negotiations hand their replies through the still-parked+ * [MirrorClient.awaitEnd] (see `MirrorClient`) and [startWatch] never launches a second reader.  *  * Under [CastController.mutex] like every other writer, because this is one more thread writing  * one socket.
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 3fb486ad48..bb8d9fa473 100644--- a/cast/src/main/java/com/vayunmathur/cast/platform/MirrorClient.kt+++ b/cast/src/main/java/com/vayunmathur/cast/platform/MirrorClient.kt@@ -37,6 +37,7 @@ import com.vayunmathur.cast.protocol.VideoCodec import com.vayunmathur.cast.protocol.VideoCodecConfig import java.security.SecureRandom import kotlinx.coroutines.CompletableDeferred+import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withTimeoutOrNull  private const val TAG = "MirrorClient"@@ -133,6 +134,22 @@ class MirrorClient(     @Volatile     private var pendingStreamReady: CompletableDeferred<StreamReady>? = null +    /** A content negotiation waiting for its `CONTENT_READY`, handed over like [pendingStreamReady]. */+    @Volatile+    private var pendingContentReady: CompletableDeferred<ContentReady>? = null++    /**+     * True while [awaitEnd] owns this socket's read position.+     *+     * Negotiations that arrive in that window cannot read the socket themselves - two readers+     * on one framed stream race for the same bytes and the watcher drops a reply it was not+     * armed for - so they arm a pending hand-off above and let [awaitEnd] complete it. That is+     * the second-session case: the channel (and its watch) deliberately survives a stopped+     * cast so the next one can start without re-picking the TV.+     */+    @Volatile+    private var watchActive: Boolean = false+     /**      * The transcript, frozen after `SEALED_SECRET`.      *@@ -338,14 +355,40 @@ class MirrorClient(         // Null means the channel went away between choosing a codec and configuring it, which is         // exactly what a teardown racing a fresh session does. Refused rather than thrown: the caller         // has a failure branch for this and had nothing to catch an exception with.+        if (watchActive) {+            // The watch owns the read position (a previous session on this same channel, kept+            // alive so this one did not have to re-pair): the reply is handed over, exactly as+            // in [reconfigureStream], instead of raced for by a second reader.+            val waiter = CompletableDeferred<StreamReady>()+            pendingStreamReady = waiter+            if (socket.send(config) == null) {+                pendingStreamReady = null+                return HandshakeOutcome.Failed(ClientFailure.StreamRefused)+            }+            val watched = runBlocking {+                withTimeoutOrNull(RECONFIGURE_TIMEOUT_MS) { waiter.await() }+            }+            pendingStreamReady = null+            return watched?.let { streamReadyOutcome(it, config, sessionKeys, videoCodec) }+                ?: HandshakeOutcome.Failed(ClientFailure.StreamRefused)+        }         socket.send(config) ?: return HandshakeOutcome.Failed(ClientFailure.StreamRefused)         val ready = socket.receive()?.message as? StreamReady             ?: return HandshakeOutcome.Failed(ClientFailure.StreamRefused)+        return streamReadyOutcome(ready, config, sessionKeys, videoCodec)+    }++    private fun streamReadyOutcome(+        ready: StreamReady,+        config: StreamConfig,+        sessionKeys: SessionKeys,+        videoCodec: VideoCodec,+    ): HandshakeOutcome {         if (ready.udpPort !in MIN_UDP_PORT..MAX_UDP_PORT) {             Log.status(TAG, "the TV named udp port ${ready.udpPort}")             return HandshakeOutcome.Failed(ClientFailure.StreamRefused)         }-        Log.status(TAG, "streaming ${videoCodec.label} ${width}x$height to udp ${ready.udpPort}")+        Log.status(TAG, "streaming ${videoCodec.label} ${config.width}x${config.height} to udp ${ready.udpPort}")         return HandshakeOutcome.Ready(Negotiation.of(config, ready, sessionKeys))     } @@ -428,6 +471,14 @@ class MirrorClient(         video: Boolean,         appLabel: String,     ): ContentOutcome {+        // Armed before the send when watched, or a television that answers immediately would+        // arrive at an unarmed watcher and be dropped - the same ordering [reconfigureStream]+        // already depends on.+        val waiter = if (watchActive) CompletableDeferred<ContentReady>().also {+            pendingContentReady = it+        } else {+            null+        }         val offered = socket.send(             ContentSession(                 host = host,@@ -438,9 +489,23 @@ class MirrorClient(                 appLabel = appLabel,             ),         )-        if (offered == null) return ContentOutcome.Refused("the control channel had already closed")-        val ready = socket.receive()?.message as? ContentReady-            ?: return ContentOutcome.Refused("the TV did not answer")+        if (offered == null) {+            pendingContentReady = null+            return ContentOutcome.Refused("the control channel had already closed")+        }+        val ready = if (waiter != null) {+            // Same hand-off as a watched [configureStream]: [awaitEnd] is the socket's only+            // reader, so the answer arrives through it rather than through a competing read+            // that would drop or corrupt the framed reply.+            val answered = runBlocking {+                withTimeoutOrNull(RECONFIGURE_TIMEOUT_MS) { waiter.await() }+            }+            pendingContentReady = null+            answered ?: return ContentOutcome.Refused("the TV did not answer")+        } else {+            socket.receive()?.message as? ContentReady+                ?: return ContentOutcome.Refused("the TV did not answer")+        }         if (!ready.accepted) {             Log.status(TAG, "the TV refused a content session: ${ready.detail}")             return ContentOutcome.Refused(ready.detail)@@ -575,6 +640,18 @@ class MirrorClient(     fun awaitEnd(         onCommand: ((PlaybackCommand) -> Unit)? = null,         onState: ((PlaybackState) -> Unit)? = null,+    ): String? {+        watchActive = true+        try {+            return awaitEndLoop(onCommand, onState)+        } finally {+            watchActive = false+        }+    }++    private fun awaitEndLoop(+        onCommand: ((PlaybackCommand) -> Unit)?,+        onState: ((PlaybackState) -> Unit)?,     ): String? {         while (true) {             val next = socket.receive() ?: return null@@ -611,6 +688,17 @@ class MirrorClient(                         waiter.complete(message)                     }                 }+                // The same hand-off for a second content session on this channel: a reply read+                // here is a reply nobody else can read, so it goes to whoever negotiated.+                is ContentReady -> {+                    val waiter = pendingContentReady+                    if (waiter == null) {+                        Log.status(TAG, "'$receiverName' sent CONTENT_READY with nothing waiting for it")+                    } else {+                        pendingContentReady = null+                        waiter.complete(message)+                    }+                }                 else -> {}             }         }
cast/src/test/java/com/vayunmathur/cast/platform/MirrorClientTest.kt
diff --git a/cast/src/test/java/com/vayunmathur/cast/platform/MirrorClientTest.kt b/cast/src/test/java/com/vayunmathur/cast/platform/MirrorClientTest.ktindex 090428199c..20ec723a61 100644--- a/cast/src/test/java/com/vayunmathur/cast/platform/MirrorClientTest.kt+++ b/cast/src/test/java/com/vayunmathur/cast/platform/MirrorClientTest.kt@@ -265,6 +265,50 @@ class MirrorClientTest {         }     } +    @Test+    fun `configure stream hands ready through awaitEnd when the watch is already running`() = runBlocking {+        val tv = FakeTv()+        try {+            val client = pairedClient(tv)+            val watcher = async(kotlinx.coroutines.Dispatchers.IO) { client.awaitEnd() }+            Thread.sleep(200) // let awaitEnd become the socket reader+            // A second session on the same channel (cast again after stopping, without+            // disconnecting) negotiates while awaitEnd owns the read position: the reply+            // has to be handed over, not raced for or dropped by the watcher's else branch.+            val ready = client.configureStream(+                1280, 720, 30f, 4_000_000, VideoCodec.Hevc, audio = true, video = true,+            ) as HandshakeOutcome.Ready+            assertEquals(45_678, ready.negotiation.udpPort)+            client.sayGoodbye("bye-now")+            tv.close()+            assertEquals(null, watcher.await())+            Unit+        } finally {+            tv.close()+        }+    }++    @Test+    fun `content session hands ready through awaitEnd when the watch is already running`() = runBlocking {+        val tv = FakeTv()+        try {+            val client = pairedClient(tv)+            val watcher = async(kotlinx.coroutines.Dispatchers.IO) { client.awaitEnd() }+            Thread.sleep(200) // let awaitEnd become the socket reader+            val content = client.openContentSession(+                host = "127.0.0.1", port = 8443,+                certificateFingerprint = ByteArray(32) { 1 }, token = "tok", video = false, appLabel = "Music",+            )+            assertEquals(ContentOutcome.Accepted, content)+            client.sayGoodbye("bye-now")+            tv.close()+            assertEquals(null, watcher.await())+            Unit+        } finally {+            tv.close()+        }+    }+     @Test     fun `reconfigure hands stream ready through awaitEnd`() = runBlocking {         val tv = FakeTv()