Modern Apps git

← Modern-Apps.git

cast: negotiate hardware H.265/AV1, drop H.264, buffer playout

Commit
a6b40063aad477a5b840d8e4329f9bee7d32f6e3
Author
vayun-mathur <[email protected]>
When
2026-08-23 04:49 UTC (3 months ago)
Parents
b016aa8

Diff

cast/protocol/src/main/java/com/vayunmathur/cast/protocol/CodecNegotiation.kt
diff --git a/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/CodecNegotiation.kt b/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/CodecNegotiation.ktnew file mode 100644index 0000000000..e2bb2ab691--- /dev/null+++ b/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/CodecNegotiation.kt@@ -0,0 +1,115 @@+package com.vayunmathur.cast.protocol++/** What [CodecNegotiation.choose] settled on, or what each end offered when nothing fitted. */+sealed interface CodecSelection {++    /**+     * Agreed.+     *+     * [receiverLimits] is the TV's envelope for [codec], and it is what the frame is fitted into and+     * what the frame rate is capped by - not the sender's, which only decides whether the fitted frame+     * is encodable at all.+     *+     * [bitRateCeiling] is the **lower** of the two ends' ceilings, because neither may be exceeded: a+     * phone whose encoder advertises less than the TV's decoder would otherwise be configured above its+     * own stated maximum.+     */+    data class Chosen(+        val codec: VideoCodec,+        val receiverLimits: CodecLimits,+        val bitRateCeiling: Int,+    ) : CodecSelection++    /**+     * Nothing fitted, with both offers named so the failure can say *which* end was short.+     *+     * An empty [senderOffered] is a phone with no hardware encoder for either codec; an empty+     * [receiverOffered] is a TV with no hardware decoder for either. Two non-empty lists with nothing+     * in common is a third thing again, and all three read differently to a user - so the lists are+     * carried rather than collapsed into one reason here.+     *+     * [demoted] is carried for the same reason: a codec both ends offer but that has already failed on+     * this pairing is skipped silently, and a message built from the offers alone would then claim two+     * ends had nothing in common when in fact they had, which is a lie the user cannot act on.+     */+    data class None(+        val senderOffered: List<VideoCodec>,+        val receiverOffered: List<VideoCodec>,+        val demoted: Set<VideoCodec>,+    ) : CodecSelection+}++/**+ * Which codec a session will use.+ *+ * **A pure function on purpose.** Every unknown in this feature is a device fact - whether a phone+ * has hardware AV1 at all, whether a TV's AV1 decoder is the software one the platform lists first -+ * and none of them can be answered without hardware. What *can* be settled without a device is the+ * rule applied to the answers, so it lives here where a JVM test can pin it down, and the platform+ * work on each side is reduced to filling in two lists.+ */+object CodecNegotiation {++    /**+     * AV1 first.+     *+     * It reaches the same quality at roughly half H.264's bitrate against H.265's ~0.6, and on a link+     * that answered 24 Mbit/s with 8.5% packet loss the bitrate is the constraint that matters. It is+     * also the codec with the unknowns, which is the argument for preferring it as soon as both ends+     * claim it: the first session is the experiment, and there is a persisted demotion behind it.+     */+    val PREFERENCE: List<VideoCodec> = listOf(VideoCodec.Av1, VideoCodec.Hevc)++    /**+     * The best codec both ends can do at [width] x [height] and [frameRate].+     *+     * [senderCodecs] is what this phone can *hardware*-encode, one entry per codec, and [receiver] is+     * what the TV advertised in `TV_IDENTITY`. A codec is viable when both ends offer it and the+     * sender's own envelope takes the frame after it has been fitted into the receiver's - which is+     * the real asymmetry between the two sides: the receiver's limits scale the frame down, while the+     * sender's encoder either takes it or does not.+     *+     * **[frameRate] is a floor against the sender's envelope only.** A phone whose encoder cannot+     * sustain it is excluded rather than accepted at a lower rate, because an encoder that silently+     * under-delivers - measured at 11 fps against a negotiated 30 - is what this ordering exists to+     * prevent. A *receiver* that caps out lower is a different matter: it genuinely cannot go faster,+     * and there is nothing to be gained by refusing it, so its cap lowers the session's rate instead+     * (see `MirrorGeometry.frameRateFor`).+     *+     * [demoted] is remembered per TV from a previous failure, so a codec that has already proved+     * itself broken on this pairing is skipped rather than retried every session.+     */+    fun choose(+        senderCodecs: List<CodecLimits>,+        receiver: DecoderLimits,+        width: Int,+        height: Int,+        frameRate: Int,+        demoted: Set<VideoCodec> = emptySet(),+    ): CodecSelection {+        for (codec in PREFERENCE) {+            if (codec in demoted) continue+            val mine = senderCodecs.firstOrNull { it.codec == codec } ?: continue+            val theirs = receiver.forCodec(codec) ?: continue+            val (fittedWidth, fittedHeight) = theirs.fit(width, height)+            if (!mine.admits(fittedWidth, fittedHeight, frameRate)) continue+            return CodecSelection.Chosen(+                codec = codec,+                receiverLimits = theirs,+                bitRateCeiling = tighterCeiling(mine.maxBitRate, theirs.maxBitRate),+            )+        }+        return CodecSelection.None(+            senderOffered = senderCodecs.map { it.codec },+            receiverOffered = receiver.codecs,+            demoted = demoted,+        )+    }++    /** The lower of two ceilings, treating a non-positive one as "did not say". */+    private fun tighterCeiling(mine: Int, theirs: Int): Int = when {+        mine <= 0 -> theirs+        theirs <= 0 -> mine+        else -> minOf(mine, theirs)+    }+}
cast/protocol/src/main/java/com/vayunmathur/cast/protocol/HandshakeMessages.kt
diff --git a/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/HandshakeMessages.kt b/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/HandshakeMessages.ktindex 0051384236..6b7157a76c 100644--- a/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/HandshakeMessages.kt+++ b/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/HandshakeMessages.kt@@ -10,8 +10,12 @@ import kotlinx.serialization.json.Json  * Checked on both sides and refused on mismatch, rather than negotiated down. Two of our own builds  * that disagree about the wire format are a bug to fix, not a compatibility matrix to maintain -  * both halves ship from this repo at the same version.+ *+ * 3 is where H.264 stopped being the only codec. [DecoderLimits] became a per-codec list and+ * [StreamConfig] gained a required codec, both reshaped rather than extended with compatibility+ * defaults - a mismatch is refused outright anyway, so the bump is the honest signal.  */-const val PROTOCOL_VERSION = 2+const val PROTOCOL_VERSION = 3  /** The mDNS service type the TV registers and the phone browses for. */ const val MACAST_SERVICE_TYPE = "_macast._tcp"@@ -30,6 +34,7 @@ const val MACAST_SERVICE_TYPE = "_macast._tcp"  *  *        STREAM_CONFIG ───────────────────────►         (chosen to fit the reported limits)  *                          ◄───────────── STREAM_READY  (udp port + receiver SSRCs)+ *        VIDEO_CODEC_CONFIG ─────────────────►          (AV1 only, and repeated on every PLI)  *        … RTP over UDP …  *        BYE ─────────────────────────────────►  * ```@@ -81,14 +86,85 @@ data class TvIdentity(  * by hand - wasting most of the frame. These come from the TV's real  * `MediaCodecInfo.VideoCapabilities`, so the sender can send the phone's own aspect ratio at  * whatever size fits and let the TV pad it.+ *+ * **One envelope per codec, and no flat AVC-shaped fields.** Those four numbers were+ * `getCapabilitiesForType(AVC)` output; with AVC gone they would be a lie, and an H.265 decoder's+ * ceiling is not an AV1 decoder's. An empty list is a receiver that could enumerate no hardware+ * decoder at all, and the phone refuses with a named failure rather than guessing.  */ @Serializable data class DecoderLimits(+    val videoCodecs: List<CodecLimits> = emptyList(),+) {+    fun forCodec(codec: VideoCodec): CodecLimits? = videoCodecs.firstOrNull { it.codec == codec }++    val codecs: List<VideoCodec> get() = videoCodecs.map { it.codec }+}++/**+ * The video codecs this protocol carries, in no particular order - [CodecNegotiation] holds the+ * preference.+ *+ * **H.264 is deliberately absent.** H.265 and AV1 reach the same quality at roughly half the+ * bitrate, and on a link that answered 24 Mbit/s with 8.5% packet loss the codec is what buys back+ * the headroom. A device with neither hardware codec refuses to mirror and says which were missing,+ * rather than falling back to the thing that caused the problem.+ *+ * [mimeType] is spelled out rather than taken from `MediaFormat`: this module is an Android library+ * only because [SecretSealing] needs one, and every test in it runs on a plain JVM.+ */+@Serializable+enum class VideoCodec(val mimeType: String, val label: String) {+    @SerialName("H265")+    Hevc("video/hevc", "H.265"),++    @SerialName("AV1")+    Av1("video/av01", "AV1"),+    ;++    /**+     * Whether the decoder must be handed its codec configuration out of band, through+     * [VideoCodecConfig], before it can be configured at all.+     *+     * H.265 inherits the H.264 contract unchanged: VPS/SPS/PPS are Annex-B start-code units, so the+     * sender prepends them to the first IDR and the receiver finds them in the stream. AV1's+     * sequence header is an OBU that `MediaCodec` expects as `csd-0`, and the receiver configures its+     * decoder *before* any frame arrives - so for AV1 there is nowhere in the stream to read it from.+     */+    val needsCodecConfig: Boolean get() = this == Av1+}++/** One codec's envelope, as reported by whichever end owns the codec. */+@Serializable+data class CodecLimits(+    val codec: VideoCodec,     val maxWidth: Int,     val maxHeight: Int,     val maxFrameRate: Int,     val maxBitRate: Int,-)+) {+    /**+     * The largest frame with [width] x [height]'s aspect ratio that fits this envelope.+     *+     * Both dimensions are checked independently, because a decoder's limits are not necessarily the+     * same shape as a phone's screen: a 3840x2160 decoder still cannot take a 1440x3120 portrait+     * frame unrotated, and scaling by the tighter of the two ratios is what respects both.+     *+     * Lives here rather than in the sender so codec selection can be a pure function - the choice+     * depends on the *fitted* frame, and a copy of this arithmetic on each side would be a copy that+     * could disagree.+     */+    fun fit(width: Int, height: Int): Pair<Int, Int> {+        if (maxWidth <= 0 || maxHeight <= 0) return width to height+        if (width <= maxWidth && height <= maxHeight) return width to height+        val scale = minOf(maxWidth.toDouble() / width, maxHeight.toDouble() / height)+        return (width * scale).toInt() to (height * scale).toInt()+    }++    /** Whether this envelope takes exactly [width] x [height] at [frameRate]. */+    fun admits(width: Int, height: Int, frameRate: Int): Boolean =+        width in 1..maxWidth && height in 1..maxHeight && frameRate <= maxFrameRate+}  /** The session secret, sealed to [TvIdentity.publicBundle]. Base64 of [SecretSealing.seal]. */ @Serializable@@ -162,6 +238,15 @@ data class StreamConfig(     val video: Boolean,     val audioSsrc: Long,     val videoSsrc: Long,+    /**+     * The codec the payload is in.+     *+     * Required, with no default: the version bump is what makes that safe, and a defaulted codec+     * would be a build silently agreeing to decode something it was never told about. The receiver+     * builds its decoder from this, so it is also what decides whether a [VideoCodecConfig] has to+     * arrive before the picture can start.+     */+    val videoCodec: VideoCodec,     /**      * The name of the app whose content this is, or empty for screen mirroring.      *@@ -182,6 +267,22 @@ data class StreamReady(     val videoSsrc: Long, ) : ControlMessage +/**+ * The video decoder's configuration bytes, phone to TV, for a codec that cannot carry them in-band.+ *+ * [csd] is Base64 of whatever `MediaCodec` handed the sender in its `BUFFER_FLAG_CODEC_CONFIG`+ * buffer, passed through untouched: for AV1 that is an `av1C` configuration record or a raw sequence+ * header OBU, and which one it is turns out to be a device fact rather than an API fact. The receiver+ * installs it as `csd-0`.+ *+ * **Re-sent on every key-frame request, not delivered once.** `CODEC_CONFIG` is emitted only at+ * `start()`, so a single-shot delivery has no repair path and losing it would be a permanent black+ * screen. Re-sending keeps PLI as the one repair primitive for both codecs.+ */+@Serializable+@SerialName("VIDEO_CODEC_CONFIG")+data class VideoCodecConfig(val csd: String) : ControlMessage+ /**  * Either end, at any point after the secret is established.  *@@ -192,6 +293,18 @@ data class StreamReady( @SerialName("BYE") data class Bye(val reason: String = "") : ControlMessage +/**+ * The [Bye.reason] values the *phone* acts on rather than only logs.+ *+ * A free-text reason is right for everything a human reads in a log, but an AV1 failure has to reach+ * the sender as a decision: it is what makes the next session start at H.265 instead. Naming the+ * string here is what stops the two ends from disagreeing about its spelling.+ */+object ByeReason {+    /** The TV had a decoder and a surface, and the codec config it needed never arrived. */+    const val MISSING_CODEC_CONFIG = "missing codec config"+}+ /**  * Strict on the way in, complete on the way out.  *
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 b390b1b656..919bbfaf0c 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@@ -66,6 +66,11 @@ class ReceiverSession(     /** Feedback rounds where a gap blocked delivery while frames beyond it kept arriving. */     private var stalledRounds = 0 +    /** Feedback rounds where packets kept arriving and nothing at all became decodable. */+    private var starvedRounds = 0+    private var packetsAtLastFeedback = 0L+    private var framesAtLastFeedback = 0L+     /** Counters, so the receiver's log can be read against the sender's. */     var packetsReceived: Long = 0         private set@@ -109,14 +114,12 @@ class ReceiverSession(      */     fun feedback(): ByteArray {         val nacks = assembler.missingPackets(after = checkpoint)-        val needsKeyFrame = !synchronised || isStalled()+        val needsKeyFrame = !synchronised || isStalled() || isStarved()         if (needsKeyFrame && synchronised) {-            // The gap has outlived the sender's retransmit buffer. Nothing else will unblock it, so-            // give up on it: resynchronise on the next key frame rather than stalling for ever.-            synchronised = false-            ready.clear()-            assembler.reset()-            stalledRounds = 0+            // 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+            // rather than stalling for ever.+            requestKeyFrame()         }         val block = Rtcp.feedback(             receiverSsrc = stream.receiverSsrc,@@ -140,6 +143,24 @@ class ReceiverSession(     fun onSenderReport(datagram: ByteArray): SenderReport? =         Rtcp.parseSenderReport(datagram, stream.senderSsrc) +    /**+     * Give up on what we hold and resynchronise on the next key frame.+     *+     * Used by [feedback] when a gap has outlived the sender's retransmit buffer, and callable from+     * outside for the case this session cannot see: a frame it counted as delivered that the decoder+     * then refused. The checkpoint has already advanced past it, so every delta frame behind it+     * references something the decoder does not have - and without this the session stays+     * "synchronised", no PLI ever goes out, and the corruption lasts until the sender's next+     * scheduled IDR.+     */+    fun requestKeyFrame() {+        synchronised = false+        ready.clear()+        assembler.reset()+        stalledRounds = 0+        starvedRounds = 0+    }+     /**      * A gap is blocking delivery while frames beyond it keep arriving.      *@@ -156,6 +177,34 @@ class ReceiverSession(         return stalledRounds > STALL_ROUNDS     } +    /**+     * Packets are arriving and *nothing* is completing.+     *+     * [isStalled] cannot see this case, because it asks whether frames are queued behind a gap - and+     * under heavy loss no frame ever completes, so [ready] stays empty, `stalledRounds` keeps+     * resetting, and the session concludes it is healthy while the picture is frozen. Measured: 18+     * seconds of a frozen mirror at 8.5% packet loss during which not one key frame was asked for,+     * because by this class's own definition nothing was wrong.+     *+     * Counted in feedback rounds like [isStalled], and only while packets are actually arriving: a+     * sender that has genuinely stopped is the control channel's problem, not something a key frame+     * would fix.+     */+    private fun isStarved(): Boolean {+        if (framesDelivered != framesAtLastFeedback) {+            framesAtLastFeedback = framesDelivered+            packetsAtLastFeedback = packetsReceived+            starvedRounds = 0+            return false+        }+        starvedRounds+++        // Packets since the **last delivered frame**, not since the last round. Asking whether a+        // packet arrived in this particular 50 ms window meant the counter reset on every quiet+        // round, so at the ~25 packets/s a struggling sender produces it could never reach the+        // threshold: measured, the picture stayed frozen and this never fired once.+        return packetsReceived != packetsAtLastFeedback && starvedRounds > STARVED_ROUNDS+    }+     /**      * Release everything now deliverable, oldest first.      *@@ -197,5 +246,16 @@ class ReceiverSession(          * enough that a picture never freezes for a noticeable time.          */         const val STALL_ROUNDS = 3++        /**+         * Longer than [STALL_ROUNDS], because this is the blunter instrument.+         *+         * A gap with frames piled behind it is unambiguous after three rounds. "Nothing completed"+         * only becomes conclusive once retransmission has had a fair chance, and the answer - throwing+         * away every partial frame the assembler holds - discards work that NACKs might still have+         * repaired. Ten rounds is half a second of frozen picture, against the 18 seconds this+         * replaces.+         */+        const val STARVED_ROUNDS = 10     } }
cast/protocol/src/main/java/com/vayunmathur/cast/protocol/Rtcp.kt
diff --git a/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/Rtcp.kt b/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/Rtcp.ktindex 59d8ad487f..768b0f0f35 100644--- a/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/Rtcp.kt+++ b/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/Rtcp.kt@@ -276,6 +276,14 @@ object Rtcp {      * and is expanded against it, exactly as `ExpandLessThanOrEqual` does. Without that the      * checkpoint would appear to jump backwards every 256 frames.      *+     * **Every sub-packet is checked against this stream's SSRC pair, the PLI included.** A receiver+     * sends one datagram per stream, and the sender tries each stream in turn until one parses. A PLI+     * accepted without that check made the *audio* stream claim a datagram carrying video's key-frame+     * request: the audio stream ignores picture loss, and the sender stopped looking, so the video+     * stream never saw its own feedback. Measured: a receiver PLI-ing for ten seconds while the sender+     * logged not one key-frame request, and no video NACKs answered either, because exactly the+     * datagrams sent when the receiver was in trouble were the ones thrown away.+     *      * Returns null when the datagram contains nothing addressed to this stream.      */     fun parse(@@ -297,7 +305,10 @@ object Rtcp {                         senderSsrc,                         maxFrameId,                     )?.let { feedback = it }-                    SUBTYPE_PICTURE_LOSS_INDICATOR -> pictureLoss = true+                    SUBTYPE_PICTURE_LOSS_INDICATOR ->+                        if (namesStream(packet, start, size, receiverSsrc, senderSsrc)) {+                            pictureLoss = true+                        }                 }             }         }@@ -341,6 +352,23 @@ object Rtcp {         }     } +    /**+     * True when a sub-packet's leading SSRC pair names this stream.+     *+     * Both the PLI and the feedback block start with receiver-then-sender, so one check serves both.+     */+    private fun namesStream(+        packet: ByteArray,+        start: Int,+        size: Int,+        receiverSsrc: Long,+        senderSsrc: Long,+    ): Boolean {+        if (size < 8) return false+        return packet.getInt(start) == receiverSsrc and 0xffff_ffffL &&+            packet.getInt(start + 4) == senderSsrc and 0xffff_ffffL+    }+     /**      * One `kFeedback` payload, i.e. the bytes after its 4-byte common header.      *
cast/protocol/src/main/java/com/vayunmathur/cast/protocol/Streams.kt
diff --git a/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/Streams.kt b/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/Streams.ktindex 6f1593fe9a..a36a471493 100644--- a/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/Streams.kt+++ b/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/Streams.kt@@ -30,10 +30,16 @@ object StreamConstants {     /**      * How long the receiver buffers before playing, in ms.      *-     * `kDefaultTargetPlayoutDelay` from openscreen. It is the budget a retransmission has to arrive-     * within to still be useful, which is why the sender's retransmit buffer is sized against it.+     * It is the budget a retransmission has to arrive within to still be useful, which is why the+     * sender's retransmit buffer is sized against it, and it is advertised in every RTCP report.+     *+     * **Deliberately not openscreen's `kDefaultTargetPlayoutDelay` of 400.** That figure was carried+     * over from a Cast receiver and then advertised by a receiver that implemented no buffer at all -+     * frames were presented at network-arrival spacing, so jitter became judder. 150 ms is what the+     * receiver's playout queue actually holds: deep enough to absorb Wi-Fi jitter and leave a NACK+     * time to be answered, shallow enough that mirroring still feels interactive.      */-    const val TARGET_DELAY_MS = 400+    const val TARGET_DELAY_MS = 150      /**      * SSRC ranges from openscreen `cast/streaming/ssrc.cc`. Audio is "high priority" and video is
cast/protocol/src/test/java/com/vayunmathur/cast/protocol/CodecNegotiationTest.kt
diff --git a/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/CodecNegotiationTest.kt b/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/CodecNegotiationTest.ktnew file mode 100644index 0000000000..cb96d32759--- /dev/null+++ b/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/CodecNegotiationTest.kt@@ -0,0 +1,235 @@+package com.vayunmathur.cast.protocol++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertIs+import kotlin.test.assertTrue++/**+ * Codec selection, which is the part of this feature that can be settled without a device.+ *+ * Every unknown behind H.265 and AV1 mirroring is a device fact - whether a phone has hardware AV1,+ * whether a TV's AV1 decoder is the software one the platform lists first - and none of them can be+ * answered here. What can be pinned down is the rule applied to the answers, and that rule is the+ * thing that decides whether a session runs at 6 Mbit/s or refuses outright.+ */+class CodecNegotiationTest {++    private fun limits(+        codec: VideoCodec,+        maxWidth: Int = 3840,+        maxHeight: Int = 2160,+        maxFrameRate: Int = 60,+        maxBitRate: Int = 40_000_000,+    ) = CodecLimits(codec, maxWidth, maxHeight, maxFrameRate, maxBitRate)++    private val bothCodecs = listOf(limits(VideoCodec.Av1), limits(VideoCodec.Hevc))++    private fun choose(+        sender: List<CodecLimits>,+        receiver: List<CodecLimits>,+        width: Int = 1344,+        height: Int = 2992,+        frameRate: Int = 30,+        demoted: Set<VideoCodec> = emptySet(),+    ) = CodecNegotiation.choose(+        senderCodecs = sender,+        receiver = DecoderLimits(receiver),+        width = width,+        height = height,+        frameRate = frameRate,+        demoted = demoted,+    )++    @Test+    fun `AV1 wins when both ends can do both`() {+        // The preference, and the reason it is AV1: roughly half H.264's bitrate for the same picture,+        // on a link whose problem was bitrate.+        val chosen = assertIs<CodecSelection.Chosen>(choose(bothCodecs, bothCodecs))+        assertEquals(VideoCodec.Av1, chosen.codec)+    }++    @Test+    fun `H265 is used when only one end has AV1`() {+        val phoneOnly = assertIs<CodecSelection.Chosen>(+            choose(bothCodecs, listOf(limits(VideoCodec.Hevc))),+        )+        assertEquals(VideoCodec.Hevc, phoneOnly.codec)++        val tvOnly = assertIs<CodecSelection.Chosen>(+            choose(listOf(limits(VideoCodec.Hevc)), bothCodecs),+        )+        assertEquals(VideoCodec.Hevc, tvOnly.codec)+    }++    @Test+    fun `the receiver's envelope is what comes back, and the ceiling is the tighter of the two`() {+        // Load-bearing: the frame size and the frame rate are both taken from the receiver's envelope,+        // and taking the phone's instead would send a TV more than it said it could decode. The bitrate+        // is the one number where *neither* end may be exceeded.+        val chosen = assertIs<CodecSelection.Chosen>(+            choose(+                sender = listOf(limits(VideoCodec.Av1, maxBitRate = 40_000_000)),+                receiver = listOf(limits(VideoCodec.Av1, maxBitRate = 8_000_000)),+            ),+        )+        assertEquals(8_000_000, chosen.receiverLimits.maxBitRate)+        assertEquals(8_000_000, chosen.bitRateCeiling)++        // And the other way round: a phone whose encoder is the tighter one must not be configured+        // above what it said it would take.+        val phoneTighter = assertIs<CodecSelection.Chosen>(+            choose(+                sender = listOf(limits(VideoCodec.Av1, maxBitRate = 5_000_000)),+                receiver = listOf(limits(VideoCodec.Av1, maxBitRate = 40_000_000)),+            ),+        )+        assertEquals(5_000_000, phoneTighter.bitRateCeiling)+    }++    @Test+    fun `an end that stated no bitrate ceiling does not clamp the other to zero`() {+        val noCeiling = assertIs<CodecSelection.Chosen>(+            choose(+                sender = listOf(limits(VideoCodec.Av1, maxBitRate = 0)),+                receiver = listOf(limits(VideoCodec.Av1, maxBitRate = 9_000_000)),+            ),+        )+        assertEquals(9_000_000, noCeiling.bitRateCeiling)+    }++    @Test+    fun `a phone with no hardware encoder refuses, and says so was the phone`() {+        // No H.264 to fall back to, so this is a terminal answer - which is why the two lists are+        // carried out: an empty sender list is a different sentence from an empty receiver one.+        val none = assertIs<CodecSelection.None>(choose(emptyList(), bothCodecs))+        assertEquals(emptyList<VideoCodec>(), none.senderOffered)+        assertEquals(listOf(VideoCodec.Av1, VideoCodec.Hevc), none.receiverOffered)+    }++    @Test+    fun `a TV with no hardware decoder refuses, and says so was the TV`() {+        val none = assertIs<CodecSelection.None>(choose(bothCodecs, emptyList()))+        assertEquals(listOf(VideoCodec.Av1, VideoCodec.Hevc), none.senderOffered)+        assertEquals(emptyList<VideoCodec>(), none.receiverOffered)+    }++    @Test+    fun `two ends with nothing in common refuse, with both offers named`() {+        val none = assertIs<CodecSelection.None>(+            choose(listOf(limits(VideoCodec.Av1)), listOf(limits(VideoCodec.Hevc))),+        )+        assertEquals(listOf(VideoCodec.Av1), none.senderOffered)+        assertEquals(listOf(VideoCodec.Hevc), none.receiverOffered)+    }++    @Test+    fun `a codec whose encoder cannot hold the frame rate is skipped`() {+        // The rate is the floor and resolution is what yields to it - an *encoder* that tops out at+        // 24 fps is excluded rather than quietly accepted, because a stream delivering 11 fps against a+        // negotiated 30 is the failure this ordering exists to prevent.+        val chosen = assertIs<CodecSelection.Chosen>(+            choose(+                sender = listOf(limits(VideoCodec.Av1, maxFrameRate = 24), limits(VideoCodec.Hevc)),+                receiver = bothCodecs,+                frameRate = 30,+            ),+        )+        assertEquals(VideoCodec.Hevc, chosen.codec)+    }++    @Test+    fun `a TV that caps out below the floor still gets the codec, at its own rate`() {+        // The deliberate asymmetry: a decoder that cannot go faster genuinely cannot, and refusing to+        // mirror to it would gain nothing. Its cap lowers the session instead, which is what+        // MirrorGeometry.frameRateFor does with the envelope handed back here.+        val chosen = assertIs<CodecSelection.Chosen>(+            choose(+                sender = bothCodecs,+                receiver = listOf(limits(VideoCodec.Av1, maxFrameRate = 24)),+                frameRate = 30,+            ),+        )+        assertEquals(VideoCodec.Av1, chosen.codec)+        assertEquals(24, chosen.receiverLimits.maxFrameRate)+    }++    @Test+    fun `a codec whose encoder cannot hold the frame is skipped, after the TV has scaled it`() {+        // The asymmetry between the two ends: the TV's envelope *scales* the frame, and the phone's+        // encoder then either takes the result or does not. A 1080p-only encoder is excluded at+        // 1344x2992 even though the 4K TV would have taken it.+        val chosen = assertIs<CodecSelection.Chosen>(+            choose(+                sender = listOf(+                    limits(VideoCodec.Av1, maxWidth = 1920, maxHeight = 1080),+                    limits(VideoCodec.Hevc),+                ),+                receiver = bothCodecs,+            ),+        )+        assertEquals(VideoCodec.Hevc, chosen.codec)++        // And the same encoder is fine once the TV's own limit has brought the frame inside it. A+        // quarter of 1344x2992 is 336x748, which a 1080p encoder takes.+        val scaled = assertIs<CodecSelection.Chosen>(+            choose(+                sender = listOf(limits(VideoCodec.Av1, maxWidth = 1920, maxHeight = 1080)),+                receiver = listOf(limits(VideoCodec.Av1, maxWidth = 336, maxHeight = 748)),+            ),+        )+        assertEquals(VideoCodec.Av1, scaled.codec)+    }++    @Test+    fun `a codec demoted against this TV is not tried again`() {+        // The recovery path in place of a mid-session downgrade: an AV1 failure is remembered per TV,+        // so the next session starts at H.265 rather than repeating the same black screen.+        val chosen = assertIs<CodecSelection.Chosen>(+            choose(bothCodecs, bothCodecs, demoted = setOf(VideoCodec.Av1)),+        )+        assertEquals(VideoCodec.Hevc, chosen.codec)++        // Both demoted is a refusal, not a fallback to the codec that already failed.+        assertIs<CodecSelection.None>(+            choose(bothCodecs, bothCodecs, demoted = setOf(VideoCodec.Av1, VideoCodec.Hevc)),+        )+    }++    @Test+    fun `a refusal caused by a demotion says so rather than denying the codec was shared`() {+        // Otherwise the message built from the two offers would claim a phone that can send AV1 and a TV+        // that can decode AV1 have nothing in common, which is untrue and leaves the user no way to find+        // the remembered demotion that is the real cause.+        val none = assertIs<CodecSelection.None>(+            choose(+                sender = listOf(limits(VideoCodec.Av1)),+                receiver = bothCodecs,+                demoted = setOf(VideoCodec.Av1),+            ),+        )+        assertEquals(setOf(VideoCodec.Av1), none.demoted)+        assertEquals(listOf(VideoCodec.Av1), none.senderOffered)+        // Both ends offered it, so the caller can tell this apart from a genuine mismatch.+        assertTrue(VideoCodec.Av1 in none.senderOffered && VideoCodec.Av1 in none.receiverOffered)+    }++    @Test+    fun `fit keeps the aspect ratio and scales by the tighter of the two ratios`() {+        // A 4K decoder still cannot take a tall portrait frame unrotated, and scaling by width alone+        // would overflow the height. Halving is used rather than a real phone shape so the assertion is+        // about the rule and not about which way a double rounded.+        val tv = limits(VideoCodec.Av1, maxWidth = 3840, maxHeight = 2000)+        assertEquals(500 to 2000, tv.fit(1000, 4000))++        // Already inside is left exactly alone, so no frame is resampled for nothing.+        assertEquals(1920 to 1080, tv.fit(1920, 1080))+    }++    @Test+    fun `a degenerate envelope is treated as unknown rather than as zero`() {+        // A decoder that answered 0 would otherwise scale every frame to nothing.+        val unknown = limits(VideoCodec.Av1, maxWidth = 0, maxHeight = 0)+        assertEquals(1344 to 2992, unknown.fit(1344, 2992))+    }+}
cast/protocol/src/test/java/com/vayunmathur/cast/protocol/HandshakeTest.kt
diff --git a/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/HandshakeTest.kt b/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/HandshakeTest.ktindex e668e84939..fae8e277dc 100644--- a/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/HandshakeTest.kt+++ b/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/HandshakeTest.kt@@ -24,10 +24,10 @@ class HandshakeTest {     private val secret = ByteArray(SessionKeys.SECRET_BYTES) { (it * 5 + 1).toByte() }      private val limits = DecoderLimits(-        maxWidth = 3840,-        maxHeight = 2160,-        maxFrameRate = 60,-        maxBitRate = 40_000_000,+        videoCodecs = listOf(+            CodecLimits(VideoCodec.Av1, 3840, 2160, 60, 40_000_000),+            CodecLimits(VideoCodec.Hevc, 3840, 2160, 60, 40_000_000),+        ),     )      // ---- framing ----@@ -89,6 +89,7 @@ class HandshakeTest {                 video = true,                 audioSsrc = 1_234,                 videoSsrc = 50_002,+                videoCodec = VideoCodec.Av1,             ),             // Screen mirroring leaves the label empty; an SDK session names the app. Both have to             // survive the round trip, and the empty case is the one `encodeDefaults` could eat.@@ -101,10 +102,15 @@ class HandshakeTest {                 video = true,                 audioSsrc = 1_235,                 videoSsrc = 50_003,+                videoCodec = VideoCodec.Hevc,                 appLabel = "YouPipe",             ),             StreamReady(udpPort = 47_505, audioSsrc = 4_321, videoSsrc = 50_009),+            // The AV1 handover. Base64 rather than a byte array because it is the one message whose+            // payload is opaque to this protocol - whatever `MediaCodec` produced, passed through.+            VideoCodecConfig(csd = ProtocolBase64.encode(ByteArray(48) { (it * 3).toByte() })),             Bye(reason = "user stopped"),+            Bye(reason = ByeReason.MISSING_CODEC_CONFIG),         )         val codec = ControlCodec()         for (message in messages) {@@ -126,6 +132,46 @@ class HandshakeTest {         assertFalse(body.contains("deviceKey"), body)     } +    @Test+    fun `codec names on the wire are the stable ones, not the Kotlin identifiers`() {+        // The enum is `Hevc` and `Av1` in Kotlin and `H265` and `AV1` on the wire. Renaming either+        // constant would otherwise change the wire format silently, and the failure would be a TV+        // that decodes nothing while both ends agree they are on version 3.+        val body = ControlCodec()+            .encode(+                StreamConfig(+                    width = 1920,+                    height = 1080,+                    frameRate = 30,+                    bitRate = 6_000_000,+                    audio = false,+                    video = true,+                    audioSsrc = 1,+                    videoSsrc = 50_001,+                    videoCodec = VideoCodec.Hevc,+                ),+            )+            .toString(Charsets.UTF_8)+        assertTrue(body.contains("\"videoCodec\":\"H265\""), body)+    }++    @Test+    fun `a TV that can decode nothing advertises an empty list rather than a guess`() {+        // The deleted FALLBACK_LIMITS. Guessing "1080p30 H.264" was defensible while H.264 was+        // universal; it would now be a fabrication, and the phone has to be able to see the absence.+        val empty = DecoderLimits()+        assertTrue(empty.videoCodecs.isEmpty())+        assertNull(empty.forCodec(VideoCodec.Av1))+        val codec = ControlCodec()+        val identity = TvIdentity(+            receiverName = "Living Room TV",+            receiverId = "tv-1",+            publicBundle = ProtocolBase64.encode(ByteArray(8)),+            limits = empty,+        )+        assertEquals(identity, codec.decode(codec.encode(identity)))+    }+     @Test     fun `a message from a newer build with extra fields still parses`() {         val codec = ControlCodec()@@ -366,6 +412,7 @@ class HandshakeTest {             video = true,             audioSsrc = 1_234,             videoSsrc = 50_002,+            videoCodec = VideoCodec.Av1,         )         val ready = StreamReady(udpPort = 47_505, audioSsrc = 4_321, videoSsrc = 50_009)         val negotiation = Negotiation.of(config, ready, keys)
cast/protocol/src/test/java/com/vayunmathur/cast/protocol/RtcpTest.kt
diff --git a/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/RtcpTest.kt b/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/RtcpTest.ktindex 2b10624e8d..503fcfe66c 100644--- a/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/RtcpTest.kt+++ b/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/RtcpTest.kt@@ -323,6 +323,22 @@ class RtcpTest {         assertEquals(FrameId(3), parsed.checkpoint)     } +    @Test+    fun `a picture loss indicator for another stream is not this stream's`() {+        // The exact shape a real session produces: the receiver sends one datagram per stream, and+        // the sender tries each stream in turn until one parses. This is a *video* datagram, and the+        // audio stream must not claim it - the audio stream ignores picture loss and the sender stops+        // looking, so accepting it here throws away the video stream's key-frame request and every+        // NACK riding with it. That cost ten seconds of frozen picture per occurrence.+        val otherReceiver = RECEIVER_SSRC + 1_000+        val otherSender = SENDER_SSRC + 1_000+        val videoDatagram = Rtcp.compound(+            Rtcp.pictureLossIndicator(otherReceiver, otherSender),+            Rtcp.feedback(otherReceiver, otherSender, FrameId(3), 400),+        )+        assertNull(parse(videoDatagram, FrameId(3)))+    }+     @Test     fun `a sender report we build is one the receiver parses`() {         val built = Rtcp.senderReport(
cast/src/main/AndroidManifest.xml
diff --git a/cast/src/main/AndroidManifest.xml b/cast/src/main/AndroidManifest.xmlindex b0b163f443..2393a95e44 100644--- a/cast/src/main/AndroidManifest.xml+++ b/cast/src/main/AndroidManifest.xml@@ -1,6 +1,21 @@ <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android"> +    <uses-permission android:name="android.permission.INTERNET" />+    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />+    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />+    <!-- Local Network Protections (Android 16+): without this NsdManager.discoverServices throws+         SecurityException and every LAN socket is blocked, so the device list is silently empty. -->+    <uses-permission android:name="android.permission.ACCESS_LOCAL_NETWORK" />++    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />+    <uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PROJECTION" />+    <uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />+    <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />+    <!-- AudioRecord needs this even for playback capture, where no microphone is involved: the+         permission gates the API, not the source. -->+    <uses-permission android:name="android.permission.RECORD_AUDIO" />+     <uses-feature android:name="android.hardware.wifi" android:required="false" />      <permission
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 127ded99fc..1f0ee27963 100644--- a/cast/src/main/java/com/vayunmathur/cast/network/CastUdpTransport.kt+++ b/cast/src/main/java/com/vayunmathur/cast/network/CastUdpTransport.kt@@ -3,6 +3,7 @@ package com.vayunmathur.cast.network import android.util.Log import java.net.InetSocketAddress import java.net.PortUnreachableException+import java.net.StandardSocketOptions import java.nio.ByteBuffer import java.nio.channels.DatagramChannel @@ -30,9 +31,15 @@ class CastUdpTransport(private val host: String, private val port: Int) {     fun open(): Boolean = try {         channel = DatagramChannel.open().apply {             configureBlocking(false)+            // An IDR at native resolution is a few hundred packets handed to the kernel at once,+            // and a non-blocking write into a full send buffer silently does not go out. Best+            // effort: the kernel clamps to its own maximum, so the granted size is read back and+            // logged.+            runCatching { setOption(StandardSocketOptions.SO_SNDBUF, SEND_BUFFER_BYTES) }             connect(InetSocketAddress(host, port))         }-        Log.i(TAG, "udp connected to $host:$port")+        val granted = runCatching { channel?.getOption(StandardSocketOptions.SO_SNDBUF) }.getOrNull()+        Log.i(TAG, "udp connected to $host:$port with sndbuf=${granted}B")         true     } catch (e: Exception) {         Log.w(TAG, "could not open a udp socket to $host:$port", e)@@ -51,6 +58,19 @@ class CastUdpTransport(private val host: String, private val port: Int) {      private var unreachableCount = 0 +    /**+     * Packets the kernel would not take, and the last time that was said out loud.+     *+     * This was the pipeline's largest diagnostic blind spot: a full send buffer made [send] return+     * false and the packet simply vanished - uncounted, unlogged, and recovered only if the receiver+     * happened to NACK it. Rate-limited to one line, because a burst that overruns the buffer+     * overruns it for hundreds of packets at a time.+     */+    var sendFailures: Long = 0+        private set++    private var lastFailureLogMs = 0L+     fun send(packet: ByteArray): Boolean {         val active = channel ?: return false         if (hexDump) Log.i(TAG, "-> ${packet.size}B ${packet.toHexPreview()}")@@ -60,6 +80,7 @@ class CastUdpTransport(private val host: String, private val port: Int) {             // would inflate the sender report and skew the receiver's loss estimate.             val wrote = active.write(ByteBuffer.wrap(packet)) == packet.size             unreachableCount = 0+            if (!wrote) countFailure()             wrote         } catch (e: PortUnreachableException) {             // Counted rather than logged per packet: at 30 fps this would be thousands of identical@@ -71,10 +92,19 @@ class CastUdpTransport(private val host: String, private val port: Int) {             false         } catch (e: Exception) {             Log.w(TAG, "udp send failed", e)+            countFailure()             false         }     } +    private fun countFailure() {+        sendFailures+++        val now = System.currentTimeMillis()+        if (now - lastFailureLogMs < FAILURE_LOG_INTERVAL_MS) return+        lastFailureLogMs = now+        Log.w(TAG, "the send buffer is full; $sendFailures packets dropped before they left")+    }+     /** One datagram, or null when nothing is waiting. Never blocks. */     fun receive(): ByteArray? {         val active = channel ?: return null@@ -103,7 +133,13 @@ class CastUdpTransport(private val host: String, private val port: Int) {     private companion object {         const val MAX_DATAGRAM = 2048 +        /** Room for one native-resolution IDR burst, so a frame is not lost to its own size. */+        const val SEND_BUFFER_BYTES = 2 * 1024 * 1024+         /** One unreachable reply can precede the receiver binding; a run of them cannot. */         const val UNREACHABLE_THRESHOLD = 30++        /** Send failures come in bursts, so they are summarised rather than reported. */+        const val FAILURE_LOG_INTERVAL_MS = 1_000L     } }
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 eabf1887cb..e622fb6239 100644--- a/cast/src/main/java/com/vayunmathur/cast/platform/CastController.kt+++ b/cast/src/main/java/com/vayunmathur/cast/platform/CastController.kt@@ -12,6 +12,7 @@ import com.vayunmathur.cast.domain.ClientPhase import com.vayunmathur.cast.domain.ClientState import com.vayunmathur.cast.network.ControlSocket import com.vayunmathur.cast.platform.discovery.CastDiscoveryManager+import com.vayunmathur.cast.platform.mirror.EncoderSupport import com.vayunmathur.cast.platform.mirror.MirrorConsentActivity import com.vayunmathur.cast.platform.mirror.MirrorDegradation import com.vayunmathur.cast.platform.mirror.MirrorEngine@@ -19,8 +20,14 @@ import com.vayunmathur.cast.platform.mirror.MirrorGeometry import com.vayunmathur.cast.platform.mirror.MirrorPreferences import com.vayunmathur.cast.platform.mirror.MirrorSource import com.vayunmathur.cast.platform.mirror.MirrorStopReason+import com.vayunmathur.cast.protocol.ByeReason+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.StreamConstants import com.vayunmathur.cast.protocol.StreamingSession+import com.vayunmathur.cast.protocol.VideoCodec import com.vayunmathur.cast.service.CastService import com.vayunmathur.library.ui.ExternalIntents import com.vayunmathur.library.util.AppMessages@@ -33,6 +40,7 @@ import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update+import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock@@ -63,6 +71,23 @@ sealed interface ContentSessionResult {     class Failed(val reason: Int) : ContentSessionResult } +/**+ * The codec a session will use, or why it will not run.+ *+ * A two-case result rather than a nullable codec, because the refusal carries a sentence the user has+ * to read: with no H.264 fallback, "this phone cannot encode H.265 or AV1" is the whole answer and+ * there is nothing else to try.+ */+private sealed interface CodecOutcome {++    /** Everything the geometry and the bitrate are computed from. */+    data class Chosen(val selection: CodecSelection.Chosen) : CodecOutcome {+        val codec: VideoCodec get() = selection.codec+    }++    data class Refused(val message: String) : CodecOutcome+}+ /**  * The single owner of the live session.  *@@ -92,6 +117,15 @@ object CastController {     /** The running mirror. Its retransmit buffers live per-stream inside it. */     private var engine: MirrorEngine? = null +    /**+     * The codec the running engine is encoding with.+     *+     * Kept so a failure can be attributed to it and remembered against this TV: [MirrorStopReason] is+     * a cause rather than a codec, and by the time it arrives the geometry that chose the codec is+     * gone.+     */+    private var activeCodec: VideoCodec? = null+     private val _mirrorPhase = MutableStateFlow(MirrorPhase.Idle)     val mirrorPhase: StateFlow<MirrorPhase> = _mirrorPhase.asStateFlow() @@ -269,7 +303,13 @@ object CastController {         // Persisted against the TV's own id rather than the mDNS instance name, so renaming the TV does         // not make the phone ask for a code again.         if (deviceKey != null) {-            MirrorPreferences.rememberDeviceKey(context, activeClient.receiverId ?: device.id, deviceKey)+            val receiverId = activeClient.receiverId ?: device.id+            MirrorPreferences.rememberDeviceKey(context, receiverId, deviceKey)+            // A code pairing is a fresh start with this TV - it has been reset, or reinstalled, or is+            // simply a different box on the same name - so a codec remembered as broken against the old+            // one has nothing to say about this one. It is also the only reset a user can reach, which+            // is why the refusal message tells them to re-pair.+            MirrorPreferences.clearDemotedCodecs(context, receiverId)         }         _sessionState.value = ClientState(             phase = ClientPhase.Paired,@@ -322,16 +362,33 @@ object CastController {             _degradation.value = MirrorDegradation()             _failure.value = null +            // The codec comes first, because everything else is chosen against it: the frame size fits+            // *that* codec's envelope on the TV, and the bitrate is that codec's efficiency applied to+            // the H.264 reference. There is no H.264 fallback behind this - a phone or a TV without one+            // of the two hardware codecs is told which were missing and mirroring stops here.+            val (screenWidth, screenHeight) = MirrorGeometry.screenSize(appContext)+            val codec = when (+                val choice = chooseCodec(appContext, device, activeClient, screenWidth, screenHeight)+            ) {+                is CodecOutcome.Refused -> {+                    Log.w(TAG, "refusing to mirror: ${choice.message}")+                    abandonMirroring(appContext, projection, choice.message)+                    return@launch+                }+                is CodecOutcome.Chosen -> choice+            }+             // The frame size is chosen from the TV's own reported limits, and it is the phone's real             // aspect ratio: the receiver letterboxes, so none of the encoded frame is wasted on bars.-            val geometry = MirrorGeometry.forDisplay(appContext, activeClient.limits)-            val frameRate = MirrorGeometry.frameRateFor(activeClient.limits)+            val geometry = MirrorGeometry.forDisplay(appContext, codec.selection)+            val frameRate = MirrorGeometry.frameRateFor(codec.selection.receiverLimits)             val outcome = mutex.withLock {                 activeClient.configureStream(                     width = geometry.width,                     height = geometry.height,                     frameRate = frameRate,                     bitRate = geometry.bitRate,+                    videoCodec = codec.codec,                     audio = true,                     video = true,                 )@@ -353,21 +410,25 @@ object CastController {                 receiverHost = device.host,                 negotiation = ready.negotiation,                 geometry = geometry,+                videoCodec = codec.codec,                 frameRate = frameRate,                 onDegraded = { _degradation.value = it },                 onStopped = { reason -> onEngineStopped(appContext, reason) },+                onCodecConfig = { csd -> sendCodecConfig(activeClient, csd) },             ).apply { hexDump = verboseStreamLogging }             engine = newEngine+            activeCodec = codec.codec             if (newEngine.start()) {                 _mirrorPhase.value = MirrorPhase.Mirroring                 _sessionState.update {                     it.copy(phase = ClientPhase.Streaming, negotiation = ready.negotiation)                 }-                startWatch(appContext, activeClient)+                startWatch(appContext, activeClient, device, codec.codec)             } 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+                activeCodec = null                 runCatching { projection.stop() }             }         }@@ -408,14 +469,24 @@ object CastController {         _degradation.value = MirrorDegradation()         _failure.value = null -        val geometry = MirrorGeometry.forContent(width, height, activeClient.limits)-        val frameRate = MirrorGeometry.frameRateFor(activeClient.limits)+        val codec = when (val choice = chooseCodec(appContext, device, activeClient, width, height)) {+            is CodecOutcome.Refused -> {+                Log.w(TAG, "refusing an app-content session: ${choice.message}")+                _mirrorPhase.value = MirrorPhase.Failed+                _failure.value = choice.message+                return@withContext ContentSessionResult.Failed(CastContract.REASON_FAILED)+            }+            is CodecOutcome.Chosen -> choice+        }+        val geometry = MirrorGeometry.forContent(width, height, codec.selection)+        val frameRate = MirrorGeometry.frameRateFor(codec.selection.receiverLimits)         val outcome = mutex.withLock {             activeClient.configureStream(                 width = geometry.width,                 height = geometry.height,                 frameRate = frameRate,                 bitRate = geometry.bitRate,+                videoCodec = codec.codec,                 audio = wantAudio,                 video = true,                 appLabel = appLabel,@@ -435,17 +506,21 @@ object CastController {             receiverHost = device.host,             negotiation = ready.negotiation,             geometry = geometry,+            videoCodec = codec.codec,             frameRate = frameRate,             onDegraded = { _degradation.value = it },             onStopped = { reason -> onEngineStopped(appContext, reason) },+            onCodecConfig = { csd -> sendCodecConfig(activeClient, csd) },         ).apply { hexDump = verboseStreamLogging }         engine = newEngine+        activeCodec = codec.codec         // No surface means there is nowhere for the app to draw, which for an SDK session is the whole         // point - unlike mirroring, it cannot usefully degrade to audio only.         val surface = if (newEngine.start()) newEngine.contentSurface else null         if (surface == null) {             newEngine.stop()             engine = null+            activeCodec = null             _mirrorPhase.value = MirrorPhase.Failed             return@withContext ContentSessionResult.Failed(CastContract.REASON_FAILED)         }@@ -453,7 +528,7 @@ object CastController {         _sessionState.update {             it.copy(phase = ClientPhase.Streaming, negotiation = ready.negotiation)         }-        startWatch(appContext, activeClient)+        startWatch(appContext, activeClient, device, codec.codec)         ContentSessionResult.Started(             surface = surface,             audioWriteEnd = newEngine.audioWriteEnd,@@ -472,13 +547,41 @@ object CastController {      * negotiation is waiting for. Until this starts, a dead TV surfaces as a failed `configureStream`,      * which is just as prompt.      */-    private fun startWatch(appContext: Context, activeClient: MirrorClient) {+    private fun startWatch(+        appContext: Context,+        activeClient: MirrorClient,+        device: CastDevice,+        codec: VideoCodec,+    ) {         watchJob = scope.launch {-            activeClient.awaitEnd()+            val reason = activeClient.awaitEnd()+            // **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+            // publishing its own failure, and a second teardown here would clear it.+            if (!isActive) return@launch             Log.i(TAG, "the control channel closed")+            val receiverId = activeClient.receiverId ?: device.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 = _failure.value             // Cleared first: teardown cancels watchJob, and this coroutine *is* watchJob.             watchJob = 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) {+                Log.w(TAG, "'${device.friendlyName}' never got ${codec.label}'s codec config")+                MirrorPreferences.demoteCodec(appContext, receiverId, codec)+                appContext.getString(R.string.cast_mirror_codec_config_failed)+            } else {+                standing+            }+            if (message != null) {+                _failure.value = message+                _mirrorPhase.value = MirrorPhase.Failed+            }             CastService.stop(appContext)         }     }@@ -516,21 +619,133 @@ object CastController {     }      private fun onEngineStopped(context: Context, reason: MirrorStopReason) {-        _failure.value = context.getString(-            when (reason) {-                MirrorStopReason.Udp -> R.string.cast_mirror_udp_failed-                MirrorStopReason.NoEncoders -> R.string.cast_mirror_no_encoder-                MirrorStopReason.ReceiverGone -> R.string.cast_mirror_receiver_gone-            },-        )+        val codec = activeCodec+        _failure.value = when (reason) {+            MirrorStopReason.Udp -> context.getString(R.string.cast_mirror_udp_failed)+            MirrorStopReason.NoEncoders -> context.getString(R.string.cast_mirror_no_encoder)+            MirrorStopReason.ReceiverGone -> context.getString(R.string.cast_mirror_receiver_gone)+            MirrorStopReason.CodecConfig ->+                context.getString(R.string.cast_mirror_codec_config_failed)+        }         _mirrorPhase.value = MirrorPhase.Failed         endContentSession(CastContract.REASON_FAILED)         CastService.stopMirroring(context)+        if (reason == MirrorStopReason.CodecConfig && codec != null) {+            endCodecConfigFailure(context, codec)+        }+    }++    /**+     * End the whole session, not just the mirror, and remember the codec that did it.+     *+     * **Unlike every other stop reason, this one leaves a perfectly healthy control channel.** Nothing+     * would tear the session down, so `_sessionState` would sit at [ClientPhase.Streaming] - and+     * [connect] treats that as live, so tapping the same TV again would return early and do nothing.+     * The user would be left unable to retry the very TV that just failed, which is exactly the retry+     * the demotion exists to make work.+     *+     * Launched rather than run inline because this is called from the engine's own video coroutine, and+     * [stopEngine] joins that coroutine - doing it here would be waiting on ourselves.+     */+    private fun endCodecConfigFailure(context: Context, codec: VideoCodec) {+        val receiverId = client?.receiverId ?: _device.value?.id+        val message = context.getString(R.string.cast_mirror_codec_config_failed)+        scope.launch {+            if (receiverId != null) MirrorPreferences.demoteCodec(context, receiverId, codec)+            client?.let { mutex.withLock { it.sayGoodbye("no codec config") } }+            teardown()+            // After the teardown, which resets both of these - see startWatch for the same ordering.+            _failure.value = message+            _mirrorPhase.value = MirrorPhase.Failed+            CastService.stop(context)+        }+    }++    /**+     * Which codec this session will use, or the sentence explaining why there is none.+     *+     * Both ends' hardware is intersected by [CodecNegotiation], which is a pure function so the rule+     * can be unit-tested; everything device-specific is in the two lists handed to it. [width] and+     * [height] are the *unfitted* frame, because a codec is only viable if it takes the frame after the+     * TV's own envelope has scaled it.+     */+    private suspend fun chooseCodec(+        context: Context,+        device: CastDevice,+        activeClient: MirrorClient,+        width: Int,+        height: Int,+    ): CodecOutcome {+        val receiverId = activeClient.receiverId ?: device.id+        val demoted = MirrorPreferences.demotedCodecs(context, receiverId)+        if (demoted.isNotEmpty()) {+            Log.i(+                TAG,+                "skipping ${demoted.joinToString { it.label }} - it has already failed on this TV",+            )+        }+        val selection = CodecNegotiation.choose(+            senderCodecs = EncoderSupport.videoCodecs(),+            receiver = activeClient.limits ?: DecoderLimits(),+            width = width,+            height = height,+            // The rate is a floor, not a target: a codec that cannot hold it is excluded rather than+            // accepted at whatever it manages. Resolution is what yields.+            frameRate = StreamConstants.VIDEO_MAX_FRAME_RATE,+            demoted = demoted,+        )+        return when (selection) {+            is CodecSelection.Chosen -> {+                Log.i(TAG, "chose ${selection.codec.label} for '${device.friendlyName}'")+                CodecOutcome.Chosen(selection)+            }+            is CodecSelection.None -> CodecOutcome.Refused(refusal(context, selection))+        }+    }++    /**+     * Which end was short, named.+     *+     * The reason there is no H.264 fallback is the reason this has to be specific: "mirroring failed"+     * would leave a user with a device that will never work and no way to find out why. The demotion+     * case gets its own sentence for the same reason - the two ends *do* share a codec there, and a+     * message built from the offers alone would deny it.+     */+    private fun refusal(context: Context, none: CodecSelection.None): String {+        val labels = { codecs: Collection<VideoCodec> -> codecs.joinToString(" or ") { it.label } }+        val both = labels(CodecNegotiation.PREFERENCE)+        val blockedByDemotion = none.demoted.filter {+            it in none.senderOffered && it in none.receiverOffered+        }+        return when {+            blockedByDemotion.isNotEmpty() ->+                context.getString(R.string.cast_mirror_codec_demoted, labels(blockedByDemotion))+            none.senderOffered.isEmpty() ->+                context.getString(R.string.cast_mirror_phone_no_codec, both)+            none.receiverOffered.isEmpty() ->+                context.getString(R.string.cast_mirror_tv_no_codec, both)+            else -> context.getString(+                R.string.cast_mirror_no_common_codec,+                labels(none.senderOffered),+                labels(none.receiverOffered),+            )+        }+    }++    /**+     * Put the codec configuration on the control channel.+     *+     * Under [mutex] because the encoder loop and the RTCP loop both call this while [startWatch] is+     * reading the same socket, and two writers interleaving would corrupt a frame.+     */+    private fun sendCodecConfig(activeClient: MirrorClient, csd: ByteArray) {+        scope.launch { mutex.withLock { activeClient.sendCodecConfig(csd) } }     }      private fun stopEngine() {         engine?.stop()         engine = null+        activeCodec = null     }      /**
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 f37c88b827..1390320514 100644--- a/cast/src/main/java/com/vayunmathur/cast/platform/MirrorClient.kt+++ b/cast/src/main/java/com/vayunmathur/cast/platform/MirrorClient.kt@@ -5,6 +5,7 @@ import android.util.Log import com.vayunmathur.cast.domain.ClientFailure import com.vayunmathur.cast.network.ControlSocket import com.vayunmathur.cast.protocol.Bye+import com.vayunmathur.cast.protocol.ByeReason import com.vayunmathur.cast.protocol.DecoderLimits import com.vayunmathur.cast.protocol.Hello import com.vayunmathur.cast.protocol.Negotiation@@ -23,6 +24,8 @@ import com.vayunmathur.cast.protocol.StreamConstants import com.vayunmathur.cast.protocol.StreamReady import com.vayunmathur.cast.protocol.Transcript import com.vayunmathur.cast.protocol.TvIdentity+import com.vayunmathur.cast.protocol.VideoCodec+import com.vayunmathur.cast.protocol.VideoCodecConfig import java.security.SecureRandom  private const val TAG = "MirrorClient"@@ -90,7 +93,7 @@ class MirrorClient(     var receiverId: String? = null         private set -    /** The TV's real decoder limits, which is what the frame size is chosen against. */+    /** The TV's real decoder limits, one envelope per codec, which the frame size is chosen against. */     var limits: DecoderLimits? = null         private set @@ -124,12 +127,19 @@ class MirrorClient(         receiverName = identity.receiverName         receiverId = identity.receiverId         limits = identity.limits-        Log.i(-            TAG,-            "'${identity.receiverName}' decodes up to ${identity.limits.maxWidth}x" +-                "${identity.limits.maxHeight} @ ${identity.limits.maxFrameRate}fps, " +-                "${identity.limits.maxBitRate / 1_000_000.0} Mbit/s",-        )+        if (identity.limits.videoCodecs.isEmpty()) {+            // Not a failure here - CastController names the codecs it checked - but the log is where+            // it would be diagnosed, and "the TV advertised nothing" is invisible otherwise.+            Log.w(TAG, "'${identity.receiverName}' advertised no hardware video decoder at all")+        }+        for (codec in identity.limits.videoCodecs) {+            Log.i(+                TAG,+                "'${identity.receiverName}' decodes ${codec.codec.label} up to " ++                    "${codec.maxWidth}x${codec.maxHeight} @ ${codec.maxFrameRate}fps, " ++                    "${codec.maxBitRate / 1_000_000.0} Mbit/s",+            )+        }          val bundle = ProtocolBase64.decode(identity.publicBundle)             ?: return HandshakeOutcome.Failed(ClientFailure.Protocol)@@ -211,6 +221,7 @@ class MirrorClient(         height: Int,         frameRate: Int,         bitRate: Int,+        videoCodec: VideoCodec,         audio: Boolean,         video: Boolean,         appLabel: String = "",@@ -226,6 +237,7 @@ class MirrorClient(             video = video,             audioSsrc = random.ssrc(StreamConstants.AUDIO_SSRC_MIN, StreamConstants.AUDIO_SSRC_MAX),             videoSsrc = random.ssrc(StreamConstants.VIDEO_SSRC_MIN, StreamConstants.VIDEO_SSRC_MAX),+            videoCodec = videoCodec,             appLabel = appLabel,         )         socket.send(config)@@ -235,23 +247,42 @@ class MirrorClient(             Log.w(TAG, "the TV named udp port ${ready.udpPort}")             return HandshakeOutcome.Failed(ClientFailure.StreamRefused)         }-        Log.i(TAG, "streaming ${width}x$height to udp ${ready.udpPort}")+        Log.i(TAG, "streaming ${videoCodec.label} ${width}x$height to udp ${ready.udpPort}")         return HandshakeOutcome.Ready(Negotiation.of(config, ready, sessionKeys))     } +    /**+     * Hand the TV the video codec configuration, for a codec that cannot carry it in-band.+     *+     * Sent on the already-open control channel rather than in a media packet, because the receiver+     * needs it *before* it configures its decoder - there is no frame yet to attach it to. Called+     * repeatedly and idempotent: every key-frame request re-sends it, which is what gives it a repair+     * path at all.+     */+    fun sendCodecConfig(csd: ByteArray) {+        Log.i(TAG, "sending codec config: ${csd.size} bytes")+        runCatching { socket.send(VideoCodecConfig(csd = ProtocolBase64.encode(csd))) }+            .onFailure { Log.w(TAG, "could not send the codec config", it) }+    }+     /**      * Wait for the TV to say goodbye, or for the socket to die.      *      * 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      * anything.+     *+     * 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.      */-    fun awaitEnd() {+    fun awaitEnd(): String? {         while (true) {-            val next = socket.receive() ?: return-            if (next.message is Bye) {-                Log.i(TAG, "'$receiverName' said goodbye")-                return+            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             }         }     }
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 00a0c0166f..b8d16ac39e 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@@ -3,6 +3,12 @@ package com.vayunmathur.cast.platform.mirror import android.media.MediaCodecInfo import android.media.MediaCodecList import android.media.MediaFormat+import android.util.Log+import com.vayunmathur.cast.protocol.CodecLimits+import com.vayunmathur.cast.protocol.CodecNegotiation+import com.vayunmathur.cast.protocol.VideoCodec++private const val TAG = "EncoderSupport"  /**  * What this device can actually encode.@@ -11,30 +17,95 @@ import android.media.MediaFormat  * pipeline supports, which says nothing about a `MediaCodec` fed by a `VirtualDisplay`. The two  * questions only look alike.  *- * Both answers gate real behaviour rather than being informational: without an H.264 surface- * encoder there is nothing to mirror, and `audio/opus` encoders are genuinely absent on some- * devices, which the UI has to be able to explain.+ * Both answers gate real behaviour rather than being informational: without a hardware surface+ * encoder for H.265 or AV1 there is nothing to mirror, and `audio/opus` encoders are genuinely absent+ * on some devices, which the UI has to be able to explain.+ *+ * **Hardware is a requirement, not a preference.** This used to take the first `MediaCodecList` match+ * for one MIME type, which worked only because every device has a hardware H.264 encoder listed+ * first. With AV1 in the picture that assumption breaks: `c2.android.av1.encoder` is a software codec+ * that publishes a very large envelope, so trusting list order would advertise 1344x2992 realtime+ * from something that cannot do it - and the negotiation would believe it.  */ object EncoderSupport { -    const val VIDEO_MIME = MediaFormat.MIMETYPE_VIDEO_AVC     const val AUDIO_MIME = MediaFormat.MIMETYPE_AUDIO_OPUS +    fun audioEncoderName(): String? {+        val codecs = MediaCodecList(MediaCodecList.REGULAR_CODECS).codecInfos+        return codecs.firstOrNull { info ->+            info.isEncoder &&+                info.supportedTypes.any { it.equals(AUDIO_MIME, ignoreCase = true) } &&+                runCatching { info.getCapabilitiesForType(AUDIO_MIME) }.isSuccess+        }?.name+    }+     /**-     * An H.264 encoder that can take frames from a `Surface`.+     * Every codec this phone has a hardware surface encoder for, as the envelope that encoder+     * advertises.+     *+     * This is one half of what [CodecNegotiation.choose] intersects; the other comes off the wire.+     * An empty list means this device cannot mirror at all, which is a named refusal rather than a+     * fallback - there is no H.264 to drop back to any more.+     */+    fun videoCodecs(): List<CodecLimits> = CodecNegotiation.PREFERENCE.mapNotNull { codec ->+        val info = hardwareSurfaceEncoder(codec) ?: run {+            Log.i(TAG, "no hardware surface encoder for ${codec.label} (${codec.mimeType})")+            return@mapNotNull null+        }+        val video = info.videoCapabilities(codec) ?: return@mapNotNull null+        val limits = runCatching {+            CodecLimits(+                codec = codec,+                maxWidth = video.supportedWidths.upper,+                maxHeight = video.supportedHeights.upper,+                maxFrameRate = video.supportedFrameRates.upper.toInt(),+                maxBitRate = video.bitrateRange.upper,+            )+        }.getOrNull() ?: return@mapNotNull null+        Log.i(+            TAG,+            "${codec.label} encodes up to ${limits.maxWidth}x${limits.maxHeight} @ " ++                "${limits.maxFrameRate}fps, ${limits.maxBitRate / 1_000_000.0} Mbit/s on ${info.name}",+        )+        limits+    }++    /**+     * The hardware encoder [codec] will be instantiated on.      *      * `COLOR_FormatSurface` is the requirement that matters. An encoder that only accepts byte      * buffers would mean reading pixels back from the display and pushing them in by hand, which is      * both slow and pointless when `createInputSurface()` exists.      */-    fun videoEncoderName(): String? = findEncoder(VIDEO_MIME) { caps ->-        caps.colorFormats.contains(MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface)-    }+    fun videoEncoderName(codec: VideoCodec): String? = hardwareSurfaceEncoder(codec)?.name -    fun audioEncoderName(): String? = findEncoder(AUDIO_MIME) { true }+    /**+     * CBR if this encoder advertises it, VBR otherwise.+     *+     * CBR is what makes a screen encoder spend the bitrate it was given - left on VBR, this one+     * answered a 12 Mbit/s target with a measured 4.18 Mbit/s. It is asked for rather than assumed+     * because `configure()` throws on a mode the encoder does not support, and no picture at all+     * would be a worse outcome than a soft one.+     */+    fun videoBitrateMode(codec: VideoCodec, name: String): Int {+        val supported = runCatching {+            MediaCodecList(MediaCodecList.REGULAR_CODECS)+                .codecInfos+                .first { it.name == name }+                .getCapabilitiesForType(codec.mimeType)+                .encoderCapabilities+                ?.isBitrateModeSupported(MediaCodecInfo.EncoderCapabilities.BITRATE_MODE_CBR)+        }.getOrNull() == true+        return if (supported) {+            MediaCodecInfo.EncoderCapabilities.BITRATE_MODE_CBR+        } else {+            MediaCodecInfo.EncoderCapabilities.BITRATE_MODE_VBR+        }+    }      /**-     * Reduce [width] x [height] to something the H.264 encoder will actually accept.+     * Reduce [width] x [height] to something [codec]'s encoder will accept **at [frameRate]**.      *      * 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@@ -42,53 +113,123 @@ object EncoderSupport {      * Rather than let `configure()` throw, the aspect ratio is preserved and the size stepped down      * until the codec agrees.      *+     * **The rate is part of the question, and used not to be.** This asked `isSizeSupported`, which+     * answers only whether the frame fits the envelope - a 4-megapixel portrait frame an encoder will+     * take at 15 fps passes it. Nothing then held the encoder to the 30 fps the handshake had already+     * advertised, so it under-delivered in silence: measured at 11 fps against a negotiated 30. Frame+     * rate is the floor here and resolution is what yields to it.+     *      * 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+    fun clampToEncoder(codec: VideoCodec, width: Int, height: Int, frameRate: Int): Pair<Int, Int> {+        val info = hardwareSurfaceEncoder(codec) ?: return width to height+        val video = info.videoCapabilities(codec) ?: 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-        }+        // **Stepped down, not transposed.** A previous version of this comment claimed it would+        // "believe the transposed limits instead" when an encoder reports only a landscape envelope,+        // which the code never did - and could not: transposing the limits would mean sending a+        // rotated picture, since nothing between here and the TV turns the frame back. Portrait+        // 1344x2992 against a landscape-only envelope therefore rides the ladder down to something+        // that fits, which costs resolution and is logged rather than silent.+        if (video.realtime(width, height, frameRate)) return width to height+        val ceiling = runCatching {+            video.getSupportedFrameRatesFor(width, height).upper+        }.getOrNull()         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+            if (video.realtime(w, h, frameRate)) {+                Log.i(+                    TAG,+                    "${width}x$height tops out at ${ceiling ?: "an unstated rate"}fps on " ++                        "${info.name}; stepping down to ${w}x$h to hold ${frameRate}fps",+                )+                return w to h+            }         }+        // Nothing in the ladder satisfied both. The caller's size is returned rather than a guess,+        // and this line is the only warning that the advertised frame rate is now aspirational.+        Log.w(+            TAG,+            "no size with this aspect ratio does ${frameRate}fps on ${info.name}; " ++                "sending ${width}x$height, which tops out at ${ceiling ?: "an unstated rate"}fps",+        )         return width to height     } +    /**+     * Whether this encoder will do [width] x [height] at [frameRate] *in realtime*.+     *+     * **Performance points where they exist, and `areSizeAndRateSupported` only as a fallback.** The+     * size-and-rate answer is derived from a macroblock-throughput figure, which software codecs+     * publish generously - it is exactly why a software AV1 encoder would say yes to 1344x2992@30.+     * `getSupportedPerformancePoints` is the platform's own statement of what it can sustain, and it+     * compares orientation-independently, so a landscape-only list still covers a portrait frame.+     *+     * A null list is "this codec did not say", which is treated as allowed - the hardware filter has+     * already run by the time anything asks, so the remaining risk is a hardware encoder being+     * refused a size it would in fact have taken.+     */+    private fun MediaCodecInfo.VideoCapabilities.realtime(+        width: Int,+        height: Int,+        frameRate: Int,+    ): Boolean = runCatching {+        val points = supportedPerformancePoints+        if (points.isNullOrEmpty()) {+            areSizeAndRateSupported(width, height, frameRate.toDouble())+        } else {+            val wanted = MediaCodecInfo.VideoCapabilities.PerformancePoint(width, height, frameRate)+            points.any { it.covers(wanted) }+        }+    }.getOrDefault(false)+     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,-        predicate: (MediaCodecInfo.CodecCapabilities) -> Boolean,-    ): String? {+    private fun MediaCodecInfo.videoCapabilities(+        codec: VideoCodec,+    ): MediaCodecInfo.VideoCapabilities? = runCatching {+        getCapabilitiesForType(codec.mimeType).videoCapabilities+    }.getOrNull()++    /**+     * The hardware surface encoder for [codec], or null.+     *+     * **Filtered explicitly and then ranked, rather than taking the first match.** `REGULAR_CODECS`+     * so the list matches what an ordinary app may instantiate; `isHardwareAccelerated` and+     * `!isSoftwareOnly` because a software encoder's advertised envelope is not a promise it can keep+     * at frame rate; and the largest advertised frame wins among what is left, so nothing here+     * depends on the order the platform happens to list its codecs in.+     */+    private fun hardwareSurfaceEncoder(codec: VideoCodec): MediaCodecInfo? {         val codecs = MediaCodecList(MediaCodecList.REGULAR_CODECS).codecInfos-        for (info in codecs) {-            if (!info.isEncoder) continue-            if (info.supportedTypes.none { it.equals(mime, ignoreCase = true) }) continue-            val caps = runCatching { info.getCapabilitiesForType(mime) }.getOrNull() ?: continue-            if (predicate(caps)) return info.name+        return codecs.filter { info ->+            info.isEncoder &&+                info.isHardwareAccelerated &&+                !info.isSoftwareOnly &&+                info.supportedTypes.any { it.equals(codec.mimeType, ignoreCase = true) } &&+                runCatching {+                    val caps = info.getCapabilitiesForType(codec.mimeType)+                    caps.videoCapabilities != null &&+                        caps.colorFormats.contains(+                            MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface,+                        )+                }.getOrDefault(false)+        }.maxByOrNull { info ->+            val video = info.videoCapabilities(codec)+            if (video == null) {+                0L+            } else {+                video.supportedWidths.upper.toLong() * video.supportedHeights.upper+            }         }-        return null     } }
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 39546d17a4..8ddc762061 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@@ -2,6 +2,7 @@ package com.vayunmathur.cast.platform.mirror  import android.content.Context import android.os.ParcelFileDescriptor+import android.os.SystemClock import android.util.Log import android.view.Surface import com.vayunmathur.cast.network.CastUdpTransport@@ -10,6 +11,7 @@ import com.vayunmathur.cast.protocol.Negotiation import com.vayunmathur.cast.protocol.Rtcp import com.vayunmathur.cast.protocol.StreamKind import com.vayunmathur.cast.protocol.StreamingSession+import com.vayunmathur.cast.protocol.VideoCodec import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job@@ -33,6 +35,21 @@ private const val FRAME_POLL_MS = 4L private const val RTCP_POLL_MS = 20L private const val STATS_LOG_INTERVAL_MS = 1_000L +/**+ * 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()`.**+ *+ * A surface-input encoder produces nothing at all until a frame has been drawn into its surface, so a+ * clock started at `start()` would be timing the *content*, not the codec. For screen mirroring that is+ * milliseconds - the `VirtualDisplay` is attached immediately - but a [MirrorSource.Content] session+ * hands its surface out over Binder and the client may legitimately take seconds to draw its first+ * frame, which would fail a perfectly healthy AV1 session and demote AV1 for that TV.+ *+ * Timed from the first frame instead, the condition is the one that is actually wrong: frames are+ * flowing and no configuration came with them.+ */+private const val CODEC_CONFIG_TIMEOUT_MS = 2_000L+ /** What could not be started, so the UI can say so rather than looking broken. */ data class MirrorDegradation(     val videoUnavailable: Boolean = false,@@ -40,7 +57,19 @@ data class MirrorDegradation( )  /** Why mirroring could not start, or stopped. */-enum class MirrorStopReason { Udp, NoEncoders, ReceiverGone }+enum class MirrorStopReason {+    Udp,+    NoEncoders,+    ReceiverGone,++    /**+     * The encoder never produced the codec configuration the chosen codec needs sent out of band.+     *+     * Distinct from [NoEncoders] because the answer is different: the encoder started, so the codec is+     * the thing at fault, and the recovery is to remember that and start the next session at H.265.+     */+    CodecConfig,+}  /**  * The running mirror: capture and encode in, RTP out, RTCP back.@@ -68,10 +97,19 @@ class MirrorEngine(     private val receiverHost: String,     private val negotiation: Negotiation,     private val geometry: CaptureGeometry,+    /** The negotiated codec, chosen against both ends' hardware before the stream was configured. */+    private val videoCodec: VideoCodec,     /** The negotiated frame rate, which is the TV's cap rather than a fixed 30. */     private val frameRate: Int,     private val onDegraded: (MirrorDegradation) -> Unit,     private val onStopped: (MirrorStopReason) -> Unit,+    /**+     * The video codec configuration, to be put on the control channel.+     *+     * Called from the encoder loop when it first appears and from the RTCP loop on every key-frame+     * request, so the implementation has to serialise its own access to the socket.+     */+    private val onCodecConfig: (ByteArray) -> Unit = {}, ) {      private val appContext: Context = context.applicationContext@@ -153,10 +191,12 @@ class MirrorEngine(      private fun startVideo(stream: NegotiatedStream, udp: CastUdpTransport): Boolean {         val encoder = VideoEncoder(+            codec = videoCodec,             width = geometry.width,             height = geometry.height,             frameRate = frameRate,             bitRate = geometry.bitRate,+            onCodecConfig = onCodecConfig,         )         if (!encoder.start()) return false         val surface = encoder.inputSurface@@ -179,7 +219,7 @@ class MirrorEngine(         }         Log.i(             TAG,-            "streaming ${geometry.width}x${geometry.height} " ++            "streaming ${videoCodec.label} ${geometry.width}x${geometry.height} " +                 "@ ${geometry.bitRate / 1_000_000.0} Mbit/s" +                 if (source.appLabel.isEmpty()) "" else " from ${source.appLabel}",         )@@ -187,12 +227,31 @@ class MirrorEngine(         val sender = StreamSender(stream, udp, StreamingSession())         senders[StreamKind.Video] = sender         videoJob = scope.launch {+            // When the encoder first produced anything, which is what the codec-config watchdog is+            // timed from. Zero until then, so a session whose content has not started drawing yet is+            // simply waiting rather than failing.+            var firstOutputAt = 0L             while (isActive) {                 val chunks = encoder.drain()                 if (chunks.isEmpty()) {                     delay(FRAME_POLL_MS)                     continue                 }+                if (firstOutputAt == 0L) firstOutputAt = SystemClock.elapsedRealtime()+                // Checked here rather than in a coroutine of its own, because this loop is already+                // running at frame cadence and the encoder it is draining is the thing being watched.+                if (videoCodec.needsCodecConfig &&+                    !encoder.hasCodecConfig &&+                    SystemClock.elapsedRealtime() - firstOutputAt >= CODEC_CONFIG_TIMEOUT_MS+                ) {+                    Log.w(+                        TAG,+                        "${videoCodec.label} has produced ${CODEC_CONFIG_TIMEOUT_MS}ms of frames " ++                            "and no codec config; the TV can never start its decoder",+                    )+                    onStopped(MirrorStopReason.CodecConfig)+                    return@launch+                }                 for (chunk in chunks) sender.send(chunk)             }         }@@ -275,7 +334,8 @@ class MirrorEngine(                     }                     Log.i(                         TAG,-                        "$summary feedback=$feedbackPackets unmatchedRtcp=$unmatchedPackets",+                        "$summary feedback=$feedbackPackets unmatchedRtcp=$unmatchedPackets " ++                            "sendFailures=${udp.sendFailures}",                     )                 }                 var packet = udp.receive()
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.ktindex a5a1a6c8e4..aafb3ebc95 100644--- a/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorGeometry.kt+++ b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorGeometry.kt@@ -5,8 +5,10 @@ import android.util.DisplayMetrics import android.util.Log import android.view.WindowManager import androidx.core.content.getSystemService-import com.vayunmathur.cast.protocol.DecoderLimits+import com.vayunmathur.cast.protocol.CodecLimits+import com.vayunmathur.cast.protocol.CodecSelection import com.vayunmathur.cast.protocol.StreamConstants+import com.vayunmathur.cast.protocol.VideoCodec  private const val TAG = "MirrorGeometry" @@ -19,7 +21,7 @@ data class CaptureGeometry( )  /**- * Decides what size frame to send, from the TV's own limits.+ * Decides what size frame to send, from the TV's own limits for the codec that was chosen.  *  * **This used to force 1920x1080 landscape, and getting to stop is the clearest single gain from  * owning the receiver.** The old reasoning was sound for a Cast receiver and every part of it is now@@ -33,17 +35,24 @@ data class CaptureGeometry(  *    scaled into a landscape frame here - spending most of the encoded pixels on black bars. Our  *    receiver pads instead, so the phone sends its own shape and every pixel carries picture.  *- * What remains is arithmetic: keep the phone's aspect ratio, fit inside the TV's limits, and round to- * something the encoder will accept.+ * What remains is arithmetic: keep the phone's aspect ratio, fit inside the TV's limits for that+ * codec, and round to something the encoder will accept.  */ object MirrorGeometry {      /**-     * Bits per pixel per second.+     * Bits per pixel per second, **for H.264**, which is now a reference rather than a rate anything+     * is sent at.      *-     * 0.1 bpp at 30 fps is a common screen-sharing figure: screen content is mostly static with sharp-     * edges, so it needs far less than camera video of the same size, but too low a rate makes text-     * unreadable.+     * 0.1 bpp at 30 fps is the common screen-sharing figure, and **0.2 was tried and measured worse.**+     * At native resolution it asks for 24 Mbit/s, which this link answered with 8.5% packet loss - and+     * at ~100 packets per frame, 8.5% loss means almost no frame ever completes, so the picture froze+     * rather than sharpened.+     *+     * It is kept as the reference because it is the figure that was actually measured on this link, and+     * because it makes each codec's [efficiencyFactor] a statement about the codec rather than a magic+     * number. The efficiency is spent on **reliability, not sharpness**: the target comes down per+     * codec instead of staying flat, which is what buys back the packet-loss headroom.      */     private const val BITS_PER_PIXEL = 0.1 @@ -55,32 +64,42 @@ object MirrorGeometry {     private const val DEFAULT_CONTENT_HEIGHT = 720      /**-     * The frame to send to a TV that reported [limits].+     * The phone's real screen size in pixels.      *-     * The phone's real screen shape, scaled down only as far as the TV's limits and this device's own-     * encoder require. [limits] null means the handshake has not happened yet, in which case the-     * phone's native size is used unclamped and the encoder check alone decides.+     * Exposed because codec selection needs it *before* a geometry exists: which codec is viable+     * depends on the frame, and the frame depends on the codec's envelope.      */-    fun forDisplay(context: Context, limits: DecoderLimits? = null): CaptureGeometry {-        val metrics = DisplayMetrics()-        val windowManager = context.getSystemService<WindowManager>()-        @Suppress("DEPRECATION")-        windowManager?.defaultDisplay?.getRealMetrics(metrics)-        val screenWidth = metrics.widthPixels.takeIf { it > 0 } ?: 1080-        val screenHeight = metrics.heightPixels.takeIf { it > 0 } ?: 1920+    fun screenSize(context: Context): Pair<Int, Int> {+        val metrics = displayMetrics(context)+        return (metrics.widthPixels.takeIf { it > 0 } ?: 1080) to+            (metrics.heightPixels.takeIf { it > 0 } ?: 1920)+    } -        val (fittedWidth, fittedHeight) = fitWithin(screenWidth, screenHeight, limits)+    /**+     * The frame to send for the codec [chosen] settled on.+     *+     * The phone's real screen shape, scaled down only as far as the TV's limits for that codec and this+     * device's own encoder require.+     */+    fun forDisplay(context: Context, chosen: CodecSelection.Chosen): CaptureGeometry {+        val metrics = displayMetrics(context)+        val (screenWidth, screenHeight) = screenSize(context)++        val (fittedWidth, fittedHeight) = chosen.receiverLimits.fit(screenWidth, screenHeight)+        val frameRate = frameRateFor(chosen.receiverLimits)         // 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(fittedWidth, fittedHeight)+        // outright rather than rounding for you. The frame rate goes in because it is the floor:+        // resolution is what gets given up to hold it.+        val (width, height) =+            EncoderSupport.clampToEncoder(chosen.codec, fittedWidth, fittedHeight, frameRate) -        val frameRate = frameRateFor(limits)-        val bitRate = bitRateFor(width, height, frameRate, limits)+        val bitRate = bitRateFor(width, height, frameRate, chosen)          Log.i(             TAG,             "sending ${width}x$height @ ${frameRate}fps at ${bitRate / 1_000_000.0} Mbit/s; " +-                "the screen is ${screenWidth}x$screenHeight and the TV will letterbox it",+                "the screen is ${screenWidth}x$screenHeight and the TV will letterbox it" ++                chosen.rateReasoning(),         )         return CaptureGeometry(             width = width,@@ -104,18 +123,19 @@ object MirrorGeometry {     fun forContent(         requestedWidth: Int,         requestedHeight: Int,-        limits: DecoderLimits? = null,+        chosen: CodecSelection.Chosen,     ): CaptureGeometry {         val safeWidth = requestedWidth.takeIf { it > 0 } ?: DEFAULT_CONTENT_WIDTH         val safeHeight = requestedHeight.takeIf { it > 0 } ?: DEFAULT_CONTENT_HEIGHT-        val (fittedWidth, fittedHeight) = fitWithin(safeWidth, safeHeight, limits)-        val (width, height) = EncoderSupport.clampToEncoder(fittedWidth, fittedHeight)-        val frameRate = frameRateFor(limits)-        val bitRate = bitRateFor(width, height, frameRate, limits)+        val (fittedWidth, fittedHeight) = chosen.receiverLimits.fit(safeWidth, safeHeight)+        val frameRate = frameRateFor(chosen.receiverLimits)+        val (width, height) =+            EncoderSupport.clampToEncoder(chosen.codec, fittedWidth, fittedHeight, frameRate)+        val bitRate = bitRateFor(width, height, frameRate, chosen)         Log.i(             TAG,             "app content: asked for ${safeWidth}x$safeHeight, sending ${width}x$height " +-                "@ ${frameRate}fps at ${bitRate / 1_000_000.0} Mbit/s",+                "@ ${frameRate}fps at ${bitRate / 1_000_000.0} Mbit/s" + chosen.rateReasoning(),         )         return CaptureGeometry(             width = width,@@ -125,33 +145,70 @@ object MirrorGeometry {         )     } -    /** The TV's cap, or ours, whichever is lower. */-    fun frameRateFor(limits: DecoderLimits?): Int = minOf(+    /**+     * The TV's cap for the chosen codec, or ours, whichever is lower.+     *+     * A TV that caps out below 30 fps lowers the session rather than being refused - it genuinely+     * cannot go faster, and there is nothing to gain by declining to mirror to it. That is why the+     * floor in `CodecNegotiation.choose` is enforced against the *sender's* envelope only.+     */+    fun frameRateFor(limits: CodecLimits): Int = minOf(         StreamConstants.VIDEO_MAX_FRAME_RATE,-        limits?.maxFrameRate?.takeIf { it > 0 } ?: StreamConstants.VIDEO_MAX_FRAME_RATE,+        limits.maxFrameRate.takeIf { it > 0 } ?: StreamConstants.VIDEO_MAX_FRAME_RATE,     ) -    private fun bitRateFor(width: Int, height: Int, frameRate: Int, limits: DecoderLimits?): Int {-        var bitRate = (width.toLong() * height * frameRate * BITS_PER_PIXEL)+    /**+     * How much of [BITS_PER_PIXEL] each codec actually needs for the same picture.+     *+     * The dial this whole change exists to turn, and it is per codec so it can be tuned without+     * touching selection. At 1344x2992@30 the H.264 reference asks for 12 Mbit/s; these bring that to+     * ~7.2 for H.265 and ~6 for AV1, which is headroom on a link that was losing 8.5% of its packets.+     *+     * Conservative rather than the ~0.5/~0.4 the codecs are usually credited with: the figures are for+     * camera content, and screen content with sharp text is where they hold up least well.+     */+    private fun efficiencyFactor(codec: VideoCodec): Double = when (codec) {+        VideoCodec.Hevc -> 0.6+        VideoCodec.Av1 -> 0.5+    }++    private fun bitRateFor(+        width: Int,+        height: Int,+        frameRate: Int,+        chosen: CodecSelection.Chosen,+    ): Int {+        val factor = efficiencyFactor(chosen.codec)+        var bitRate = (width.toLong() * height * frameRate * BITS_PER_PIXEL * factor)             .toLong()             .coerceAtLeast(MIN_BITRATE.toLong())-        limits?.maxBitRate?.takeIf { it > 0 }?.let { bitRate = minOf(bitRate, it.toLong()) }+        // The tighter of the two ends' ceilings, worked out during selection. Clamping to the TV's+        // alone would let a phone be configured above what its own encoder said it would take.+        chosen.bitRateCeiling.takeIf { it > 0 }?.let { bitRate = minOf(bitRate, it.toLong()) }         return bitRate.toInt()     }      /**-     * The largest frame with the same aspect ratio as [width] x [height] that fits [limits].+     * Why the rate is what it is, in the same line as the rate itself.      *-     * Both dimensions are checked independently, because a TV's limits are not necessarily the same-     * shape as a phone's screen: a 3840x2160 decoder still cannot take a 1440x3120 portrait frame-     * unrotated, and scaling by the tighter of the two ratios is what respects both.+     * All three parts are needed to diagnose an under-spend from one line: [bitRateFor] clamps to the+     * ceiling silently, so a decoder reporting a low `bitrateRange.upper` would make changing either+     * [BITS_PER_PIXEL] or [efficiencyFactor] do nothing at all - and there would be no way to tell that+     * apart from the encoder simply choosing not to spend its allowance.      */-    private fun fitWithin(width: Int, height: Int, limits: DecoderLimits?): Pair<Int, Int> {-        if (limits == null) return width to height-        val maxWidth = limits.maxWidth.takeIf { it > 0 } ?: return width to height-        val maxHeight = limits.maxHeight.takeIf { it > 0 } ?: return width to height-        if (width <= maxWidth && height <= maxHeight) return width to height-        val scale = minOf(maxWidth.toDouble() / width, maxHeight.toDouble() / height)-        return (width * scale).toInt() to (height * scale).toInt()+    private fun CodecSelection.Chosen.rateReasoning(): String =+        "; ${codec.label} at ${efficiencyFactor(codec)}x the H.264 reference" ++            if (bitRateCeiling <= 0) {+                ""+            } else {+                ", under a ${bitRateCeiling / 1_000_000.0} Mbit/s ceiling"+            }++    private fun displayMetrics(context: Context): DisplayMetrics {+        val metrics = DisplayMetrics()+        val windowManager = context.getSystemService<WindowManager>()+        @Suppress("DEPRECATION")+        windowManager?.defaultDisplay?.getRealMetrics(metrics)+        return metrics     } }
cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorPreferences.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorPreferences.kt b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorPreferences.ktindex 6b90d71b11..61befdcf7a 100644--- a/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorPreferences.kt+++ b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorPreferences.kt@@ -2,6 +2,7 @@ package com.vayunmathur.cast.platform.mirror  import com.vayunmathur.cast.domain.CastDevice import android.content.Context+import com.vayunmathur.cast.protocol.VideoCodec import com.vayunmathur.library.util.DataStoreUtils import java.util.UUID @@ -77,5 +78,42 @@ object MirrorPreferences {         DataStoreUtils.getInstance(context).setByteArray(deviceKeyName(receiverId), deviceKey)     } +    /**+     * The codecs that have already failed against [receiverId], so the next session skips them.+     *+     * **This is the recovery path, and it is deliberately not a mid-session renegotiation.** By the+     * time an AV1 failure is visible the codec is baked into `StreamConfig` and the encoder, the+     * `ScreenCapture` and the `VirtualDisplay` are all live; unpicking that safely is a great deal of+     * machinery for something that can be answered by remembering the answer instead. Recorded per TV+     * rather than globally because the failure may be either end's, and a phone that met one bad+     * decoder should not give up AV1 for every TV it ever sees.+     */+    suspend fun demotedCodecs(context: Context, receiverId: String): Set<VideoCodec> {+        val stored = DataStoreUtils.getInstance(context).getStringAwait(demotedName(receiverId))+            ?: return emptySet()+        return stored.split(',')+            .mapNotNull { name -> VideoCodec.entries.firstOrNull { it.name == name } }+            .toSet()+    }++    suspend fun demoteCodec(context: Context, receiverId: String, codec: VideoCodec) {+        val next = demotedCodecs(context, receiverId) + codec+        DataStoreUtils.getInstance(context)+            .setString(demotedName(receiverId), next.joinToString(",") { it.name })+    }++    /**+     * Forget what failed against [receiverId].+     *+     * Called on a fresh code pairing, which is the one point at which the TV might genuinely be a+     * different box - and the only reset a user can reach without a setting nobody would find. Without+     * it a single transient failure would pin a pairing to H.265 for good.+     */+    suspend fun clearDemotedCodecs(context: Context, receiverId: String) {+        DataStoreUtils.getInstance(context).setString(demotedName(receiverId), "")+    }+     private fun deviceKeyName(receiverId: String): String = "cast_paired_$receiverId"++    private fun demotedName(receiverId: String): String = "cast_demoted_codecs_$receiverId" }
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 6d2caa43c5..41afc79e25 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@@ -10,6 +10,7 @@ import com.vayunmathur.cast.protocol.Recovery import com.vayunmathur.cast.protocol.Retransmission import com.vayunmathur.cast.protocol.RtpPacketizer import com.vayunmathur.cast.protocol.StreamingSession+import java.util.concurrent.locks.LockSupport  /**  * One stream's send path: encrypt, packetize, count.@@ -106,10 +107,26 @@ class StreamSender(     /** [packetIds] null means every packet of the frame; otherwise only those listed. */     private fun emit(frame: EncryptedFrame, packetIds: List<Int>?) {         val packets = packetizer.packetize(frame)+        // **Paced, not dumped.** A key frame at native resolution is a few hundred packets, and+        // handing them to the kernel in one tight loop overruns the send buffer, the Wi-Fi driver's+        // queue, or the receiver's - and an overrun drops the packets at the front of the burst,+        // which are the ones carrying the parameter sets. Small frames, and every audio frame, are+        // one burst and never pause.+        val paced = packets.size > BURST_PACKETS+        var sinceRest = 0         var sent = 0L         var octets = 0L         packets.forEachIndexed { index, packet ->             if (packetIds != null && index !in packetIds) return@forEachIndexed+            if (paced && sinceRest == BURST_PACKETS) {+                sinceRest = 0+                // Blocking, and deliberately so: this runs under [lock], which the RTP sequence+                // counter needs held for the whole frame. The caller is a coroutine on the IO+                // dispatcher, where parking a thread for a fraction of a millisecond is what that+                // dispatcher is for.+                LockSupport.parkNanos(BURST_PAUSE_NANOS)+            }+            sinceRest++             // 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)) {@@ -119,6 +136,20 @@ class StreamSender(         }         stats = stats.copy(packets = stats.packets + sent, octets = stats.octets + octets)     }++    private companion object {+        /**+         * Packets per burst, and how long to rest between them.+         *+         * 8 packets is about 12 KB - well inside any send buffer - and 500 us between bursts+         * spreads a 300-packet IDR across roughly 20 ms, so it arrives over most of a frame interval+         * instead of instantaneously. Both are pacing hints rather than a rate limit:+         * [LockSupport.parkNanos] may return early, and the only cost of that is less pacing than+         * intended.+         */+        const val BURST_PACKETS = 8+        const val BURST_PAUSE_NANOS = 500_000L+    } }  /** What a sender report reports. */
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 e49d500294..cede89b541 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@@ -2,14 +2,27 @@ package com.vayunmathur.cast.platform.mirror  import android.media.MediaCodec import android.media.MediaFormat+import android.os.SystemClock import android.util.Log import android.view.Surface+import com.vayunmathur.cast.protocol.VideoCodec import java.nio.ByteBuffer  private const val TAG = "VideoEncoder"  private const val TIMEOUT_US = 10_000L +/**+ * The most often a key frame may be asked for.+ *+ * While the receiver has no decoder it PLIs every feedback round - every 50 ms - and each request+ * resets [VideoEncoder.sentParameterSets] and demands an IDR, so the sender emitted back-to-back key+ * frames at native resolution that the receiver then threw away for want of a surface. AV1's extra+ * startup gate widens that window, which is what turns a pre-existing waste into a real one. Long+ * enough to stop the storm, short enough that a genuine loss is still repaired within a few frames.+ */+private const val KEY_FRAME_MIN_INTERVAL_MS = 400L+ /** One encoded access unit, straight off the codec. */ data class EncodedChunk(     val data: ByteArray,@@ -31,7 +44,7 @@ data class EncodedChunk( }  /**- * H.264 encoder fed by a `Surface`, producing raw access units.+ * An H.265 or AV1 encoder fed by a `Surface`, producing raw access units.  *  * The drain-loop shape is borrowed from `camera/.../MotionPhotoEncoder.kt`, with two inversions  * that matter:@@ -39,43 +52,68 @@ data class EncodedChunk(  *  - **It never touches pixels.** [inputSurface] is handed to a `VirtualDisplay`, which writes into  *    it directly, so there is no input-buffer queueing and no `fillI420` colour conversion.  *  - **It keeps `BUFFER_FLAG_CODEC_CONFIG`.** `MotionPhotoEncoder` discards it because `MediaMuxer`- *    writes SPS/PPS into the container itself. There is no container here, so the parameter sets are- *    cached and prepended to the first IDR - a receiver handed an IDR with no SPS/PPS shows nothing- *    at all, and shows it silently.+ *    writes the parameter sets into the container itself. There is no container here, so they are+ *    cached - a receiver handed a key frame with no parameter sets shows nothing at all, and shows it+ *    silently.+ *+ * **Where those cached bytes go depends on the codec, and that is the one genuinely per-codec branch+ * in this class.** H.265's VPS/SPS/PPS are Annex-B units, so they are prepended to the first key+ * frame exactly as H.264's were. AV1's are a sequence header the decoder wants as `csd-0` before it+ * is configured at all, so they cannot ride in the stream - they go out through [onCodecConfig] on the+ * control channel instead.  */ class VideoEncoder(+    private val codec: VideoCodec,     private val width: Int,     private val height: Int,     private val frameRate: Int,     private val bitRate: Int,+    /**+     * The codec configuration, for a codec that cannot carry it in-band.+     *+     * Called from the encoder loop when the bytes first appear, and again from the RTCP loop on every+     * [requestKeyFrame] - so the implementation has to be safe from both, and is expected to be+     * cheap: it is on the path of a repair.+     */+    private val onCodecConfig: (ByteArray) -> Unit = {}, ) { -    private var codec: MediaCodec? = null+    private var mediaCodec: MediaCodec? = null     private val bufferInfo = MediaCodec.BufferInfo() +    /** The parameter sets, cached from the codec-config buffer. */+    @Volatile+    private var parameterSets: ByteArray? = null+     /**-     * SPS/PPS, cached from the codec-config buffer and prepended to the first key frame.+     * Whether the current key-frame generation has had its parameter sets prepended already.      *-     * [sentParameterSets] is volatile because [requestKeyFrame] runs on the RTCP loop while [drain]+     * **Meaningful only for a codec that carries them in-band**, i.e. H.265. For AV1 nothing reads it,+     * because the bytes never travel with a frame; it is left alone rather than special-cased so the+     * latch has one meaning. 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 +    @Volatile+    private var lastKeyFrameRequestMs = 0L++    /** True once the codec has produced its configuration, for the caller's own startup watchdog. */+    val hasCodecConfig: Boolean get() = parameterSets != null+     var inputSurface: Surface? = null         private set      /** False when the device has no usable surface encoder, which is not recoverable. */     fun start(): Boolean {-        val name = EncoderSupport.videoEncoderName()+        val name = EncoderSupport.videoEncoderName(codec)         if (name == null) {-            Log.w(TAG, "no ${EncoderSupport.VIDEO_MIME} encoder taking COLOR_FormatSurface")+            Log.w(TAG, "no hardware ${codec.mimeType} encoder taking COLOR_FormatSurface")             return false         }         return try {-            val format = MediaFormat.createVideoFormat(EncoderSupport.VIDEO_MIME, width, height)+            val format = MediaFormat.createVideoFormat(codec.mimeType, width, height)                 .apply {                     setInteger(                         MediaFormat.KEY_COLOR_FORMAT,@@ -97,19 +135,25 @@ class VideoEncoder(                         MediaFormat.KEY_REPEAT_PREVIOUS_FRAME_AFTER,                         1_000_000L / frameRate,                     )+                    // **CBR where the encoder offers it, not VBR.** With VBR this encoder answered a+                    // 12 Mbit/s target with a measured 4.18 Mbit/s: it read a mostly-static screen as+                    // cheap and did not spend the allowance, which is what the bleeding around text+                    // was. Screen content is where VBR's judgement is worst - flat regions cost+                    // nothing, and the sharp edges that need the bits get averaged away with them.                     setInteger(                         MediaFormat.KEY_BITRATE_MODE,-                        android.media.MediaCodecInfo.EncoderCapabilities.BITRATE_MODE_VBR,+                        EncoderSupport.videoBitrateMode(codec, name),                     )                 }             val created = MediaCodec.createByCodecName(name)             created.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE)             inputSurface = created.createInputSurface()             created.start()-            codec = created+            mediaCodec = created+            Log.i(TAG, "encoding ${codec.label} at ${width}x$height @ ${frameRate}fps on $name")             true         } catch (e: Exception) {-            Log.w(TAG, "could not start the video encoder", e)+            Log.w(TAG, "could not start the ${codec.label} encoder", e)             release()             false         }@@ -122,7 +166,7 @@ class VideoEncoder(      * even when the encoder has produced nothing.      */     fun drain(): List<EncodedChunk> {-        val active = codec ?: return emptyList()+        val active = mediaCodec ?: return emptyList()         val out = mutableListOf<EncodedChunk>()         while (true) {             val index = try {@@ -136,17 +180,20 @@ class VideoEncoder(             if (buffer != null && bufferInfo.size > 0) {                 val bytes = buffer.readChunk()                 if (bufferInfo.flags and MediaCodec.BUFFER_FLAG_CODEC_CONFIG != 0) {-                    // Not a frame: the parameter sets, which must lead the first IDR.-                    parameterSets = bytes+                    onCodecConfigBuffer(bytes)                 } else {                     val isKeyFrame =                         bufferInfo.flags and MediaCodec.BUFFER_FLAG_KEY_FRAME != 0-                    val payload = if (isKeyFrame && !sentParameterSets) {-                        sentParameterSets = true-                        (parameterSets ?: ByteArray(0)) + bytes-                    } else {-                        bytes-                    }+                    // Prepended only for a codec whose parameter sets belong in the stream. AV1's are+                    // already on their way over the control channel, and putting them here as well+                    // would hand the decoder bytes it has been configured to expect elsewhere.+                    val payload =+                        if (isKeyFrame && !sentParameterSets && !codec.needsCodecConfig) {+                            sentParameterSets = true+                            (parameterSets ?: ByteArray(0)) + bytes+                        } else {+                            bytes+                        }                     out += EncodedChunk(payload, bufferInfo.presentationTimeUs, isKeyFrame)                 }             }@@ -159,9 +206,19 @@ class VideoEncoder(      *      * Called when RTCP feedback says a receiver has fallen further behind than the retransmit      * buffer can repair, which is the only way it can recover.+     *+     * **Rate-limited**, because a receiver with nowhere to draw asks on every feedback round and each+     * answer is a key frame at native resolution that it then discards. See+     * [KEY_FRAME_MIN_INTERVAL_MS].      */     fun requestKeyFrame() {-        val active = codec ?: return+        val active = mediaCodec ?: return+        // Monotonic, not wall clock: a backwards time adjustment would make the interval negative and+        // suppress every later request - including the AV1 codec-config re-send below, which is the+        // only repair path there is for it.+        val now = SystemClock.elapsedRealtime()+        if (now - lastKeyFrameRequestMs < KEY_FRAME_MIN_INTERVAL_MS) return+        lastKeyFrameRequestMs = now         runCatching {             active.setParameters(                 android.os.Bundle().apply {@@ -169,22 +226,48 @@ class VideoEncoder(                 },             )         }.onFailure { Log.w(TAG, "could not request a key frame", it) }-        // The new IDR needs SPS/PPS in front of it too: a receiver asking for a key frame is one-        // that may never have seen the originals.+        // The new key frame needs its parameter sets in front of it too: a receiver asking for one is+        // a receiver that may never have seen the originals.         sentParameterSets = false+        // And for a codec that cannot carry them in-band, "in front of it" means the control channel.+        // This is the whole repair path for AV1 - `CODEC_CONFIG` is emitted once per encoder, with its+        // first output, so a single-shot delivery that was lost would be a black screen for the rest of+        // the session.+        if (codec.needsCodecConfig) parameterSets?.let(onCodecConfig)     }      fun release() {-        runCatching { codec?.stop() }-        runCatching { codec?.release() }+        runCatching { mediaCodec?.stop() }+        runCatching { mediaCodec?.release() }         runCatching { inputSurface?.release() }-        codec = null+        mediaCodec = null         inputSurface = null     } +    /** Not a frame: the parameter sets, cached and - for AV1 - sent on at once. */+    private fun onCodecConfigBuffer(bytes: ByteArray) {+        parameterSets = bytes+        Log.i(+            TAG,+            "${codec.label} codec config: ${bytes.size} bytes, ${bytes.hexPreview()}" ++                if (codec.needsCodecConfig) " - sending it to the TV" else " - riding in-band",+        )+        if (codec.needsCodecConfig) onCodecConfig(bytes)+    }+     private fun ByteBuffer.readChunk(): ByteArray {         position(bufferInfo.offset)         limit(bufferInfo.offset + bufferInfo.size)         return ByteArray(bufferInfo.size).also { get(it) }     } }++/**+ * The first bytes as hex, for a log line.+ *+ * The only way to answer, from a device, whether AV1's codec config arrived as an `av1C`+ * configuration record or as a raw sequence-header OBU - and that question decides whether `csd-0`+ * was the right place to put it. 16 bytes is enough to see the leading marker either way.+ */+internal fun ByteArray.hexPreview(count: Int = 16): String =+    take(count).joinToString(" ") { "%02x".format(it) }
cast/src/main/res/values/strings.xml
diff --git a/cast/src/main/res/values/strings.xml b/cast/src/main/res/values/strings.xmlindex 1fdf08cea0..6948ce7586 100644--- a/cast/src/main/res/values/strings.xml+++ b/cast/src/main/res/values/strings.xml@@ -50,6 +50,14 @@     <string name="cast_mirror_udp_failed">Could not reach the TV to send video</string>     <string name="cast_mirror_no_encoder">This device has no usable screen encoder</string>     <string name="cast_mirror_receiver_gone">The TV stopped accepting the stream</string>+    <!-- Naming the codecs is the point of these three. Mirroring needs hardware H.265 or AV1 and has+         no H.264 fallback, so a device that cannot do either will never work - and a message that did+         not say which codec was missing would leave no way to find that out. -->+    <string name="cast_mirror_phone_no_codec">This phone has no hardware video encoder. Mirroring needs %1$s.</string>+    <string name="cast_mirror_tv_no_codec">This TV has no hardware video decoder. Mirroring needs %1$s.</string>+    <string name="cast_mirror_no_common_codec">This phone can send %1$s and this TV can decode %2$s, but nothing they share works at this screen size.</string>+    <string name="cast_mirror_codec_demoted">%1$s did not work with this TV before, and there is no other codec you both support. Pair with this TV again to retry it.</string>+    <string name="cast_mirror_codec_config_failed">The TV could not be given the video settings it needed. The next attempt will use a different codec.</string>      <!-- Quick Settings tile -->     <string name="cast_tile_label">Mirror screen</string>
cast/tv/build.gradle.kts
diff --git a/cast/tv/build.gradle.kts b/cast/tv/build.gradle.ktsindex 7d72353110..b77d17b430 100644--- a/cast/tv/build.gradle.kts+++ b/cast/tv/build.gradle.kts@@ -11,6 +11,12 @@ launcherIcon {     symbol = "cast" } +// Google TV hardware (the onn 4K Streaming Box and friends) runs a 32-bit userspace and+// reports only `armeabi-v7a,armeabi`, so an arm64-only APK is rejected at install time.+nativeAbis {+    armv7 = true+}+ android {     defaultConfig {         applicationId = "com.vayunmathur.cast.tv"
cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/AudioPlayer.kt
diff --git a/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/AudioPlayer.kt b/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/AudioPlayer.ktindex 351894e228..3c2afd5490 100644--- a/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/AudioPlayer.kt+++ b/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/AudioPlayer.kt@@ -28,12 +28,28 @@ private const val TIMEOUT_US = 10_000L  * does not send its codec-config buffer over the wire. So the header is synthesised here from the  * parameters both ends already agree on - they are fixed constants in [StreamConstants], not  * negotiated, which is what makes reconstructing it sound rather than a guess.+ *+ * **A failure here is terminal, and that is the fix for a measured disaster.** [play] used to catch+ * every exception and retry on the next packet, so a codec that entered its released state a few+ * seconds in logged a stack trace per 20 ms packet from then on: 2,634 traces in 38,233 logcat lines+ * in one session, on the thread that has to be reading datagrams. The storm cost more than the lost+ * audio ever did, and it was voluminous enough to evict its own root cause from the log buffer.  */ class AudioPlayer { +    // Volatile so the lifecycle is explicit rather than resting on the loop thread happening to be+    // the only reader: [release] can run while a stale reference is still in a local.+    @Volatile     private var codec: MediaCodec? = null++    @Volatile     private var track: AudioTrack? = null +    /** Once set, this session has no sound and [play] is a no-op. */+    @Volatile+    var failed: Boolean = false+        private set+     /** False when this TV has no Opus decoder, which leaves the picture but no sound. */     fun start(): Boolean {         val name = decoderName()@@ -51,6 +67,9 @@ class AudioPlayer {                 setByteBuffer("csd-0", java.nio.ByteBuffer.wrap(opusIdentificationHeader()))             }             val created = MediaCodec.createByCodecName(name)+            // Published before the AudioTrack is built, because the catch below releases through the+            // fields: a throw from AudioTrack.Builder would otherwise leak a started MediaCodec.+            codec = created             created.configure(format, null, null, 0)             created.start() @@ -78,10 +97,8 @@ class AudioPlayer {                 .setTransferMode(AudioTrack.MODE_STREAM)                 .setPerformanceMode(AudioTrack.PERFORMANCE_MODE_LOW_LATENCY)                 .build()-            output.play()--            codec = created             track = output+            output.play()             true         } catch (e: Exception) {             Log.w(TAG, "could not start audio playback", e)@@ -90,8 +107,14 @@ class AudioPlayer {         }     } -    /** Queue one Opus packet and write out whatever the decoder finished. */+    /**+     * Queue one Opus packet and write out whatever the decoder finished.+     *+     * Called from the socket loop, so the cost of failing has to be bounded: the first exception+     * gives up on audio for the rest of the session rather than being retried per packet.+     */     fun play(data: ByteArray, presentationTimeUs: Long) {+        if (failed) return         val activeCodec = codec ?: return         val activeTrack = track ?: return         try {@@ -117,7 +140,11 @@ class AudioPlayer {                 activeCodec.releaseOutputBuffer(out, false)             }         } catch (e: Exception) {-            Log.w(TAG, "audio playback failed", e)+            // One trace, once. Whatever put the codec in this state will not be undone by the next+            // packet, and a realtime path may not log per packet.+            failed = true+            Log.w(TAG, "audio playback failed for good; the rest of this session is silent", e)+            release()         }     } 
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 3fd4758ed1..21e462e261 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@@ -45,17 +45,17 @@ class MediaReceiver(     val port: Int get() = socket.localPort      init {-        // Bounded so the loop can check for a stop request rather than parking for ever, and so a-        // sender that dies is noticed instead of leaving a thread blocked in recv. This is also the-        // feedback cadence: a timeout is what tells the caller to report.+        // Bounded so the loop can check for a stop request rather than parking for ever, so a sender+        // that dies is noticed instead of leaving a thread blocked in recv, and so the caller gets+   

Diff truncated.