Modern Apps git

← Modern-Apps.git

cast: fix an opaque overlay, a leaked gain and a shared history position

Commit
9c8fe3e5c48ed906cf8bb331c31c290394d30995
Author
vayun-mathur <[email protected]>
When
2026-08-23 07:35 UTC (3 months ago)
Parents
e862073

Diff

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 8546742c63..d158dc8408 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@@ -142,7 +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 = video.sustainableFrameRate(width, height).takeIf { it > 0 }+        val ceiling = video.sustainableFrameRate(width, height)         var scale = 1.0         repeat(MAX_CLAMP_STEPS) {             scale *= CLAMP_STEP@@ -152,7 +152,7 @@ object EncoderSupport {             if (video.realtime(w, h, frameRate)) {                 Log.i(                     TAG,-                    "${width}x$height tops out at ${ceiling ?: "an unstated rate"}fps on " ++                    "${width}x$height tops out at ${ceiling}fps on " +                         "${info.name}; stepping down to ${w}x$h to hold ${frameRate}fps",                 )                 return w to h@@ -163,7 +163,7 @@ object EncoderSupport {         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",+                "sending ${width}x$height, which tops out at ${ceiling}fps",         )         return width to height     }
cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverController.kt
diff --git a/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverController.kt b/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverController.ktindex 20c61cc9dc..4c62163db3 100644--- a/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverController.kt+++ b/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverController.kt@@ -219,7 +219,21 @@ object ReceiverController {         advertiser = null         runCatching { serverSocket?.close() }         serverSocket = null-        _state.update { it.copy(phase = ReceiverPhase.Starting, playback = null) }+        forgetPlayback()+        _state.update { it.copy(phase = ReceiverPhase.Starting) }+    }++    /**+     * Drop everything the last session said about playback.+     *+     * Both halves together, always: clearing [ReceiverUiState.playback] is what takes the overlay away,+     * and resetting [castVolume] is what stops the *next* session inheriting this one's gain. Missing+     * the second is a quiet, nasty failure - a screen-mirroring session that follows a quiet cast would+     * play at that gain for ever, with no snapshot to change it and `nudgeVolume` declining to try.+     */+    private fun forgetPlayback() {+        castVolume = 1f+        _state.update { it.copy(playback = null) }     }      /** Called by `MirrorActivity` once its `SurfaceView` has a surface to draw into. */@@ -284,11 +298,12 @@ object ReceiverController {             // A failure from the previous session has been on screen long enough; the phone connecting             // now is what the user cares about. The previous session's playback goes with it, or the             // next phone would inherit a seek bar describing something that is no longer playing.+            forgetPlayback()             _state.update {                 if (it.phase is ReceiverPhase.Failed) {-                    it.copy(phase = ReceiverPhase.Advertising, playback = null)+                    it.copy(phase = ReceiverPhase.Advertising)                 } else {-                    it.copy(playback = null)+                    it                 }             }             [email protected] = channel@@ -301,6 +316,7 @@ object ReceiverController {                     channel.close()                     [email protected] = null                     endMedia()+                    forgetPlayback()                     // A failure the user has to read is *not* overwritten with "ready" - it stays until                     // the next phone tries, which is when it stops being the useful thing to show.                     if (scope.isActive) {@@ -311,9 +327,6 @@ object ReceiverController {                                 it.copy(                                     phase = ReceiverPhase.Advertising,                                     localNetworkBlocked = nsd.localNetworkBlocked,-                                    // The overlay is gated on this being non-null, so clearing it is-                                    // what takes the transport controls away with the session.-                                    playback = null,                                 )                             }                         }
cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/ReceiverContent.kt
diff --git a/cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/ReceiverContent.kt b/cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/ReceiverContent.ktindex 8d54547e4e..b97fe7c3d4 100644--- a/cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/ReceiverContent.kt+++ b/cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/ReceiverContent.kt@@ -1,5 +1,6 @@ package com.vayunmathur.cast.tv.ui +import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize@@ -36,13 +37,19 @@ import com.vayunmathur.cast.tv.platform.ReceiverUiState  * whose entire job is to show one sentence was furniture; the ten-foot rule is that everything on  * screen should be worth reading from a sofa.  *+ * The background is painted here rather than in `CastTvTheme`, because the other thing that theme wraps+ * is an overlay above a decoder surface and must stay transparent.+ *  * Sizes are deliberately large: this is read from across a room, and a pair code the user has to walk  * up to the TV to make out is a pair code that makes the feature feel broken.  */ @Composable fun ReceiverContent(state: ReceiverUiState, modifier: Modifier = Modifier) {     Column(-        modifier = modifier.fillMaxSize().padding(48.dp),+        modifier = modifier+            .fillMaxSize()+            .background(MaterialTheme.colorScheme.background)+            .padding(48.dp),         verticalArrangement = Arrangement.spacedBy(24.dp, Alignment.CenterVertically),         horizontalAlignment = Alignment.CenterHorizontally,     ) {
cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/Theme.kt
diff --git a/cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/Theme.kt b/cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/Theme.ktindex f16a2f6d48..2bb11c1bc7 100644--- a/cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/Theme.kt+++ b/cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/Theme.kt@@ -1,10 +1,6 @@ package com.vayunmathur.cast.tv.ui -import androidx.compose.foundation.background-import androidx.compose.foundation.layout.Box-import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.Composable-import androidx.compose.ui.Modifier import androidx.tv.material3.MaterialTheme import androidx.tv.material3.darkColorScheme @@ -16,16 +12,12 @@ import androidx.tv.material3.darkColorScheme  * has ever wanted a white screen filling a wall in a dim room. The old call site passed  * `darkTheme = true` unconditionally, which was that conclusion reached one argument short.  *- * The background is painted here rather than by a `Surface`, so that a full-bleed decoder surface can- * live under an overlay that draws nothing of its own - the mirror Activity needs transparency above- * the picture, and a themed `Surface` wrapping everything would be an opaque layer in the way.+ * **Paints nothing.** Deliberately not `Surface`, and not a `Box` with the scheme's background either:+ * one of the two things wrapped in this theme is an overlay above a decoder surface, and anything+ * opaque here would be a solid rectangle over the video for the whole session. Screens that want a+ * background say so themselves - see `ReceiverContent`.  */ @Composable fun CastTvTheme(content: @Composable () -> Unit) {-    MaterialTheme(colorScheme = darkColorScheme()) {-        Box(-            modifier = Modifier.fillMaxSize().background(MaterialTheme.colorScheme.background),-            content = { content() },-        )-    }+    MaterialTheme(colorScheme = darkColorScheme(), content = content) }
cast/tv/src/main/res/values/strings.xml
diff --git a/cast/tv/src/main/res/values/strings.xml b/cast/tv/src/main/res/values/strings.xmlindex 38d169bcd0..87c39187b2 100644--- a/cast/tv/src/main/res/values/strings.xml+++ b/cast/tv/src/main/res/values/strings.xml@@ -30,7 +30,6 @@     <!-- Transport overlay, driven from the TV remote -->     <string name="tv_transport_speed">%1$s×</string>     <string name="tv_transport_hint">OK to play or pause · ◀ ▶ to seek · ▲ ▼ for volume</string>-    <string name="tv_transport_volume">Volume %1$d%%</string>      <!-- Foreground service -->     <string name="tv_notification_channel_name">Receiving</string>
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 281c2ee4ac..71b0b87bcd 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/platform/CastPlayback.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/platform/CastPlayback.kt@@ -150,14 +150,33 @@ object CastPlayback {      */     private var audio: AudioManager? = null -    /** Called by the player screen once its `MediaController` has connected, and with null as it goes. */+    /**+     * Called by the player screen once its `MediaController` has connected, and with null as it goes.+     *+     * **Detach is identity-guarded, and has to be.** A navigation composes the incoming screen before+     * disposing the outgoing one, so if the new screen's controller connects first an unguarded+     * `attachPlayer(null)` would clear the player that had just arrived *and* start the orphan timer -+     * ending the cast in exactly the "next from the television" case this whole mechanism exists for.+     */     fun attachPlayer(newPlayer: Player?) {-        player = newPlayer-        if (newPlayer != null) {-            orphanJob?.cancel()-            orphanJob = null+        if (newPlayer == null) {+            detachPlayer(null)             return         }+        player = newPlayer+        orphanJob?.cancel()+        orphanJob = null+    }++    /**+     * Let go of [outgoing], if it is still the attached player.+     *+     * Passing the player being disposed is what makes the guard possible; null means "whatever is+     * attached", which only the session teardown wants.+     */+    fun detachPlayer(outgoing: Player?) {+        if (outgoing != null && player !== outgoing) return+        player = null         if (_state.value !is State.Casting) return         // **The grace period is what lets a cast survive navigation.** Leaving a video used to end the         // session outright, on the reasoning that there is one video output and it cannot follow the@@ -407,7 +426,7 @@ object CastPlayback {      /** The range the phone's own speed menu offers; a TV must not be able to ask for more. */     private const val MIN_SPEED = 0.25f-    private const val MAX_SPEED = 4f+    private const val MAX_SPEED = 2f      /**      * Slow enough not to compete with the encoder for the control socket, fast enough that a seek bar
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 ac01c73ab7..3de0b2c176 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/ui/VideoPlayer.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/ui/VideoPlayer.kt@@ -50,6 +50,7 @@ import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableFloatStateOf+import androidx.compose.runtime.mutableLongStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope@@ -97,6 +98,8 @@ import com.vayunmathur.youpipe.util.PlaybackService import com.vayunmathur.youpipe.util.YouPipeViewModel import kotlinx.coroutines.delay import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.flow.drop+import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import androidx.compose.foundation.Canvas@@ -181,6 +184,13 @@ fun VideoPlayer(     val isDragging = transport.dragging     val playbackSpeed = transport.speed +    // Position and duration for *this* video's history entry, kept per screen rather than read back out+    // of the shared transport state. A video-to-video navigation composes both screens at once, and+    // both see the same singleton - so a shared read would persist the incoming video's progress+    // against the outgoing video's id and lose the user's place in it.+    var historyPosition by remember(videoInfo.videoID) { mutableLongStateOf(0L) }+    var historyDuration by remember(videoInfo.videoID) { mutableLongStateOf(0L) }+     var isVideoMenuExpanded by remember { mutableStateOf(false) }     var isLanguageMenuExpanded by remember { mutableStateOf(false) }     var isChapterMenuVisible by remember { mutableStateOf(false) }@@ -193,16 +203,24 @@ fun VideoPlayer(     var playbackPitch by remember { mutableFloatStateOf(1f) }     var unhookPitch by remember { mutableStateOf(false) } -    // Durable in both directions, and each guarded against the other so they converge rather than-    // ping-pong: the stored value seeds the session - it arrives asynchronously from DataStore, which-    // is why this keys on it rather than running once - and every later change, from this menu or from-    // the TV's remote, is written back so it survives moving to another video.-    val persistedSpeed by ypvm.playbackSpeed.collectAsState()-    LaunchedEffect(persistedSpeed) {-        if (persistedSpeed != playbackSpeed) CastPlayback.update { it.copy(speed = persistedSpeed) }+    // Hooked pitch follows tempo from *any* source, which is why it is an effect rather than a line in+    // the slider's callback: the television can change the tempo too, and a pitch left behind would+    // silently unhook itself without the checkbox moving.+    LaunchedEffect(playbackSpeed, unhookPitch) {+        if (!unhookPitch) playbackPitch = playbackSpeed+    }++    // **Seeded once, then written back one way only.** Following the stored value would mean an echo of+    // an earlier write arriving mid-drag and snapping the slider out from under the thumb, because+    // DataStore answers asynchronously and this cannot tell an echo from a fresh value. `drop(1)` is+    // what waits for storage rather than for the flow's own 1x placeholder; if nothing is stored it+    // never arrives and 1x stands, which is the right answer anyway.+    LaunchedEffect(Unit) {+        val stored = ypvm.playbackSpeed.drop(1).first()+        CastPlayback.update { it.copy(speed = stored) }     }     LaunchedEffect(playbackSpeed) {-        if (playbackSpeed != persistedSpeed) ypvm.setPlaybackSpeed(playbackSpeed)+        ypvm.setPlaybackSpeed(playbackSpeed)     }      // Lock hides all controls (and disables seek/speed gestures) so a fullscreen video can't be@@ -300,7 +318,7 @@ fun VideoPlayer(         player.addListener(listener)         onDispose {             player.removeListener(listener)-            CastPlayback.attachPlayer(null)+            CastPlayback.detachPlayer(player)             context.findActivity().setPictureInPictureParams(PictureInPictureParams.Builder().apply {                 setAutoEnterEnabled(false)             }.build())@@ -327,11 +345,13 @@ fun VideoPlayer(                         bufferedMs = player.bufferedPosition.coerceAtLeast(0L),                     )                 }+                historyPosition = position+                historyDuration = player.duration.coerceAtLeast(0L)                  if (player.isPlaying) {                     val now = System.currentTimeMillis()                     if (now - lastHistoryUpsert >= HISTORY_UPSERT_INTERVAL_MS) {-                        ypvm.upsertHistoryVideo(HistoryVideo.fromVideoData(videoInfo.copy(duration = duration), position))+                        ypvm.upsertHistoryVideo(HistoryVideo.fromVideoData(videoInfo.copy(duration = historyDuration), position))                         lastHistoryUpsert = now                     }                 }@@ -343,7 +363,9 @@ fun VideoPlayer(     // Persist the final watch position once when leaving the player.     DisposableEffect(videoInfo.videoID) {         onDispose {-            ypvm.upsertHistoryVideo(HistoryVideo.fromVideoData(videoInfo.copy(duration = duration), currentPosition))+            ypvm.upsertHistoryVideo(+                HistoryVideo.fromVideoData(videoInfo.copy(duration = historyDuration), historyPosition),+            )         }     } @@ -759,7 +781,6 @@ fun VideoPlayer(                                     value = playbackSpeed,                                     onValueChange = {                                         CastPlayback.update { state -> state.copy(speed = it) }-                                        if (!unhookPitch) playbackPitch = it                                     },                                     valueRange = 0.25f..2f,                                 )@@ -802,7 +823,6 @@ fun VideoPlayer(                                 TextButton(                                     onClick = {                                         CastPlayback.update { it.copy(speed = 1f) }-                                        playbackPitch = 1f                                         unhookPitch = false                                     },                                     modifier = Modifier.align(Alignment.End)