Modern Apps git

← Modern-Apps.git

cast: send a letterboxed 1080p frame and keep a static screen alive

Commit
d283ccc555a0c6cdf80024a4112214230b2a134f
Author
vayun-mathur <[email protected]>
When
2026-08-21 15:16 UTC (3 months ago)
Parents
0462cbd

Diff

cast/src/main/java/com/vayunmathur/cast/network/CastUdpTransport.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/network/CastUdpTransport.kt b/cast/src/main/java/com/vayunmathur/cast/network/CastUdpTransport.ktindex 021699a6ec..127ded99fc 100644--- a/cast/src/main/java/com/vayunmathur/cast/network/CastUdpTransport.kt+++ b/cast/src/main/java/com/vayunmathur/cast/network/CastUdpTransport.kt@@ -2,6 +2,7 @@ package com.vayunmathur.cast.network  import android.util.Log import java.net.InetSocketAddress+import java.net.PortUnreachableException import java.nio.ByteBuffer import java.nio.channels.DatagramChannel @@ -39,6 +40,17 @@ class CastUdpTransport(private val host: String, private val port: Int) {         false     } +    /**+     * True once the receiver's port has answered ICMP "unreachable" repeatedly.+     *+     * On a connected datagram socket that surfaces as [PortUnreachableException] on *send*, which+     * means the receiver closed or never bound its port - so it is a diagnosis, not a transient. One+     * occurrence can happen before the receiver binds, hence the threshold.+     */+    val receiverGone: Boolean get() = unreachableCount >= UNREACHABLE_THRESHOLD++    private var unreachableCount = 0+     fun send(packet: ByteArray): Boolean {         val active = channel ?: return false         if (hexDump) Log.i(TAG, "-> ${packet.size}B ${packet.toHexPreview()}")@@ -46,7 +58,17 @@ class CastUdpTransport(private val host: String, private val port: Int) {             // A non-blocking write can accept fewer bytes than offered when the send buffer is             // full, which for a datagram socket means the packet did not go. Reporting it as sent             // would inflate the sender report and skew the receiver's loss estimate.-            active.write(ByteBuffer.wrap(packet)) == packet.size+            val wrote = active.write(ByteBuffer.wrap(packet)) == packet.size+            unreachableCount = 0+            wrote+        } catch (e: PortUnreachableException) {+            // Counted rather than logged per packet: at 30 fps this would be thousands of identical+            // stack traces, which buries whatever else the log had to say.+            unreachableCount+++            if (unreachableCount == UNREACHABLE_THRESHOLD) {+                Log.w(TAG, "$host:$port is unreachable - the receiver closed its socket")+            }+            false         } catch (e: Exception) {             Log.w(TAG, "udp send failed", e)             false@@ -80,5 +102,8 @@ class CastUdpTransport(private val host: String, private val port: Int) {      private companion object {         const val MAX_DATAGRAM = 2048++        /** One unreachable reply can precede the receiver binding; a run of them cannot. */+        const val UNREACHABLE_THRESHOLD = 30     } }
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 12d535211a..205bb50d5b 100644--- a/cast/src/main/java/com/vayunmathur/cast/platform/CastController.kt+++ b/cast/src/main/java/com/vayunmathur/cast/platform/CastController.kt@@ -329,6 +329,7 @@ object CastController {                 MirrorStopReason.Udp -> R.string.cast_mirror_udp_failed                 MirrorStopReason.NoEncoders -> R.string.cast_mirror_no_encoder                 MirrorStopReason.NoAudioForSpeaker -> R.string.cast_mirror_no_audio+                MirrorStopReason.ReceiverGone -> R.string.cast_mirror_receiver_gone             },         )         _mirrorPhase.value = MirrorPhase.Failed
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 c64048e2cf..603451d785 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@@ -40,7 +40,7 @@ data class MirrorDegradation( )  /** Why mirroring could not start, or stopped. */-enum class MirrorStopReason { Udp, NoEncoders, NoAudioForSpeaker }+enum class MirrorStopReason { Udp, NoEncoders, NoAudioForSpeaker, ReceiverGone }  /**  * The running mirror: capture and encode in, RTP out, RTCP back.@@ -235,6 +235,14 @@ class MirrorEngine(                     handleFeedback(packet)                     packet = udp.receive()                 }+                // A receiver whose port has gone unreachable is not coming back, and spinning at it+                // forever hides the failure from the user behind a notification that says+                // "Mirroring your screen".+                if (udp.receiverGone) {+                    Log.w(TAG, "the receiver stopped listening; ending the mirror")+                    onStopped(MirrorStopReason.ReceiverGone)+                    return@launch+                }                 delay(RTCP_POLL_MS)             }         }
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 06b0715348..3c00b29cfb 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@@ -9,7 +9,7 @@ import com.vayunmathur.cast.domain.streaming.StreamSelection  private const val TAG = "MirrorGeometry" -/** The capture size, the density to mirror at, and the bitrate that size needs. */+/** The frame size to encode, the density to mirror at, and the bitrate that size needs. */ data class CaptureGeometry(     val width: Int,     val height: Int,@@ -18,64 +18,67 @@ data class CaptureGeometry( )  /**- * Decides what size to capture the screen at.+ * Decides what size frame to send.  *- * Separate from [ScreenCapture] because the answer is needed **before** the OFFER goes out: the- * OFFER advertises a `resolutions` list, and a receiver told to expect one shape while being sent- * another has been misinformed. It needs no projection, only display metrics, so it runs before- * consent is even asked for.+ * Needed **before** the OFFER, which advertises a `resolutions` list - a receiver told to expect one+ * shape and sent another has been misinformed. It needs no projection, only display metrics.  *- * The screen's **native resolution** is used, not a downscale. The receiver answers- * `scaling: "sender"` against its own (often 4K) panel, so it will not letterbox for us and sending- * fewer pixels than the phone has just throws detail away for nothing. The only reason to reduce it- * is an encoder that refuses the size, which is what [EncoderSupport.clampToEncoder] handles.+ * **A landscape frame, not the phone's native portrait one.** Three reasons, learned the hard way:+ *+ *  1. Chrome caps mirroring at 1920x1080 (`kMaxResolution` in `mirror_settings.cc`) and never sends+ *     a phone's native resolution. A modern phone screen is around 4 megapixels and, in portrait,+ *     nearly 3000 pixels tall - a shape TV H.264 decoders are not obliged to accept and in practice+ *     often refuse, which shows up as a receiver that goes quiet and closes its socket.+ *  2. The receiver answers `scaling: "sender"`, meaning it will *not* letterbox for us. Sending a+ *     tall narrow frame to a 16:9 panel is therefore our problem to solve, not its.+ *  3. `VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR` already solves it: given a landscape display it scales the+ *     phone screen to fit and pads the sides, which is exactly what mirroring to a TV should look+ *     like. No compositing code required.  */ object MirrorGeometry { +    /** `kMaxResolution` from Chrome's `mirror_settings.cc`. */+    private const val FRAME_WIDTH = 1920+    private const val FRAME_HEIGHT = 1080+     /**      * Bits per pixel per second.      *-     * 0.1 bpp at 30 fps is a common desktop-sharing figure - screen content is mostly static with-     * sharp edges, so it needs far less than camera video at the same size but punishes a bitrate-     * too low to keep text legible. On a 1344x2992 phone this lands near 12 Mbit/s.+     * 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. At 1080p this lands near 6 Mbit/s, close to Chrome's 5 Mbit/s start rate.      */     private const val BITS_PER_PIXEL = 0.1 -    /** openscreen's `kDefaultVideoMinBitRate`, as a floor for a very small display. */+    /** openscreen's `kDefaultVideoMinBitRate`, as a floor. */     private const val MIN_BITRATE = 300_000 -    /**-     * Above this a phone encoder starts dropping frames rather than degrading quality, and a home-     * network starts losing packets. Not a resolution limit - only a rate one.-     */-    private const val MAX_BITRATE = 20_000_000-     fun forDisplay(context: Context): CaptureGeometry {         val metrics = DisplayMetrics()         val windowManager = context.getSystemService<WindowManager>()         @Suppress("DEPRECATION")         windowManager?.defaultDisplay?.getRealMetrics(metrics)-        val realWidth = metrics.widthPixels.takeIf { it > 0 } ?: 1080-        val realHeight = metrics.heightPixels.takeIf { it > 0 } ?: 1920         // 4:2:0 chroma subsampling cannot represent an odd width or height, and some encoders fail         // outright rather than rounding for you.-        val (width, height) = EncoderSupport.clampToEncoder(realWidth.even(), realHeight.even())+        val (width, height) = EncoderSupport.clampToEncoder(FRAME_WIDTH, FRAME_HEIGHT)         val bitRate = (             width.toLong() * height * StreamSelection.VIDEO_MAX_FRAME_RATE * BITS_PER_PIXEL             )             .toLong()-            .coerceIn(MIN_BITRATE.toLong(), MAX_BITRATE.toLong())+            .coerceAtLeast(MIN_BITRATE.toLong())             .toInt()-        if (width != realWidth || height != realHeight) {-            Log.i(TAG, "capturing at ${width}x$height rather than ${realWidth}x$realHeight")-        }+        Log.i(+            TAG,+            "sending ${width}x$height at ${bitRate / 1_000_000.0} Mbit/s; " ++                "the ${metrics.widthPixels}x${metrics.heightPixels} screen is letterboxed into it",+        )         return CaptureGeometry(             width = width,             height = height,+            // The phone's own density, so text scales the way it does on the screen rather than+            // being rendered for a notional 1080p tablet.             densityDpi = metrics.densityDpi.takeIf { it > 0 } ?: DisplayMetrics.DENSITY_DEFAULT,             bitRate = bitRate,         )     }--    private fun Int.even(): Int = this / 2 * 2 }
cast/src/main/java/com/vayunmathur/cast/platform/mirror/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 93a1500281..e49d500294 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@@ -86,6 +86,17 @@ class VideoEncoder(                     // One second. A receiver that joins or loses sync recovers at the next IDR, and                     // the RTCP path can ask for one sooner when it actually needs it.                     setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 1)+                    // **Load-bearing for screen capture.** A VirtualDisplay only hands the encoder a+                    // buffer when the screen content changes, so a phone sitting on a static screen+                    // produces no frames at all - the stream simply stops, and a receiver watching a+                    // stream that has stopped concludes the sender is gone and tears the session+                    // down. This tells the encoder to re-emit the previous frame if nothing new has+                    // arrived, which keeps a steady frame rate for free: an unchanged frame codes to+                    // almost nothing.+                    setLong(+                        MediaFormat.KEY_REPEAT_PREVIOUS_FRAME_AFTER,+                        1_000_000L / frameRate,+                    )                     setInteger(                         MediaFormat.KEY_BITRATE_MODE,                         android.media.MediaCodecInfo.EncoderCapabilities.BITRATE_MODE_VBR,
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 ef6a1ebab0..f87487fdb9 100644--- a/cast/src/main/res/values/strings.xml+++ b/cast/src/main/res/values/strings.xml@@ -44,6 +44,7 @@     <string name="cast_mirror_udp_failed">Could not reach the device to send video</string>     <string name="cast_mirror_no_encoder">This device has no usable screen encoder</string>     <string name="cast_mirror_no_audio">Audio could not be captured, and this device can only play audio</string>+    <string name="cast_mirror_receiver_gone">The device stopped accepting the stream</string>      <!-- Quick Settings tile -->     <string name="cast_tile_label">Mirror screen</string>