Modern Apps git

← Modern-Apps.git

youpipe: hoist transport state and take commands from the TV

Commit
e7e9d016aa9cc6705977666b4a44a77ce2097fb2
Author
vayun-mathur <[email protected]>
When
2026-08-23 06:56 UTC (3 months ago)
Parents
3becf2f

Diff

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 701079da94..57d600cde5 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/platform/CastPlayback.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/platform/CastPlayback.kt@@ -5,14 +5,28 @@ import android.os.ParcelFileDescriptor import android.util.Log import android.view.Surface import androidx.annotation.OptIn+import androidx.media3.common.Player import androidx.media3.common.util.UnstableApi import androidx.media3.exoplayer.audio.TeeAudioProcessor import com.vayunmathur.sdk.cast.CastClient import com.vayunmathur.sdk.cast.CastContract import com.vayunmathur.sdk.cast.CastException+import com.vayunmathur.sdk.cast.PlaybackAction+import com.vayunmathur.sdk.cast.PlaybackCommand+import com.vayunmathur.sdk.cast.PlaybackState+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Job+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.flow.distinctUntilChanged+import kotlinx.coroutines.flow.map+import kotlinx.coroutines.flow.update+import kotlinx.coroutines.isActive+import kotlinx.coroutines.launch import java.io.FileOutputStream import java.nio.ByteBuffer import java.util.concurrent.ArrayBlockingQueue@@ -68,6 +82,65 @@ object CastPlayback {     private val _state = MutableStateFlow<State>(State.Idle)     val state: StateFlow<State> = _state.asStateFlow() +    /**+     * Where playback is, and everything a remote needs to know about it.+     *+     * **Hoisted out of `VideoPlayer` because a television outlives a composable.** All of this used to+     * be `remember`ed locals, which was correct while the only thing that read them was the UI drawn+     * beside them - the seek bar and the transport buttons are two feet from the player. A TV asking+     * "what is playing, and how far in" is a second reader with a different lifetime, and a+     * `remember` dies on navigation while the cast session does not.+     *+     * The 300 ms poll loop in `VideoPlayer` remains the **single writer** of [positionMs] and+     * [bufferedMs]; the player listener writes the rest. Nothing else may write them, which is what+     * makes [dragging] a sufficient guard.+     */+    data class Transport(+        val positionMs: Long = 0,+        val bufferedMs: Long = 0,+        val durationMs: Long = 0,+        val playing: Boolean = false,+        val buffering: Boolean = false,+        /**+         * The user has the phone's own seek bar under their thumb.+         *+         * Freezes the poll loop's position write so the bar does not fight the finger, and - now that+         * a television can seek too - refuses a remote seek for the same reason. Two seeks resolving+         * against each other would leave the position wherever the loser landed.+         */+        val dragging: Boolean = false,+        val speed: Float = 1f,+        val volume: Float = 1f,+        val hasNext: Boolean = false,+        val hasPrevious: Boolean = false,+    )++    private val _transport = MutableStateFlow(Transport())+    val transport: StateFlow<Transport> = _transport.asStateFlow()++    /** Read-modify-write, so the poll loop and the player listener cannot drop each other's change. */+    fun update(block: (Transport) -> Transport) {+        _transport.update(block)+    }++    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main)++    private var reportJob: Job? = null++    /**+     * The player a remote command is applied to.+     *+     * Held here rather than passed with each command because the commands arrive from Cast, which has+     * no idea what a `MediaController` is. Cleared when the player screen goes away, so a command that+     * outlives it is dropped rather than driving a released controller.+     */+    private var player: Player? = null++    /** Called by the player screen once its `MediaController` has connected, and with null as it goes. */+    fun attachPlayer(newPlayer: Player?) {+        player = newPlayer+    }+     private var client: CastClient? = null      fun support(context: Context): CastClient.Support = CastClient(context).support()@@ -98,6 +171,8 @@ object CastPlayback {                 close()             }             CastAudioTap.attach(session.audio)+            newClient.onCommand = { command -> apply(command) }+            startReporting(newClient)             if (session.width != width || session.height != height) {                 Log.i(                     TAG,@@ -124,11 +199,113 @@ object CastPlayback {      /** Back to playing locally. Idempotent. */     fun close() {+        reportJob?.cancel()+        reportJob = null         CastAudioTap.detach()         client?.close()         client = null         _state.value = State.Idle     }++    /**+     * Keep the TV's copy of [transport] current, for as long as this session lasts.+     *+     * Two cadences, because they answer different needs. Anything the TV *renders* differently goes out+     * the instant it changes - a pause that took half a second to reach the screen reads as a dropped+     * button press. Position is deliberately excluded from that: it moves on every poll, so "changed"+     * would mean "always", and the TV interpolates between snapshots anyway precisely so it does not+     * need them faster.+     *+     * The heartbeat underneath is what makes the whole thing self-repairing: every message is an+     * absolute snapshot, so a lost one costs at most one interval of staleness and needs no+     * acknowledgement, no sequence number and no retry.+     */+    private fun startReporting(activeClient: CastClient) {+        reportJob?.cancel()+        reportJob = scope.launch {+            launch {+                _transport+                    .map { it.copy(positionMs = 0, bufferedMs = 0) }+                    .distinctUntilChanged()+                    .collect { activeClient.reportPlaybackState(_transport.value.asPlaybackState()) }+            }+            while (isActive) {+                delay(HEARTBEAT_MS)+                activeClient.reportPlaybackState(_transport.value.asPlaybackState())+            }+        }+    }++    private fun Transport.asPlaybackState() = PlaybackState(+        positionMs = positionMs,+        durationMs = durationMs,+        playing = playing,+        buffering = buffering,+        speed = speed,+        volume = volume,+        hasNext = hasNext,+        hasPrevious = hasPrevious,+    )++    /**+     * Do what the television's remote asked.+     *+     * Runs on the main thread - `CastClient` guarantees it - because a `MediaController` may only be+     * touched there. Every case drives the same player the phone's own buttons drive, so there is one+     * transport rather than two that could disagree.+     *+     * With no player attached this does nothing at all. That is the correct answer rather than a+     * failure: the user has navigated away from the video, and until the session learns to survive+     * that there is nothing to control.+     */+    private fun apply(command: PlaybackCommand) {+        val target = player ?: return+        when (command.action) {+            PlaybackAction.Play -> target.play()+            PlaybackAction.Pause -> target.pause()+            PlaybackAction.Toggle -> if (target.isPlaying) target.pause() else target.play()+            PlaybackAction.SeekTo -> command.value?.let { seek(target, it.toLong()) }+            PlaybackAction.SkipForward -> seek(target, target.currentPosition + SKIP_MS)+            PlaybackAction.SkipBack -> seek(target, target.currentPosition - SKIP_MS)+            PlaybackAction.SetSpeed -> command.value?.let { speed ->+                // Written into [transport] rather than onto the player: `VideoPlayer` already has an+                // effect that applies the speed together with the pitch, and setting+                // `playbackParameters` here would drop whatever pitch the user had chosen.+                update { it.copy(speed = speed.toFloat().coerceIn(MIN_SPEED, MAX_SPEED)) }+            }+            // Volume and the queue are somebody else's to answer; ignored rather than guessed at.+            PlaybackAction.SetVolume, PlaybackAction.Next, PlaybackAction.Previous -> Unit+        }+    }++    /**+     * Seek, unless the phone's own seek bar is currently under a thumb.+     *+     * The position is written here rather than left to the next poll: the TV re-anchors its estimate on+     * every snapshot, so one still carrying the pre-seek position would visibly pull its bar back+     * before the following tick pushed it forward again.+     */+    private fun seek(target: Player, positionMs: Long) {+        val current = _transport.value+        if (current.dragging) return+        val end = current.durationMs.takeIf { it > 0 } ?: Long.MAX_VALUE+        val clamped = positionMs.coerceIn(0, end)+        target.seekTo(clamped)+        update { it.copy(positionMs = clamped) }+    }++    /** Matches the phone's own skip buttons, so the two remotes move by the same amount. */+    private const val SKIP_MS = 10_000L++    /** 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++    /**+     * Slow enough not to compete with the encoder for the control socket, fast enough that a seek bar+     * re-anchors before its interpolation has drifted anywhere visible.+     */+    private const val HEARTBEAT_MS = 500L }  /**
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 68a360ec7c..8b49ef483f 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/ui/VideoPlayer.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/ui/VideoPlayer.kt@@ -50,7 +50,6 @@ 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@@ -164,14 +163,23 @@ fun VideoPlayer(         currentAudioStream = filtered.maxByOrNull { it.bitrate } ?: filtered.firstOrNull()     }     var isControlsVisible by remember { mutableStateOf(true) }-    var isPlaying by remember { mutableStateOf(false) }     var controlsInteractionTick by remember { mutableStateOf(0) }     val keepControlsVisible by ypvm.keepPlayerControlsVisible.collectAsState()-    var currentPosition by remember { mutableLongStateOf(0L) }-    var bufferedPosition by remember { mutableLongStateOf(0L) }-    var duration by remember { mutableLongStateOf(0L) }-    var isDragging by remember { mutableStateOf(false) }-    var isBuffering by remember { mutableStateOf(false) }++    // ---- transport state, which lives in CastPlayback rather than here ----+    // All of this used to be `remember`ed locals, which was right while the only reader was the seek bar+    // drawn beside them. A television showing this video is a second reader with a different lifetime -+    // it needs to know where playback is in order to draw a bar of its own - and a `remember` dies on+    // navigation while a cast session does not. The 300 ms loop below is still the only writer of the+    // position, so `dragging` remains a sufficient guard against two seeks fighting.+    val transport by CastPlayback.transport.collectAsState()+    val currentPosition = transport.positionMs+    val bufferedPosition = transport.bufferedMs+    val duration = transport.durationMs+    val isPlaying = transport.playing+    val isBuffering = transport.buffering+    val isDragging = transport.dragging+    val playbackSpeed = transport.speed      var isVideoMenuExpanded by remember { mutableStateOf(false) }     var isLanguageMenuExpanded by remember { mutableStateOf(false) }@@ -181,10 +189,22 @@ fun VideoPlayer(      // Tempo (playback speed) and pitch, applied via PlaybackParameters. When pitch is "hooked"     // to tempo it tracks it 1:1 (natural resample); unhooking lets the user set it independently.-    var playbackSpeed by remember { mutableFloatStateOf(1f) }+    // The tempo itself is in `transport` above, because the TV shows it and can change it.     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) }+    }+    LaunchedEffect(playbackSpeed) {+        if (playbackSpeed != persistedSpeed) ypvm.setPlaybackSpeed(playbackSpeed)+    }+     // Lock hides all controls (and disables seek/speed gestures) so a fullscreen video can't be     // disturbed by accidental touches, until the user taps the on-screen unlock button.     var isLocked by remember { mutableStateOf(false) }@@ -247,17 +267,23 @@ fun VideoPlayer(     DisposableEffect(controller) {         val player = controller ?: return@DisposableEffect onDispose {}         // Sync initial playing state once controller is available-        isPlaying = player.isPlaying+        CastPlayback.update { it.copy(playing = player.isPlaying) }+        // What a remote command is applied to, so the TV drives the same transport these buttons do.+        CastPlayback.attachPlayer(player)         val listener = object : Player.Listener {             override fun onEvents(player: Player, events: Player.Events) {                 if (events.contains(Player.EVENT_TIMELINE_CHANGED) || events.contains(Player.EVENT_PLAYBACK_STATE_CHANGED)) {-                    duration = player.duration.coerceAtLeast(0L)-                    isBuffering = player.playbackState == Player.STATE_BUFFERING-                    isPlaying = player.isPlaying+                    CastPlayback.update {+                        it.copy(+                            durationMs = player.duration.coerceAtLeast(0L),+                            buffering = player.playbackState == Player.STATE_BUFFERING,+                            playing = player.isPlaying,+                        )+                    }                 }             }             override fun onIsPlayingChanged(isPlayingNow: Boolean) {-                isPlaying = isPlayingNow+                CastPlayback.update { it.copy(playing = isPlayingNow) }                 context.findActivity().setPictureInPictureParams(PictureInPictureParams.Builder().apply {                     setAutoEnterEnabled(isPlayingNow)                 }.build())@@ -274,6 +300,7 @@ fun VideoPlayer(         player.addListener(listener)         onDispose {             player.removeListener(listener)+            CastPlayback.attachPlayer(null)             context.findActivity().setPictureInPictureParams(PictureInPictureParams.Builder().apply {                 setAutoEnterEnabled(false)             }.build())@@ -285,21 +312,26 @@ fun VideoPlayer(         var lastHistoryUpsert = 0L         while (true) {             if (!isDragging) {-                currentPosition = player.currentPosition.coerceAtLeast(0L)-                bufferedPosition = player.bufferedPosition.coerceAtLeast(0L)+                var position = player.currentPosition.coerceAtLeast(0L)                  if (sponsorBlockEnabled) {-                    val currentSegment = sponsorSegments.find { currentPosition in it.start until it.end }+                    val currentSegment = sponsorSegments.find { position in it.start until it.end }                     if (currentSegment != null) {                         player.seekTo(currentSegment.end)-                        currentPosition = currentSegment.end+                        position = currentSegment.end                     }                 }+                CastPlayback.update {+                    it.copy(+                        positionMs = position,+                        bufferedMs = player.bufferedPosition.coerceAtLeast(0L),+                    )+                }                  if (player.isPlaying) {                     val now = System.currentTimeMillis()                     if (now - lastHistoryUpsert >= HISTORY_UPSERT_INTERVAL_MS) {-                        ypvm.upsertHistoryVideo(HistoryVideo.fromVideoData(videoInfo.copy(duration = duration), currentPosition))+                        ypvm.upsertHistoryVideo(HistoryVideo.fromVideoData(videoInfo.copy(duration = duration), position))                         lastHistoryUpsert = now                     }                 }@@ -358,7 +390,7 @@ fun VideoPlayer(          player.setMediaItem(mediaItem, timeWatched)         player.prepare()-        currentPosition = timeWatched+        CastPlayback.update { it.copy(positionMs = timeWatched) }     }      LaunchedEffect(controller, selectedSubtitle) {@@ -726,7 +758,7 @@ fun VideoPlayer(                                 Slider(                                     value = playbackSpeed,                                     onValueChange = {-                                        playbackSpeed = it+                                        CastPlayback.update { state -> state.copy(speed = it) }                                         if (!unhookPitch) playbackPitch = it                                     },                                     valueRange = 0.25f..2f,@@ -769,7 +801,7 @@ fun VideoPlayer(                                 HorizontalDivider()                                 TextButton(                                     onClick = {-                                        playbackSpeed = 1f+                                        CastPlayback.update { it.copy(speed = 1f) }                                         playbackPitch = 1f                                         unhookPitch = false                                     },@@ -836,9 +868,14 @@ fun VideoPlayer(                             }                             Slider(                                 value = if (duration > 0) currentPosition.toFloat() else 0f,-                                onValueChange = { isDragging = true; currentPosition = it.toLong() },+                                onValueChange = {+                                    CastPlayback.update { state ->+                                        state.copy(dragging = true, positionMs = it.toLong())+                                    }+                                },                                 onValueChangeFinished = {-                                    controller?.seekTo(currentPosition); isDragging = false+                                    controller?.seekTo(currentPosition)+                                    CastPlayback.update { it.copy(dragging = false) }                                 },                                 valueRange = 0f..(duration.toFloat().coerceAtLeast(1f)),                                 colors = SliderDefaults.colors(
youpipe/src/main/java/com/vayunmathur/youpipe/util/YouPipeViewModel.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/util/YouPipeViewModel.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/util/YouPipeViewModel.ktindex cb1c976958..5b8cec876e 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/util/YouPipeViewModel.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/util/YouPipeViewModel.kt@@ -1035,6 +1035,27 @@ class YouPipeViewModel(         .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), false)     val keepPlayerControlsVisible: StateFlow<Boolean> = _keepPlayerControlsVisible +    /**+     * The tempo multiplier, kept across videos.+     *+     * Durable because it stopped being a per-video whim the moment a television could show it: a speed+     * that reset on every navigation would have the TV's overlay disagree with the phone for reasons+     * neither screen explains. Stored as a double because that is what `DataStoreUtils` has; the player+     * works in floats.+     */+    private val _playbackSpeed: StateFlow<Float> = DataStoreUtils+        .getInstance(application)+        .doubleFlow("playback_speed")+        .map { it.toFloat() }+        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), 1f)+    val playbackSpeed: StateFlow<Float> = _playbackSpeed++    fun setPlaybackSpeed(speed: Float) {+        viewModelScope.launch {+            DataStoreUtils.getInstance(getApplication()).setDouble("playback_speed", speed.toDouble())+        }+    }+     fun setKeepPlayerControlsVisible(keepVisible: Boolean) {         viewModelScope.launch {             DataStoreUtils.getInstance(getApplication()).setBoolean("keep_player_controls_visible", keepVisible)