Modern Apps git

← Modern-Apps.git

cast: fix mirroring lifecycle races and projection leaks

Commit
7b9a05a949751b9a7e57813a635f6d9d75c47023
Author
vayun-mathur <[email protected]>
When
2026-08-21 07:03 UTC (3 months ago)
Parents
8452e8c

Diff

cast/src/main/java/com/vayunmathur/cast/network/CastUdpTransport.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/network/CastUdpTransport.kt b/cast/src/main/java/com/vayunmathur/cast/network/CastUdpTransport.ktindex 4f622b652b..021699a6ec 100644--- a/cast/src/main/java/com/vayunmathur/cast/network/CastUdpTransport.kt+++ b/cast/src/main/java/com/vayunmathur/cast/network/CastUdpTransport.kt@@ -43,8 +43,10 @@ class CastUdpTransport(private val host: String, private val port: Int) {         val active = channel ?: return false         if (hexDump) Log.i(TAG, "-> ${packet.size}B ${packet.toHexPreview()}")         return try {-            active.write(ByteBuffer.wrap(packet))-            true+            // A non-blocking write can accept fewer bytes than offered when the send buffer is+            // full, which for a datagram socket means the packet did not go. Reporting it as sent+            // would inflate the sender report and skew the receiver's loss estimate.+            active.write(ByteBuffer.wrap(packet)) == packet.size         } catch (e: Exception) {             Log.w(TAG, "udp send failed", e)             false
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 1f0ef9da76..5c8604769b 100644--- a/cast/src/main/java/com/vayunmathur/cast/platform/CastController.kt+++ b/cast/src/main/java/com/vayunmathur/cast/platform/CastController.kt@@ -229,19 +229,31 @@ object CastController {             val failure = streamingSession.onAnswer(answer)             if (failure != null) {                 Log.w(TAG, "the receiver would not agree a stream: $failure")-                _mirrorPhase.value = MirrorPhase.Failed-                _failure.value = context.getString(-                    when (failure) {-                        is NegotiationFailure.NoStreams -> R.string.cast_mirror_no_streams-                        else -> R.string.cast_mirror_negotiation_failed-                    },+                abandonMirroring(+                    context,+                    projection,+                    context.getString(+                        when (failure) {+                            is NegotiationFailure.NoStreams -> R.string.cast_mirror_no_streams+                            else -> R.string.cast_mirror_negotiation_failed+                        },+                    ),                 )-                projection.stop()-                CastService.stopMirroring(context)                 return@launch             }-            val negotiation = streamingSession.negotiation ?: return@launch-            val started = MirrorEngine(+            val negotiation = streamingSession.negotiation+            if (negotiation == null) {+                // onAnswer reported no failure, so this cannot happen - but leaving a live+                // projection behind if it ever did would be a camera-light-style bug.+                Log.w(TAG, "an accepted answer produced no negotiation")+                abandonMirroring(+                    context,+                    projection,+                    context.getString(R.string.cast_mirror_negotiation_failed),+                )+                return@launch+            }+            val newEngine = MirrorEngine(                 context = context,                 projection = projection,                 receiverHost = host,@@ -249,11 +261,28 @@ object CastController {                 session = streamingSession,                 onDegraded = { _degradation.value = it },                 onStopped = { reason -> onEngineStopped(context, reason) },-            ).also { engine = it }.start()-            _mirrorPhase.value = if (started) MirrorPhase.Mirroring else MirrorPhase.Failed+            )+            engine = newEngine+            if (newEngine.start()) {+                _mirrorPhase.value = MirrorPhase.Mirroring+            } else {+                // start() already called onStopped, which set the message and the phase; all that+                // is left is to make sure nothing keeps holding the screen.+                engine = null+                runCatching { projection.stop() }+            }         }     } +    /** Give up on mirroring, and make sure the screen stops being captured. */+    private fun abandonMirroring(context: Context, projection: MediaProjection, message: String) {+        _mirrorPhase.value = MirrorPhase.Failed+        _failure.value = message+        streaming = null+        runCatching { projection.stop() }+        CastService.stopMirroring(context)+    }+     private fun onEngineStopped(context: Context, reason: MirrorStopReason) {         _failure.value = context.getString(             when (reason) {
cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorConsentActivity.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorConsentActivity.kt b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorConsentActivity.ktindex 3536cee1a1..740aad1e33 100644--- a/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorConsentActivity.kt+++ b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorConsentActivity.kt@@ -69,10 +69,12 @@ class MirrorConsentActivity : ComponentActivity() {          * An intent that starts the consent flow.          *          * `NEW_TASK` because the callers are a tile and a notification, neither of which has a task-         * of its own to launch into.+         * of its own. Deliberately **not** `CLEAR_TASK`: this activity has no `taskAffinity` of its+         * own, so it lands in the app's task and clearing it would finish `MainActivity` - which is+         * exactly where the user is standing when they press the in-app button.          */         fun intent(context: Context): Intent =             Intent(context, MirrorConsentActivity::class.java)-                .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)+                .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)     } }
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 9c9451e936..942345e754 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@@ -14,9 +14,12 @@ import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.cancel import kotlinx.coroutines.delay import kotlinx.coroutines.isActive import kotlinx.coroutines.launch+import kotlinx.coroutines.runBlocking+import java.util.concurrent.ConcurrentHashMap  private const val TAG = "MirrorEngine" @@ -64,8 +67,13 @@ class MirrorEngine(      private val appContext: Context = context.applicationContext -    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)-    private val senders = mutableMapOf<StreamKind, StreamSender>()+    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)++    /**+     * Concurrent because the RTCP loop iterates it while [stop] clears it, and the encoder loops+     * populate it during [start].+     */+    private val senders = ConcurrentHashMap<StreamKind, StreamSender>()      private var videoJob: Job? = null     private var audioJob: Job? = null@@ -178,13 +186,18 @@ class MirrorEngine(                     lastReport = now                     for ((kind, sender) in senders) {                         val stream = negotiation.streams.firstOrNull { it.kind == kind } ?: continue+                        val stats = sender.stats+                        // Nothing has been sent yet, so there is no clock mapping to report.+                        if (stats.lastSentAtMillis == 0L) continue                         udp.send(                             CastRtcp.senderReport(                                 senderSsrc = stream.senderSsrc,-                                ntpTimestamp = ntpTimestamp(now),-                                rtpTimestamp = sender.stats.lastRtpTimestamp,-                                packetCount = sender.stats.packets,-                                octetCount = sender.stats.octets,+                                // Paired with the RTP timestamp captured at the same instant, not+                                // with the current clock.+                                ntpTimestamp = ntpTimestamp(stats.lastSentAtMillis),+                                rtpTimestamp = stats.lastRtpTimestamp,+                                packetCount = stats.packets,+                                octetCount = stats.octets,                             ),                         )                     }@@ -224,12 +237,28 @@ class MirrorEngine(         }     } +    /**+     * Stop everything, in an order that does not race.+     *+     * The loops are cancelled **and joined** before anything they touch is released: they call into+     * `MediaCodec` and `AudioRecord` directly, and releasing either underneath a thread parked+     * inside it is a native-side crash rather than a catchable exception. `runBlocking` is+     * acceptable here because the loops only ever park for a few milliseconds.+     */     fun stop() {-        videoJob?.cancel()-        audioJob?.cancel()-        rtcpJob?.cancel()-        // The display goes first: it is what is writing into the encoder's surface, and releasing-        // the encoder underneath a live VirtualDisplay is what makes the codec throw on the way out.+        val jobs = listOfNotNull(videoJob, audioJob, rtcpJob)+        videoJob = null+        audioJob = null+        rtcpJob = null+        runCatching {+            runBlocking {+                for (job in jobs) {+                    job.cancel()+                    job.join()+                }+            }+        }+        // The display goes before the encoder: it is what is writing into the encoder's surface.         capture?.release()         videoEncoder?.release()         audioEncoder?.release()@@ -239,6 +268,7 @@ class MirrorEngine(         audioEncoder = null         transport = null         senders.clear()+        scope.cancel()     }      /** 32 bits of seconds since 1900, then 32 bits of fraction. */
cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorTileService.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorTileService.kt b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorTileService.ktindex 3ffeb275dc..b43c49f0b1 100644--- a/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorTileService.kt+++ b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorTileService.kt@@ -13,6 +13,7 @@ import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel+import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch  /**@@ -48,9 +49,17 @@ class MirrorTileService : TileService() {      override fun onClick() {         super.onClick()-        if (CastController.mirrorPhase.value != MirrorPhase.Idle) {+        val phase = CastController.mirrorPhase.value+        // Failed is drawn as inactive, so a tap on it has to *start* rather than stop - otherwise+        // the first press after a failure looks like it did nothing.+        if (phase == MirrorPhase.Mirroring || phase == MirrorPhase.Negotiating) {             CastController.stopMirroring(this)-            refreshTile()+            // stopMirroring is asynchronous, so waiting for Idle rather than reading the phase+            // straight back: refreshing now would re-publish the state we are leaving.+            scope.launch {+                CastController.mirrorPhase.first { it != MirrorPhase.Mirroring }+                refreshTile()+            }             return         }         scope.launch {
cast/src/main/java/com/vayunmathur/cast/platform/mirror/StreamSender.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/platform/mirror/StreamSender.kt b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/StreamSender.ktindex 5743e1321d..8aa3e8aca0 100644--- a/cast/src/main/java/com/vayunmathur/cast/platform/mirror/StreamSender.kt+++ b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/StreamSender.kt@@ -24,18 +24,33 @@ class StreamSender(     private val crypto = CastCrypto(stream.keys.key, stream.keys.ivMask)     private val packetizer = CastRtpPacketizer(stream.payloadType, stream.senderSsrc) +    /**+     * One send at a time.+     *+     * [send] runs on the encoder loop and [retransmit] on the RTCP loop, and both drive the same+     * packetizer - whose RTP sequence number is a plain counter. Interleaving them would emit two+     * packets with the same sequence number, which a receiver reads as a duplicate and drops.+     */+    private val lock = Any()+     private var nextFrameId = FrameId.First     private var lastKeyFrameId = FrameId.Leader     private var firstPresentationTimeUs = -1L -    /** The highest frame id sent, which is what an 8-bit checkpoint is expanded against. */+    /**+     * The highest frame id sent, which is what an 8-bit checkpoint is expanded against.+     *+     * Volatile because the RTCP loop reads it while the encoder loop writes it.+     */+    @Volatile     var lastFrameId: FrameId = FrameId.First         private set +    @Volatile     var stats: SenderStats = SenderStats()         private set -    fun send(chunk: EncodedChunk) {+    fun send(chunk: EncodedChunk) = synchronized(lock) {         // Timestamps are relative to the first frame, so a receiver does not have to know when the         // encoder happened to start.         if (firstPresentationTimeUs < 0) firstPresentationTimeUs = chunk.presentationTimeUs@@ -58,10 +73,13 @@ class StreamSender(         lastFrameId = frameId         session.record(frame)         emit(frame, packetIds = null)-        stats = stats.copy(lastRtpTimestamp = rtpTimestamp)+        // The wall clock is captured *here*, alongside the RTP timestamp it corresponds to. A sender+        // report has to pair the two for the same instant; pairing "now" with an older frame's+        // timestamp is what makes a receiver's clock estimate drift.+        stats = stats.copy(lastRtpTimestamp = rtpTimestamp, lastSentAtMillis = System.currentTimeMillis())     } -    fun retransmit(items: List<Retransmission>) {+    fun retransmit(items: List<Retransmission>) = synchronized(lock) {         for (item in items) emit(item.frame, item.packetIds)     } @@ -72,12 +90,14 @@ class StreamSender(         var octets = 0L         packets.forEachIndexed { index, packet ->             if (packetIds != null && index !in packetIds) return@forEachIndexed+            // Only a datagram the kernel actually accepted is counted: a sender report that+            // over-reports what was sent makes the receiver's loss estimate wrong.             if (udp.send(packet)) {                 sent++                 octets += packet.size             }         }-        stats = SenderStats(stats.packets + sent, stats.octets + octets, stats.lastRtpTimestamp)+        stats = stats.copy(packets = stats.packets + sent, octets = stats.octets + octets)     } } @@ -86,4 +106,6 @@ data class SenderStats(     val packets: Long = 0,     val octets: Long = 0,     val lastRtpTimestamp: Long = 0,+    /** When [lastRtpTimestamp] was sent, so a report can pair the two honestly. */+    val lastSentAtMillis: Long = 0, )
cast/src/main/java/com/vayunmathur/cast/platform/mirror/VideoEncoder.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/platform/mirror/VideoEncoder.kt b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/VideoEncoder.ktindex 696fbe8e60..93a1500281 100644--- a/cast/src/main/java/com/vayunmathur/cast/platform/mirror/VideoEncoder.kt+++ b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/VideoEncoder.kt@@ -53,8 +53,15 @@ class VideoEncoder(     private var codec: MediaCodec? = null     private val bufferInfo = MediaCodec.BufferInfo() -    /** SPS/PPS, cached from the codec-config buffer and prepended to the first key frame. */+    /**+     * SPS/PPS, cached from the codec-config buffer and prepended to the first key frame.+     *+     * [sentParameterSets] is volatile because [requestKeyFrame] runs on the RTCP loop while [drain]+     * runs on the encoder loop.+     */     private var parameterSets: ByteArray? = null++    @Volatile     private var sentParameterSets = false      var inputSurface: Surface? = null
cast/src/main/java/com/vayunmathur/cast/service/CastService.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/service/CastService.kt b/cast/src/main/java/com/vayunmathur/cast/service/CastService.ktindex 00011564b5..ce2db10ce8 100644--- a/cast/src/main/java/com/vayunmathur/cast/service/CastService.kt+++ b/cast/src/main/java/com/vayunmathur/cast/service/CastService.kt@@ -89,10 +89,14 @@ class CastService : Service() {     }      override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {-        val isMirroring = intent?.action == ACTION_START_MIRRORING         // Before anything else: this is started with startForegroundService, and the platform kills-        // a process that does not honour that within a few seconds.-        enterForeground(withProjection = isMirroring)+        // a process that does not honour that within a few seconds. The type must be+        // mediaProjection both when a projection is about to be obtained and whenever one is+        // already held - downgrading to mediaPlayback under a live VirtualDisplay is what gets a+        // capturing service killed.+        val needsProjectionType =+            intent?.action == ACTION_START_MIRRORING || projection != null+        enterForeground(withProjection = needsProjectionType)         when (intent?.action) {             ACTION_STOP -> {                 CastController.disconnect(this)@@ -100,6 +104,8 @@ class CastService : Service() {             }             ACTION_STOP_MIRRORING -> {                 releaseProjection()+                // No projection is held any more, so the service should stop claiming that type.+                enterForeground(withProjection = false)                 return START_NOT_STICKY             }             ACTION_START_MIRRORING -> startMirroringFrom(intent)@@ -136,6 +142,7 @@ class CastService : Service() {         val data = IntentCompat.getParcelableExtra(intent, EXTRA_RESULT_DATA, Intent::class.java)         if (data == null) {             Log.w(TAG, "no consent token in the mirroring request")+            demoteFromProjection()             return         }         val manager = getSystemService<MediaProjectionManager>()@@ -148,6 +155,7 @@ class CastService : Service() {         }         if (granted == null) {             Log.w(TAG, "no projection")+            demoteFromProjection()             return         }         releaseProjection()@@ -156,6 +164,16 @@ class CastService : Service() {         CastController.startMirroring(this, granted)     } +    /**+     * Drop back to `mediaPlayback` after failing to obtain a projection.+     *+     * Staying typed `mediaProjection` with no projection to show for it is the state the platform+     * objects to, so it is worth correcting rather than leaving until the next start command.+     */+    private fun demoteFromProjection() {+        if (projection == null) enterForeground(withProjection = false)+    }+     private fun releaseProjection() {         val active = projection ?: return         runCatching { active.unregisterCallback(projectionCallback) }