Modern Apps git

← Modern-Apps.git

cast: don't ask a paused sender for key frames it cannot make

Commit
200215512260d8cc1905115aa3d6e56e88cacc21
Author
vayun-mathur <[email protected]>
When
2026-08-23 16:13 UTC (3 months ago)
Parents
99f63a0

Diff

cast/protocol/src/main/java/com/vayunmathur/cast/protocol/ReceiverSession.kt
diff --git a/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/ReceiverSession.kt b/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/ReceiverSession.ktindex 919bbfaf0c..7b2765406a 100644--- a/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/ReceiverSession.kt+++ b/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/ReceiverSession.kt@@ -111,10 +111,21 @@ class ReceiverSession(      * Called on a timer rather than per packet, because feedback is only useful at about the rate the      * sender can act on it. A PLI rides in the same datagram as the feedback block - RTCP is compound      * by design, and sending them separately doubles the chance of losing the one that mattered.+     *+     * **[senderIdle] suppresses the PLI, and without it a paused cast never recovers.** Every+     * key-frame condition here means "the sender is producing frames and they are not reaching me".+     * None of them is true of a sender that has deliberately stopped: once transport controls existed,+     * pausing on the television left [synchronised] false with no key frame coming, so a PLI went out+     * on *every* round - measured at twenty a second for fifteen seconds - and the sender answered each+     * one by reconfiguring an encoder that had no input. The picture did not come back when playback+     * resumed. A frozen frame is the correct thing to show while paused; asking for a new one is not.+     *+     * The stall and starve counters are left alone rather than reset, so a genuine gap that existed+     * before the pause is still remembered when playback resumes.      */-    fun feedback(): ByteArray {+    fun feedback(senderIdle: Boolean = false): ByteArray {         val nacks = assembler.missingPackets(after = checkpoint)-        val needsKeyFrame = !synchronised || isStalled() || isStarved()+        val needsKeyFrame = !senderIdle && (!synchronised || isStalled() || isStarved())         if (needsKeyFrame && synchronised) {             // The gap has outlived the sender's retransmit buffer, or nothing is completing at all.             // Nothing else will unblock either, so give up: resynchronise on the next key frame
cast/protocol/src/test/java/com/vayunmathur/cast/protocol/MediaRoundTripTest.kt
diff --git a/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/MediaRoundTripTest.kt b/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/MediaRoundTripTest.ktindex ac95df069e..da17f85439 100644--- a/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/MediaRoundTripTest.kt+++ b/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/MediaRoundTripTest.kt@@ -4,6 +4,7 @@ import kotlin.random.Random import kotlin.test.Test import kotlin.test.assertContentEquals import kotlin.test.assertEquals+import kotlin.test.assertFalse import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.test.assertTrue@@ -275,6 +276,46 @@ class MediaRoundTripTest {         assertTrue(receiver.onPacket(good.copyOf().also { it[1] = 96 }).isEmpty())     } +    @Test+    fun `a paused sender is not asked for key frames it cannot produce`() {+        // **The bug this guards against froze a 4K cast for good.** Pausing from the television means+        // the encoder legitimately produces nothing - but every key-frame condition here reads "frames+        // are being sent and are not reaching me", so an unsynchronised session asked for one on every+        // 50 ms round. Measured on hardware: twenty picture-loss indicators a second for fifteen+        // seconds, each answered by reconfiguring an encoder with no input, and no picture when+        // playback resumed. A frozen frame is the right thing to show while paused; asking for a fresh+        // one is not.+        val receiver = ReceiverSession(videoStream())++        // Nothing decoded yet, so the session is unsynchronised - which is exactly the state that used+        // to produce the storm.+        val whilePlaying = Rtcp.parse(+            receiver.feedback(senderIdle = false),+            RECEIVER_SSRC,+            SENDER_SSRC,+            FrameId(0),+        )+        assertTrue(assertNotNull(whilePlaying).pictureLoss, "a live sender should still be asked")++        val whilePaused = Rtcp.parse(+            receiver.feedback(senderIdle = true),+            RECEIVER_SSRC,+            SENDER_SSRC,+            FrameId(0),+        )+        assertFalse(assertNotNull(whilePaused).pictureLoss, "a paused sender must not be asked")++        // And the suppression is not a latch: resuming asks again, because the receiver still has no+        // key frame and now there is an encoder that can answer.+        val afterResume = Rtcp.parse(+            receiver.feedback(senderIdle = false),+            RECEIVER_SSRC,+            SENDER_SSRC,+            FrameId(0),+        )+        assertTrue(assertNotNull(afterResume).pictureLoss, "resuming must ask again")+    }+     private fun videoStream() = NegotiatedStream(         kind = StreamKind.Video,         senderSsrc = SENDER_SSRC,
cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorEngine.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorEngine.kt b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorEngine.ktindex 8ddc762061..c7c172ed0b 100644--- a/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorEngine.kt+++ b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorEngine.kt@@ -35,6 +35,15 @@ private const val FRAME_POLL_MS = 4L private const val RTCP_POLL_MS = 20L private const val STATS_LOG_INTERVAL_MS = 1_000L +/**+ * The most often the encoder may be asked for a key frame.+ *+ * Matches the receiver's own resync interval: it reports every 50 ms, so an unsynchronised session asks+ * twenty times a second, and every one of those is a `setParameters` call on a hardware encoder that+ * can produce at most one key frame per ask anyway.+ */+private const val KEY_FRAME_REQUEST_INTERVAL_MS = 500L+ /**  * How long a codec that needs its configuration sent out of band has to produce it, **measured from  * the encoder's first output rather than from `start()`.**@@ -163,6 +172,16 @@ class MirrorEngine(     private var feedbackPackets = 0L     private var unmatchedPackets = 0L +    /**+     * When a key frame was last actually asked of the encoder, and how many asks were folded into it.+     *+     * The count is logged rather than dropped silently: a run of thousands means the receiver is+     * unsynchronised and staying that way, which is a different fault from ordinary packet loss and+     * would otherwise be invisible now that the per-request log line is gone.+     */+    private var lastKeyFrameRequest = 0L+    private var coalescedKeyFrameRequests = 0L+     fun start(): Boolean {         val udp = CastUdpTransport(receiverHost, negotiation.udpPort)         udp.hexDump = hexDump@@ -335,8 +354,14 @@ class MirrorEngine(                     Log.i(                         TAG,                         "$summary feedback=$feedbackPackets unmatchedRtcp=$unmatchedPackets " +-                            "sendFailures=${udp.sendFailures}",+                            "sendFailures=${udp.sendFailures}" ++                            if (coalescedKeyFrameRequests > 0) {+                                " keyFrameAsks=$coalescedKeyFrameRequests coalesced"+                            } else {+                                ""+                            },                     )+                    coalescedKeyFrameRequests = 0                 }                 var packet = udp.receive()                 while (packet != null) {@@ -387,8 +412,21 @@ class MirrorEngine(             ) {                 // Either the receiver asked outright (PLI) or it has fallen further behind than the                 // retransmit buffer can repair. A key frame is the only way out of both.-                Log.i(TAG, "key frame requested (pli=${feedback.pictureLoss})")-                videoEncoder?.requestKeyFrame()+                //+                // **Coalesced, because a receiver can ask far faster than an encoder can answer.** The+                // receiver reports every 50 ms, so a session it considers unsynchronised produces+                // twenty of these a second - and each one is a `setParameters` on the encoder.+                // Measured: fifteen seconds of that while playback was paused left the encoder+                // unable to produce a picture even after frames started arriving again. One request+                // per interval is all an encoder can act on anyway; the rest are the same request.+                val now = System.currentTimeMillis()+                if (now - lastKeyFrameRequest >= KEY_FRAME_REQUEST_INTERVAL_MS) {+                    lastKeyFrameRequest = now+                    Log.i(TAG, "key frame requested (pli=${feedback.pictureLoss})")+                    videoEncoder?.requestKeyFrame()+                } else {+                    coalescedKeyFrameRequests+++                }             }             return         }
cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/MediaReceiver.kt
diff --git a/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/MediaReceiver.kt b/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/MediaReceiver.ktindex 21e462e261..f48fa997de 100644--- a/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/MediaReceiver.kt+++ b/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/MediaReceiver.kt@@ -107,11 +107,14 @@ class MediaReceiver(      * Sent even before anything has been decoded - that first report is a PLI, and it is what tells      * the sender to produce a key frame now rather than at its next scheduled one. Nothing goes out      * before the first datagram arrives, because until then there is no address to send it to.+     *+     * [senderIdle] is true when the phone has told us playback is paused, and suppresses the key-frame+     * request - see [ReceiverSession.feedback] for why a paused cast otherwise never recovers.      */-    fun sendFeedback() {+    fun sendFeedback(senderIdle: Boolean = false) {         val address = senderAddress ?: return         for (session in sessions.values) {-            val packet = session.feedback()+            val packet = session.feedback(senderIdle)             try {                 socket.send(DatagramPacket(packet, packet.size, address, senderPort))             } catch (e: Exception) {
cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/MirrorActivity.kt
diff --git a/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/MirrorActivity.kt b/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/MirrorActivity.ktindex d3851ea298..bfe9ffae18 100644--- a/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/MirrorActivity.kt+++ b/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/MirrorActivity.kt@@ -8,6 +8,7 @@ import android.view.SurfaceView import android.view.ViewGroup import android.widget.FrameLayout import androidx.activity.ComponentActivity+import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableLongStateOf@@ -77,9 +78,22 @@ class MirrorActivity : ComponentActivity(), SurfaceHolder.Callback {      * on the control channel and into an ExoPlayer that is simultaneously feeding a hardware encoder;      * holding a local preview and sending one `SeekTo` at the end is both kinder and what the user      * means by holding the button down.+     *+     * Held past the commit until the phone's own answer arrives - see [scrubCommittedAtMs].      */     private var scrubPreviewMs by mutableLongStateOf(NO_SCRUB) +    /**+     * When the last scrub was committed, so its preview can be held until the phone confirms.+     *+     * Dropping the preview the instant the seek went out made the bar jump backwards: snapshots arrive+     * twice a second, so for up to half a second the newest one still described the *pre-seek*+     * position, and the bar snapped back there before the next one pulled it forward. Keeping the+     * preview until a snapshot that postdates the commit arrives makes the bar move once, to where the+     * user put it.+     */+    private var scrubCommittedAtMs = 0L+     private var hideJob: Job? = null      override fun onCreate(savedInstanceState: Bundle?) {@@ -143,6 +157,15 @@ class MirrorActivity : ComponentActivity(), SurfaceHolder.Callback {             CastTvTheme {                 val state by ReceiverController.state.collectAsState()                 val playback = state.playback+                // Released in an effect rather than inline: writing state during composition is how a+                // recomposition loop starts.+                LaunchedEffect(playback?.receivedAtMs) {+                    val arrivedAt = playback?.receivedAtMs ?: return@LaunchedEffect+                    if (scrubCommittedAtMs != 0L && arrivedAt > scrubCommittedAtMs) {+                        scrubCommittedAtMs = 0L+                        scrubPreviewMs = NO_SCRUB+                    }+                }                 if (playback != null && overlayVisible) {                     TransportOverlay(                         snapshot = playback,@@ -246,14 +269,14 @@ class MirrorActivity : ComponentActivity(), SurfaceHolder.Callback {      private fun commitScrub() {         val target = scrubPreviewMs-        scrubPreviewMs = NO_SCRUB         if (target == NO_SCRUB) return+        // The preview is *kept*, and released by the composition above once a snapshot postdating this+        // moment arrives. A seek the phone refuses - which it does while its own slider is under a+        // thumb - is therefore corrected by the next heartbeat rather than left showing for ever.+        scrubCommittedAtMs = System.currentTimeMillis()         ReceiverController.send(             PlaybackCommand(PlaybackAction.SeekTo, value = target.toDouble()),         )-        // The preview is dropped here rather than held until the phone confirms: the next snapshot is-        // at most half a second away, and holding a stale preview would freeze the bar if the seek was-        // refused - which the phone does while its own slider is under a thumb.         revealOverlay()     } @@ -271,6 +294,7 @@ class MirrorActivity : ComponentActivity(), SurfaceHolder.Callback {         hideJob?.cancel()         hideJob = null         scrubPreviewMs = NO_SCRUB+        scrubCommittedAtMs = 0L         overlayVisible = false     } 
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 4c62163db3..cbeb361510 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@@ -738,7 +738,7 @@ object ReceiverController {                             rtpToMicros(frame.rtpTimestamp),                             frame.isKeyFrame,                         )-                        if (!queued && now - lastResync >= RESYNC_INTERVAL_MS) {+                        if (!queued && now - lastResync >= RESYNC_INTERVAL_MS && !senderIdle()) {                             // The session counted this frame as delivered, so its checkpoint has                             // moved past a frame the decoder never got: every delta frame behind it                             // now references something that does not exist. Only a key frame@@ -767,7 +767,7 @@ object ReceiverController {                 }                 if (now - lastFeedback >= FEEDBACK_INTERVAL_MS) {                     lastFeedback = now-                    media.sendFeedback()+                    media.sendFeedback(senderIdle = senderIdle())                 }                 if (now - lastStatsLog >= STATS_LOG_INTERVAL_MS) {                     lastStatsLog = now@@ -789,6 +789,17 @@ object ReceiverController {         }     } +    /**+     * Whether the phone has told us it is deliberately not producing frames.+     *+     * The one thing that distinguishes "paused" from "broken", and the pipeline had no way to know it+     * until the phone started reporting playback: a paused sender and a dead link look identical from+     * here - no frames arriving - and every recovery mechanism is built for the second. False for screen+     * mirroring, which never reports playback and can never be paused, so its behaviour is unchanged.+     */+    private fun senderIdle(): Boolean =+        _state.value.playback?.state?.let { !it.playing && !it.buffering } == true+     /**      * Stop the media loop.      *