Modern Apps git

← Modern-Apps.git

cast: fix key frame self-reference that made receivers decode nothing

Commit
b2836ca938ee6f278f9131ff491a11d900b0252e
Author
vayun-mathur <[email protected]>
When
2026-08-21 14:55 UTC (3 months ago)
Parents
7b9a05a

Diff

cast/src/main/java/com/vayunmathur/cast/domain/streaming/StreamSelection.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/domain/streaming/StreamSelection.kt b/cast/src/main/java/com/vayunmathur/cast/domain/streaming/StreamSelection.ktindex e397054677..9544089cfb 100644--- a/cast/src/main/java/com/vayunmathur/cast/domain/streaming/StreamSelection.kt+++ b/cast/src/main/java/com/vayunmathur/cast/domain/streaming/StreamSelection.kt@@ -26,7 +26,7 @@ object StreamSelection {     const val AUDIO_CHANNELS = 2     const val AUDIO_BITRATE = 128_000 -    /** `kStartVideoBitrate` from `mirror_settings.cc`. */+    /** `kStartVideoBitrate` from `mirror_settings.cc`, used when no better figure is supplied. */     const val VIDEO_MAX_BITRATE = 5_000_000      const val VIDEO_MAX_FRAME_RATE = 30@@ -62,8 +62,18 @@ object StreamSelection {      * Stream indexes are load-bearing: `CreateMirroringOffer` in openscreen's `sender_session.cc`      * puts audio at `[0..N-1]` and video at `[N..K]`, and the ANSWER's `sendIndexes` refers back      * to them. Audio is therefore always index 0 and video, when present, index 1.+     *+     * [videoWidth], [videoHeight] and [videoBitRate] describe what will actually be captured, so+     * the advertised `resolutions` and `maxBitRate` are honest. A receiver told to expect 1280x720+     * and then sent a portrait frame has been misinformed.      */-    fun offer(kind: CastDeviceKind, random: SecureRandom = SecureRandom()): StreamPlan {+    fun offer(+        kind: CastDeviceKind,+        videoWidth: Int = 1280,+        videoHeight: Int = 720,+        videoBitRate: Int = VIDEO_MAX_BITRATE,+        random: SecureRandom = SecureRandom(),+    ): StreamPlan {         val audio = StreamKeys(random.bytes16(), random.bytes16())         val audioSsrc = random.ssrc(AUDIO_SSRC_MIN, AUDIO_SSRC_MAX)         val audioStream = OfferStream(@@ -100,10 +110,9 @@ object StreamSelection {             aesIvMask = video.ivMask.toHex(),             timeBase = "1/$VIDEO_TIMEBASE",             maxFrameRate = "${VIDEO_MAX_FRAME_RATE * 1000}/1000",-            maxBitRate = VIDEO_MAX_BITRATE,-            // Only an upper bound. The TV answered `scaling: "sender"` with a 4K display, so the-            // capture resolution is ours to choose and this is what we promise not to exceed.-            resolutions = listOf(Resolution(1280, 720)),+            maxBitRate = videoBitRate,+            // What will actually be sent, so the receiver is not told to expect another shape.+            resolutions = listOf(Resolution(videoWidth, videoHeight)),         )         return StreamPlan(             streams = listOf(audioStream, videoStream),
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 5c8604769b..12d535211a 100644--- a/cast/src/main/java/com/vayunmathur/cast/platform/CastController.kt+++ b/cast/src/main/java/com/vayunmathur/cast/platform/CastController.kt@@ -18,11 +18,15 @@ import com.vayunmathur.cast.domain.streaming.encode import com.vayunmathur.cast.domain.streaming.parseAnswer import com.vayunmathur.cast.network.CastChannel import com.vayunmathur.cast.platform.discovery.CastDiscoveryManager+import com.vayunmathur.cast.platform.mirror.CaptureGeometry+import com.vayunmathur.cast.platform.mirror.MirrorConsentActivity import com.vayunmathur.cast.platform.mirror.MirrorDegradation import com.vayunmathur.cast.platform.mirror.MirrorEngine+import com.vayunmathur.cast.platform.mirror.MirrorGeometry import com.vayunmathur.cast.platform.mirror.MirrorPreferences import com.vayunmathur.cast.platform.mirror.MirrorStopReason import com.vayunmathur.cast.service.CastService+import com.vayunmathur.library.ui.ExternalIntents import com.vayunmathur.library.util.AppMessages import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope@@ -33,6 +37,7 @@ import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock@@ -103,17 +108,22 @@ object CastController {             .also { discoveryManager = it }      /**-     * Open a channel to [device] and launch the mirroring receiver on it.+     * Open a channel to [device], launch the mirroring receiver, and start mirroring.      *-     * A no-op for the device already connected to; switching devices tears the old session down-     * first, since a sender holds one session at a time. The app id follows from-     * [CastDevice.kind] and is not negotiable - a receiver refuses the wrong one at LAUNCH.+     * Connecting and mirroring are one action because there is nothing else this app does. A joined+     * receiver that is not mirroring is a dead state: the TV is already showing the receiver's idle+     * screen and the only thing the connection could still be used for is volume. So tapping a+     * device asks for capture consent as soon as the receiver is joined.+     *+     * A no-op for the device already mirroring to; switching devices tears the old session down+     * first, since a sender holds one session at a time. The app id follows from [CastDevice.kind]+     * and is not negotiable - a receiver refuses the wrong one at LAUNCH.      *      * A [CastPhase.Failed] session is *not* treated as live, so tapping the same device again-     * retries rather than doing nothing. A refusal is a routine outcome here - the receiver says-     * no whenever the capability bitmask and the app id disagree - so a dead end would be a bug.+     * retries rather than doing nothing. A refusal is a routine outcome here - the receiver says no+     * whenever the capability bitmask and the app id disagree - so a dead end would be a bug.      */-    fun connect(context: Context, device: CastDevice) {+    fun connect(context: Context, device: CastDevice, thenMirror: Boolean = true) {         val phase = _sessionState.value.phase         val live = phase != CastPhase.Idle && phase != CastPhase.Failed         if (_device.value?.id == device.id && live) return@@ -150,6 +160,17 @@ object CastController {             // Started only once a channel is actually open, so a failed connection does not             // leave a notification behind.             CastService.start(appContext)+            if (!thenMirror) return@launch+            // Consent can only be asked for by an Activity, and only once the receiver is joined -+            // an OFFER sent before that is dropped without an error. Waiting for Failed too so a+            // refused LAUNCH does not leave a consent dialog queued behind it.+            val resolved = _sessionState.first {+                it.phase == CastPhase.Ready || it.phase == CastPhase.Idle ||+                    it.phase == CastPhase.Failed+            }+            if (resolved.phase == CastPhase.Ready) {+                ExternalIntents.launch(appContext, MirrorConsentActivity.intent(appContext))+            }         }     } @@ -167,6 +188,14 @@ object CastController {         }     } +    /**+     * Log every packet and a throughput summary once a second.+     *+     * A plain switch rather than a build flag: mirroring can only be diagnosed on hardware, and+     * something that needs a recompile to turn on does not get turned on.+     */+    var verboseStreamLogging: Boolean = false+     fun setVolume(level: Double) = act { it.setVolume(level) }      /**@@ -194,13 +223,22 @@ object CastController {             _mirrorPhase.value = MirrorPhase.Negotiating             _degradation.value = MirrorDegradation()             _failure.value = null-            val plan = StreamSelection.offer(device.kind)+            // The capture size is decided here, before the OFFER, so the resolution advertised is+            // the resolution actually sent. Offering 1280x720 and then sending a portrait frame+            // tells the receiver to expect a shape it never gets.+            val geometry = MirrorGeometry.forDisplay(appContext)+            val plan = StreamSelection.offer(+                kind = device.kind,+                videoWidth = geometry.width,+                videoHeight = geometry.height,+                videoBitRate = geometry.bitRate,+            )             val streamingSession = StreamingSession(plan)             streaming = streamingSession             // Fed by CastSession's webrtc route rather than parsed there: OFFER/ANSWER is its own             // state machine and the control plane has no business understanding it.             activeSession.onWebrtcPayload = { payload ->-                onWebrtcPayload(appContext, payload, projection, device.host)+                onWebrtcPayload(appContext, payload, projection, device.host, geometry)             }             send(activeChannel, activeSession) {                 it.webrtcFrame(plan.message(it.allocateRequestId()).encode())@@ -222,6 +260,7 @@ object CastController {         payload: String,         projection: MediaProjection,         host: String,+        geometry: CaptureGeometry,     ) {         val answer = parseAnswer(payload) ?: return         val streamingSession = streaming ?: return@@ -258,10 +297,11 @@ object CastController {                 projection = projection,                 receiverHost = host,                 negotiation = negotiation,+                geometry = geometry,                 session = streamingSession,                 onDegraded = { _degradation.value = it },                 onStopped = { reason -> onEngineStopped(context, reason) },-            )+            ).apply { hexDump = verboseStreamLogging }             engine = newEngine             if (newEngine.start()) {                 _mirrorPhase.value = MirrorPhase.Mirroring
cast/src/main/java/com/vayunmathur/cast/platform/mirror/EncoderSupport.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/platform/mirror/EncoderSupport.kt b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/EncoderSupport.ktindex b1c8a02fd9..00a0c0166f 100644--- a/cast/src/main/java/com/vayunmathur/cast/platform/mirror/EncoderSupport.kt+++ b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/EncoderSupport.kt@@ -33,6 +33,50 @@ object EncoderSupport {      fun audioEncoderName(): String? = findEncoder(AUDIO_MIME) { true } +    /**+     * Reduce [width] x [height] to something the H.264 encoder will actually accept.+     *+     * Native phone resolutions are not always encodable: `MediaCodec` advertises a maximum size, an+     * alignment requirement, and a supported-performance envelope, and a portrait 1344x2992 sits+     * outside what some encoders will take even though the same pixel count in landscape is fine.+     * Rather than let `configure()` throw, the aspect ratio is preserved and the size stepped down+     * until the codec agrees.+     *+     * Returns the input unchanged when there is no encoder to ask, so the caller's own failure+     * handling stays the single place that deals with "this device cannot encode".+     */+    fun clampToEncoder(width: Int, height: Int): Pair<Int, Int> {+        val name = videoEncoderName() ?: return width to height+        val video = runCatching {+            android.media.MediaCodecList(android.media.MediaCodecList.REGULAR_CODECS)+                .codecInfos+                .first { it.name == name }+                .getCapabilitiesForType(VIDEO_MIME)+                .videoCapabilities+        }.getOrNull() ?: return width to height++        // Some encoders only report a landscape envelope, so try the orientation as given and, if+        // that is refused, believe the transposed limits instead.+        if (runCatching { video.isSizeSupported(width, height) }.getOrDefault(false)) {+            return width to height+        }+        var scale = 1.0+        repeat(MAX_CLAMP_STEPS) {+            scale *= CLAMP_STEP+            val w = (width * scale).toInt().alignedDown(video.widthAlignment)+            val h = (height * scale).toInt().alignedDown(video.heightAlignment)+            if (w <= 0 || h <= 0) return width to height+            if (runCatching { video.isSizeSupported(w, h) }.getOrDefault(false)) return w to h+        }+        return width to height+    }++    private fun Int.alignedDown(alignment: Int): Int =+        if (alignment <= 1) this / 2 * 2 else this / alignment * alignment++    private const val CLAMP_STEP = 0.9+    private const val MAX_CLAMP_STEPS = 12+     /** REGULAR_CODECS, so the list matches what an ordinary app is allowed to instantiate. */     private inline fun findEncoder(         mime: String,
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 942345e754..db9f087099 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@@ -31,6 +31,7 @@ private const val NTP_UNIX_OFFSET_SECONDS = 2_208_988_800L  private const val FRAME_POLL_MS = 4L private const val RTCP_POLL_MS = 20L+private const val STATS_LOG_INTERVAL_MS = 1_000L  /** What could not be started, so the UI can say so rather than looking broken. */ data class MirrorDegradation(@@ -60,6 +61,7 @@ class MirrorEngine(     private val projection: MediaProjection,     private val receiverHost: String,     private val negotiation: Negotiation,+    private val geometry: CaptureGeometry,     private val session: StreamingSession,     private val onDegraded: (MirrorDegradation) -> Unit,     private val onStopped: (MirrorStopReason) -> Unit,@@ -84,9 +86,18 @@ class MirrorEngine(     private var videoEncoder: VideoEncoder? = null     private var audioEncoder: AudioEncoder? = null -    /** Hex-dump every packet. Off by default: per-packet and very loud. */+    /**+     * Hex-dump every packet, and log throughput once a second.+     *+     * Settable from [CastController] via a debug switch, because a pipeline that can only be+     * diagnosed by reading it is a pipeline that cannot be diagnosed.+     */     var hexDump: Boolean = false +    /** Counts inbound RTCP so a run can be told apart from one where nothing came back. */+    private var feedbackPackets = 0L+    private var unmatchedPackets = 0L+     fun start(): Boolean {         val udp = CastUdpTransport(receiverHost, negotiation.udpPort)         udp.hexDump = hexDump@@ -122,13 +133,12 @@ class MirrorEngine(     }      private fun startVideo(stream: NegotiatedStream, udp: CastUdpTransport): Boolean {-        val screen = ScreenCapture(appContext, projection)-        val geometry = screen.geometry()+        val screen = ScreenCapture(projection)         val encoder = VideoEncoder(             width = geometry.width,             height = geometry.height,             frameRate = StreamSelection.VIDEO_MAX_FRAME_RATE,-            bitRate = StreamSelection.VIDEO_MAX_BITRATE,+            bitRate = geometry.bitRate,         )         if (!encoder.start()) return false         val surface = encoder.inputSurface@@ -137,7 +147,11 @@ class MirrorEngine(             screen.release()             return false         }-        Log.i(TAG, "mirroring at ${geometry.width}x${geometry.height}")+        Log.i(+            TAG,+            "mirroring at ${geometry.width}x${geometry.height} " ++                "@ ${geometry.bitRate / 1_000_000.0} Mbit/s",+        )         videoEncoder = encoder         capture = screen         val sender = StreamSender(stream, udp, session)@@ -180,6 +194,7 @@ class MirrorEngine(     private fun startRtcp(udp: CastUdpTransport) {         rtcpJob = scope.launch {             var lastReport = 0L+            var lastStatsLog = 0L             while (isActive) {                 val now = System.currentTimeMillis()                 if (now - lastReport >= SENDER_REPORT_INTERVAL_MS) {@@ -202,6 +217,19 @@ class MirrorEngine(                         )                     }                 }+                // The single most useful line for diagnosing "the TV is black": whether packets are+                // leaving, and whether the receiver is answering. Feedback arriving at all proves it+                // is parsing our RTP, which halves the search space.+                if (now - lastStatsLog >= STATS_LOG_INTERVAL_MS) {+                    lastStatsLog = now+                    val summary = senders.entries.joinToString(" ") { (kind, sender) ->+                        "$kind=${sender.stats.packets}pkt/${sender.stats.octets}B"+                    }+                    Log.i(+                        TAG,+                        "$summary feedback=$feedbackPackets unmatchedRtcp=$unmatchedPackets",+                    )+                }                 var packet = udp.receive()                 while (packet != null) {                     handleFeedback(packet)@@ -227,6 +255,15 @@ class MirrorEngine(                 senderSsrc = stream.senderSsrc,                 maxFrameId = sender.lastFrameId,             ) ?: continue+            feedbackPackets+++            if (hexDump) {+                Log.i(+                    TAG,+                    "${stream.kind} feedback checkpoint=${feedback.checkpoint} " ++                        "nacks=${feedback.nacks.size} acks=${feedback.ackedFrames.size} " ++                        "playoutDelay=${feedback.playoutDelayMs}",+                )+            }             val recovery = session.onFeedback(feedback)             sender.retransmit(recovery.retransmissions)             if (recovery.needsKeyFrame && stream.kind == StreamKind.Video) {@@ -235,6 +272,9 @@ class MirrorEngine(             }             return         }+        // Receiver reports and event logs also arrive here and are none of our business, but a run+        // where *everything* is unmatched means the SSRC pairing is wrong.+        unmatchedPackets++     }      /**
cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorGeometry.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorGeometry.kt b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorGeometry.ktnew file mode 100644index 0000000000..06b0715348--- /dev/null+++ b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorGeometry.kt@@ -0,0 +1,81 @@+package com.vayunmathur.cast.platform.mirror++import android.content.Context+import android.util.DisplayMetrics+import android.util.Log+import android.view.WindowManager+import androidx.core.content.getSystemService+import com.vayunmathur.cast.domain.streaming.StreamSelection++private const val TAG = "MirrorGeometry"++/** The capture size, the density to mirror at, and the bitrate that size needs. */+data class CaptureGeometry(+    val width: Int,+    val height: Int,+    val densityDpi: Int,+    val bitRate: Int,+)++/**+ * Decides what size to capture the screen at.+ *+ * Separate from [ScreenCapture] because the answer is needed **before** the OFFER goes out: the+ * OFFER advertises a `resolutions` list, and a receiver told to expect one shape while being sent+ * another has been misinformed. It needs no projection, only display metrics, so it runs before+ * consent is even asked for.+ *+ * The screen's **native resolution** is used, not a downscale. The receiver answers+ * `scaling: "sender"` against its own (often 4K) panel, so it will not letterbox for us and sending+ * fewer pixels than the phone has just throws detail away for nothing. The only reason to reduce it+ * is an encoder that refuses the size, which is what [EncoderSupport.clampToEncoder] handles.+ */+object MirrorGeometry {++    /**+     * Bits per pixel per second.+     *+     * 0.1 bpp at 30 fps is a common desktop-sharing figure - screen content is mostly static with+     * sharp edges, so it needs far less than camera video at the same size but punishes a bitrate+     * too low to keep text legible. On a 1344x2992 phone this lands near 12 Mbit/s.+     */+    private const val BITS_PER_PIXEL = 0.1++    /** openscreen's `kDefaultVideoMinBitRate`, as a floor for a very small display. */+    private const val MIN_BITRATE = 300_000++    /**+     * Above this a phone encoder starts dropping frames rather than degrading quality, and a home+     * network starts losing packets. Not a resolution limit - only a rate one.+     */+    private const val MAX_BITRATE = 20_000_000++    fun forDisplay(context: Context): CaptureGeometry {+        val metrics = DisplayMetrics()+        val windowManager = context.getSystemService<WindowManager>()+        @Suppress("DEPRECATION")+        windowManager?.defaultDisplay?.getRealMetrics(metrics)+        val realWidth = metrics.widthPixels.takeIf { it > 0 } ?: 1080+        val realHeight = metrics.heightPixels.takeIf { it > 0 } ?: 1920+        // 4:2:0 chroma subsampling cannot represent an odd width or height, and some encoders fail+        // outright rather than rounding for you.+        val (width, height) = EncoderSupport.clampToEncoder(realWidth.even(), realHeight.even())+        val bitRate = (+            width.toLong() * height * StreamSelection.VIDEO_MAX_FRAME_RATE * BITS_PER_PIXEL+            )+            .toLong()+            .coerceIn(MIN_BITRATE.toLong(), MAX_BITRATE.toLong())+            .toInt()+        if (width != realWidth || height != realHeight) {+            Log.i(TAG, "capturing at ${width}x$height rather than ${realWidth}x$realHeight")+        }+        return CaptureGeometry(+            width = width,+            height = height,+            densityDpi = metrics.densityDpi.takeIf { it > 0 } ?: DisplayMetrics.DENSITY_DEFAULT,+            bitRate = bitRate,+        )+    }++    private fun Int.even(): Int = this / 2 * 2+}
cast/src/main/java/com/vayunmathur/cast/platform/mirror/ScreenCapture.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/platform/mirror/ScreenCapture.kt b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/ScreenCapture.ktindex f4476de399..8016f23029 100644--- a/cast/src/main/java/com/vayunmathur/cast/platform/mirror/ScreenCapture.kt+++ b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/ScreenCapture.kt@@ -1,55 +1,23 @@ package com.vayunmathur.cast.platform.mirror -import android.content.Context import android.hardware.display.DisplayManager import android.hardware.display.VirtualDisplay import android.media.projection.MediaProjection-import android.util.DisplayMetrics import android.util.Log import android.view.Surface-import android.view.WindowManager-import androidx.core.content.getSystemService  private const val TAG = "ScreenCapture" -/** The capture size and the frame rate to encode at. */-data class CaptureGeometry(val width: Int, val height: Int, val densityDpi: Int)- /**  * A `VirtualDisplay` mirroring the real screen into an encoder's input surface.  *- * The receiver answers `scaling: "sender"` with its own (often 4K) dimensions, so choosing the- * capture size is ours to do. It is scaled down to at most [MAX_DIMENSION] on the long edge, keeping- * the real aspect ratio, because that is what the OFFER promised and what keeps the bitrate sane.- *- * Both dimensions are rounded to even numbers: H.264's 4:2:0 chroma subsampling cannot represent an- * odd width or height, and some encoders fail outright rather than rounding for you.+ * The size comes from [MirrorGeometry], decided before the OFFER so the resolution advertised and+ * the resolution actually sent are the same.  */-class ScreenCapture(-    private val context: Context,-    private val projection: MediaProjection,-) {+class ScreenCapture(private val projection: MediaProjection) {      private var display: VirtualDisplay? = null -    fun geometry(): CaptureGeometry {-        val metrics = DisplayMetrics()-        val windowManager = context.getSystemService<WindowManager>()-        @Suppress("DEPRECATION")-        windowManager?.defaultDisplay?.getRealMetrics(metrics)-        val realWidth = metrics.widthPixels.takeIf { it > 0 } ?: 1080-        val realHeight = metrics.heightPixels.takeIf { it > 0 } ?: 1920-        val scale = minOf(-            1.0,-            MAX_DIMENSION.toDouble() / maxOf(realWidth, realHeight),-        )-        return CaptureGeometry(-            width = ((realWidth * scale).toInt() / 2) * 2,-            height = ((realHeight * scale).toInt() / 2) * 2,-            densityDpi = metrics.densityDpi.takeIf { it > 0 } ?: DisplayMetrics.DENSITY_DEFAULT,-        )-    }-     /** Returns false if the platform refused the display, which leaves nothing to encode. */     fun start(surface: Surface, geometry: CaptureGeometry): Boolean = try {         display = projection.createVirtualDisplay(@@ -72,9 +40,4 @@ class ScreenCapture(         runCatching { display?.release() }         display = null     }--    private companion object {-        /** 720p on the long edge, matching the `resolutions` the OFFER advertises. */-        const val MAX_DIMENSION = 1280-    } }
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 8aa3e8aca0..bed6005411 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@@ -34,7 +34,6 @@ class StreamSender(     private val lock = Any()      private var nextFrameId = FrameId.First-    private var lastKeyFrameId = FrameId.Leader     private var firstPresentationTimeUs = -1L      /**@@ -57,10 +56,18 @@ class StreamSender(         val elapsedUs = chunk.presentationTimeUs - firstPresentationTimeUs         val rtpTimestamp = elapsedUs * stream.timebase / 1_000_000L         val frameId = nextFrameId-        // A key frame references the leader, having no predecessor. A delta frame references the-        // last key frame rather than the frame just before it, so one lost delta does not invalidate-        // every frame that follows.-        val referenced = if (chunk.isKeyFrame) FrameId.Leader else lastKeyFrameId+        // A key frame references **itself**, and a delta frame its immediate predecessor. Both are+        // load-bearing and neither is a free choice:+        //+        //  - `encoded_frame.h` is explicit that a frame needing nothing else to decode must set+        //    referenced_frame_id == frame_id. Pointing a key frame at FrameId.Leader instead makes+        //    the receiver wait for frame 255 forever and decode nothing at all - a black screen with+        //    no error anywhere.+        //  - MediaCodec emits IPPP, where each P frame really does depend on the one before it, so+        //    naming any other frame misdescribes the bitstream.+        //+        // Chromium does exactly this in `media/cast/encoding/media_video_encoder_wrapper.cc`.+        val referenced = if (chunk.isKeyFrame) frameId else FrameId(frameId.value - 1)         val frame = EncryptedFrame(             frameId = frameId,             referencedFrameId = referenced,@@ -68,7 +75,6 @@ class StreamSender(             isKeyFrame = chunk.isKeyFrame,             payload = crypto.crypt(frameId, chunk.data),         )-        if (chunk.isKeyFrame) lastKeyFrameId = frameId         nextFrameId += 1         lastFrameId = frameId         session.record(frame)@@ -76,7 +82,10 @@ class StreamSender(         // 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())+        stats = stats.copy(+            lastRtpTimestamp = rtpTimestamp,+            lastSentAtMillis = System.currentTimeMillis(),+        )     }      fun retransmit(items: List<Retransmission>) = synchronized(lock) {
cast/src/test/java/com/vayunmathur/cast/domain/streaming/CastRtpPacketizerTest.kt
diff --git a/cast/src/test/java/com/vayunmathur/cast/domain/streaming/CastRtpPacketizerTest.kt b/cast/src/test/java/com/vayunmathur/cast/domain/streaming/CastRtpPacketizerTest.ktindex 3f84397db3..d1dd5377b4 100644--- a/cast/src/test/java/com/vayunmathur/cast/domain/streaming/CastRtpPacketizerTest.kt+++ b/cast/src/test/java/com/vayunmathur/cast/domain/streaming/CastRtpPacketizerTest.kt@@ -107,6 +107,34 @@ class CastRtpPacketizerTest {         assertEquals(0, second.getShort(2))     } +    @Test+    fun `a key frame references itself and a delta frame its predecessor`() {+        // The invariant that made a real TV show nothing. encoded_frame.h: "If this frame does not+        // require any other frame in order to become decodable (e.g., key frames),+        // referenced_frame_id must equal frame_id." Pointing a key frame at FrameId.Leader makes the+        // receiver wait for frame 255 forever, with no error anywhere.+        val keyFrame = EncryptedFrame(+            frameId = FrameId.First,+            referencedFrameId = FrameId.First,+            rtpTimestamp = 0,+            isKeyFrame = true,+            payload = ByteArray(4),+        )+        val packet = CastRtpPacketizer(96, 50_001).packetize(keyFrame).single()+        // Frame id and reference frame id are the same byte value.+        assertEquals(packet[13], packet[18])+        assertEquals(0, packet[18].toInt() and 0xff)++        val delta = keyFrame.copy(+            frameId = FrameId(1),+            referencedFrameId = FrameId.First,+            isKeyFrame = false,+        )+        val deltaPacket = CastRtpPacketizer(96, 50_001).packetize(delta).single()+        assertEquals(1, deltaPacket[13].toInt() and 0xff)+        assertEquals(0, deltaPacket[18].toInt() and 0xff)+    }+     @Test     fun `frame id and rtp timestamp are truncated to the wire width`() {         // The counter is 64-bit; only the low 8 bits go in the header and the low 32 in the