Modern Apps git

← Modern-Apps.git

cast: cast at the video's own resolution, on measured encoder limits

Commit
aa7d13aaff80c7da4fe934e21e168d99f0c455e3
Author
vayun-mathur <[email protected]>
When
2026-08-23 06:45 UTC (3 months ago)
Parents
4418dd8

Diff

cast/src/main/java/com/vayunmathur/cast/platform/CastController.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/platform/CastController.kt b/cast/src/main/java/com/vayunmathur/cast/platform/CastController.ktindex e622fb6239..2a9fd492b6 100644--- a/cast/src/main/java/com/vayunmathur/cast/platform/CastController.kt+++ b/cast/src/main/java/com/vayunmathur/cast/platform/CastController.kt@@ -667,7 +667,8 @@ object CastController {      * 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.+     * TV's own envelope has scaled it - and because this phone's own sustainable frame rate is only+     * meaningful for a stated geometry, which is what [EncoderSupport.videoCodecs] needs them for.      */     private suspend fun chooseCodec(         context: Context,@@ -685,7 +686,7 @@ object CastController {             )         }         val selection = CodecNegotiation.choose(-            senderCodecs = EncoderSupport.videoCodecs(),+            senderCodecs = EncoderSupport.videoCodecs(width, height),             receiver = activeClient.limits ?: DecoderLimits(),             width = width,             height = height,
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 b8d16ac39e..8546742c63 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@@ -41,35 +41,44 @@ object EncoderSupport {     }      /**-     * Every codec this phone has a hardware surface encoder for, as the envelope that encoder-     * advertises.+     * Every codec this phone has a hardware surface encoder for, with each one's frame rate stated+     * **for [width] x [height]** rather than for the easiest frame in its envelope.      *      * 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.+     *+     * **The geometry is a parameter because a rate without one means nothing.**+     * `supportedFrameRates` is the ceiling for the *smallest* frame the encoder accepts: on the+     * Pixel 9 Pro XL AV1 reports 480 there while holding around 10 fps at 4K. Since+     * [CodecNegotiation.choose] enforces the 30 fps floor against this list, an envelope-wide figure+     * meant AV1 was selected for a frame it cannot encode, and all the downstream clamp could do+     * about it was give up resolution instead.      */-    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,+    fun videoCodecs(width: Int, height: Int): 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.sustainableFrameRate(width, height),+                    maxBitRate = video.bitrateRange.upper,+                )+            }.getOrNull() ?: return@mapNotNull null+            Log.i(+                TAG,+                "${codec.label} encodes up to ${limits.maxWidth}x${limits.maxHeight} and holds " ++                    "${limits.maxFrameRate}fps at ${width}x$height, " ++                    "${limits.maxBitRate / 1_000_000.0} Mbit/s on ${info.name}",             )-        }.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-    }+            limits+        }      /**      * The hardware encoder [codec] will be instantiated on.@@ -133,9 +142,7 @@ object EncoderSupport {         // 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()+        val ceiling = video.sustainableFrameRate(width, height).takeIf { it > 0 }         var scale = 1.0         repeat(MAX_CLAMP_STEPS) {             scale *= CLAMP_STEP@@ -164,21 +171,30 @@ object EncoderSupport {     /**      * 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.+     * **Measured rates first, because the advertised ones are optimistic.** This used to argue that+     * `getSupportedPerformancePoints` was the platform's own honest statement of what it could+     * sustain. On the Pixel 9 Pro XL it is not: the performance points put `c2.google.av1.encoder`+     * at 180 fps for 1080p and 60 fps for 4K, while the same device's `measured-frame-rate-*` data+     * says 40 fps at 1080p, which interpolates to around 10 at 4K. `c2.exynos.hevc.encoder` measures+     * 45-54 fps at 4K. AV1 is first in [CodecNegotiation.PREFERENCE], so believing the performance+     * points hands 4K to the one encoder that cannot hold 30 fps at it.+     *+     * So the three tests run in order of how much each was actually measured: [achievableFrameRate],+     * then the performance points, then `areSizeAndRateSupported` - which is derived from a+     * macroblock-throughput figure and is exactly why a software AV1 encoder would say yes to+     * 1344x2992@30.      *-     * 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.+     * **An unmeasured geometry defers to the next test rather than being refused.** Measured data is+     * optional and some encoders publish none at all; treating silence as a no would exclude codecs+     * that are fine. The hardware filter has already run by the time anything asks, so the remaining+     * risk is the mild one - a hardware encoder refused a size it would in fact have taken.      */     private fun MediaCodecInfo.VideoCapabilities.realtime(         width: Int,         height: Int,         frameRate: Int,     ): Boolean = runCatching {+        achievableFrameRate(width, height)?.let { return@runCatching it >= frameRate }         val points = supportedPerformancePoints         if (points.isNullOrEmpty()) {             areSizeAndRateSupported(width, height, frameRate.toDouble())@@ -188,6 +204,43 @@ object EncoderSupport {         }     }.getOrDefault(false) +    /**+     * The rate this encoder holds at [width] x [height], from the most measured source with an+     * answer.+     *+     * [achievableFrameRate] first for the reason [realtime] gives. `getSupportedFrameRatesFor` is+     * next because it is at least size-aware, generous though it is. `supportedFrameRates` is the+     * last resort and is only truthful for very small frames - it is what this used to hand+     * [CodecNegotiation.choose] for every geometry.+     */+    private fun MediaCodecInfo.VideoCapabilities.sustainableFrameRate(+        width: Int,+        height: Int,+    ): Int {+        if (width <= 0 || height <= 0) return supportedFrameRates.upper.toInt()+        achievableFrameRate(width, height)?.let { return it.toInt() }+        runCatching { getSupportedFrameRatesFor(width, height).upper }.getOrNull()?.let {+            return it.toInt()+        }+        return supportedFrameRates.upper.toInt()+    }++    /**+     * What this device *measured* this encoder doing at [width] x [height], or null if it has no+     * measurement to interpolate from.+     *+     * `getAchievableFrameRatesFor` reads the `measured-frame-rate-*` entries of the platform's media+     * codec profile and scales them by block count to sizes that were never measured directly, which+     * is what turns "AV1 manages 40 fps at 1080p" into the ~10 fps it gets at four times the pixels.+     *+     * A throw is the same answer as a null - "no measurement", not "refused" - because a size that+     * genuinely cannot be encoded is still caught by the tests that follow.+     */+    private fun MediaCodecInfo.VideoCapabilities.achievableFrameRate(+        width: Int,+        height: Int,+    ): Double? = runCatching { getAchievableFrameRatesFor(width, height)?.upper }.getOrNull()+     private fun Int.alignedDown(alignment: Int): Int =         if (alignment <= 1) this / 2 * 2 else this / alignment * alignment 
youpipe/src/main/java/com/vayunmathur/youpipe/platform/CastPlayback.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/platform/CastPlayback.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/platform/CastPlayback.ktindex ffcf0280b9..701079da94 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/platform/CastPlayback.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/platform/CastPlayback.kt@@ -49,12 +49,19 @@ object CastPlayback {         /**          * On the TV. [surface] is what the player must render into, and it belongs to Cast - it must          * not be released here, which is what would break the *next* cast rather than this one.+         *+         * [width], [height] and [frameRate] are what Cast **granted**, not what was asked for. They+         * are carried rather than dropped so that a clamp shows up in the log next to the request+         * that provoked it: a session silently downscaled is indistinguishable from one that was+         * never asked for the resolution in the first place, which is how the 1080p cap survived as+         * long as it did.          */         data class Casting(             val surface: Surface,             val receiverName: String,             val width: Int,             val height: Int,+            val frameRate: Int,         ) : State     } @@ -91,11 +98,21 @@ object CastPlayback {                 close()             }             CastAudioTap.attach(session.audio)+            if (session.width != width || session.height != height) {+                Log.i(+                    TAG,+                    "asked ${width}x$height, granted ${session.width}x${session.height} " ++                        "@ ${session.frameRate}fps on '${session.receiverName}'",+                )+            } else {+                Log.i(TAG, "casting ${width}x$height @ ${session.frameRate}fps as asked")+            }             _state.value = State.Casting(                 surface = session.surface,                 receiverName = session.receiverName,                 width = session.width,                 height = session.height,+                frameRate = session.frameRate,             )             null         } catch (e: CastException) {
youpipe/src/main/java/com/vayunmathur/youpipe/ui/VideoPlayer.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/ui/VideoPlayer.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/ui/VideoPlayer.ktindex 73d7ca146d..68a360ec7c 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/ui/VideoPlayer.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/ui/VideoPlayer.kt@@ -402,10 +402,8 @@ fun VideoPlayer(             return@rememberLauncherForActivityResult         }         scope.launch {-            // 1080 tall in the video's own shape: the receiver letterboxes, so the aspect ratio is-            // ours to choose, and Cast clamps whatever the TV cannot decode.-            val requestedWidth = (CAST_REQUEST_HEIGHT * aspectRatio).toInt().coerceAtLeast(2)-            if (CastPlayback.open(context, requestedWidth, CAST_REQUEST_HEIGHT) != null) {+            val (requestedWidth, requestedHeight) = castRequestSize(currentVideoStream, aspectRatio)+            if (CastPlayback.open(context, requestedWidth, requestedHeight) != null) {                 AppMessages.show(castFailedMessage)             }         }@@ -941,13 +939,35 @@ private const val HISTORY_UPSERT_INTERVAL_MS = 5000L private const val CONTROLS_AUTO_HIDE_DELAY_MS = 2000L  /**- * The frame height asked of Cast, with the width taken from the video's own aspect ratio.+ * The fallback frame height asked of Cast, used only when the stream does not report its own size.  *  * A request, not a decision: Cast clamps it to what the TV reported it can decode and to what this  * phone's encoder will take, and answers with the real numbers.  */ private const val CAST_REQUEST_HEIGHT = 1080 +/**+ * The frame size to ask Cast for, taken from the stream that is actually playing.+ *+ * **This used to be `CAST_REQUEST_HEIGHT * aspectRatio` by `CAST_REQUEST_HEIGHT`, which asked for+ * 1920x1080 for every video ever cast.** `aspectRatio` is a ratio: it carries shape and no magnitude,+ * so a 360p stream was asked to fill 1080 lines and a 4K one was thrown away on the way out. The real+ * numbers were in scope at the call site the whole time, and YouPipe deliberately does not filter+ * streams above 1080p, so there was nothing to gain from the cap.+ *+ * **Both dimensions are rounded down to even.** 4:2:0 chroma cannot represent an odd width or height,+ * and several encoders refuse such a size outright rather than rounding it themselves.+ *+ * A stream that reports no size falls back to the old fixed height in the measured aspect ratio -+ * that path is a guess either way, and the receiver letterboxes, so the shape is ours to choose.+ */+private fun castRequestSize(stream: VideoStream, aspectRatio: Float): Pair<Int, Int> {+    if (stream.width > 0 && stream.height > 0) return stream.width.evenDown() to stream.height.evenDown()+    return (CAST_REQUEST_HEIGHT * aspectRatio).toInt().evenDown() to CAST_REQUEST_HEIGHT+}++private fun Int.evenDown(): Int = (this - (this and 1)).coerceAtLeast(2)+ /**  * What the player shows once the video is on the TV.  *