Modern Apps git

← Modern-Apps.git

music: make every surface show and drive the television's player

Commit
d93a8a47907fdd7c4ffd76452648fc28c5815897
Author
vayun-mathur <[email protected]>
When
2026-08-24 00:22 UTC (3 months ago)
Parents
a2b858d

Diff

music/src/main/java/com/vayunmathur/music/platform/CastPlayback.kt
diff --git a/music/src/main/java/com/vayunmathur/music/platform/CastPlayback.kt b/music/src/main/java/com/vayunmathur/music/platform/CastPlayback.ktindex 6677f9c7df..3692d87d63 100644--- a/music/src/main/java/com/vayunmathur/music/platform/CastPlayback.kt+++ b/music/src/main/java/com/vayunmathur/music/platform/CastPlayback.kt@@ -10,6 +10,8 @@ import com.vayunmathur.music.data.Music import com.vayunmathur.sdk.cast.CastClient import com.vayunmathur.sdk.cast.CastException import com.vayunmathur.sdk.cast.CastResource+import com.vayunmathur.sdk.cast.PlaybackCommand+import com.vayunmathur.sdk.cast.PlaybackState import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job@@ -18,7 +20,6 @@ import kotlinx.coroutines.SupervisorJob 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.withContext@@ -44,7 +45,12 @@ private const val TAG = "CastPlayback"  *  * The price is one thing a user can notice: **a track being encoded for the first time cannot be  * seeked**, because a stream with no known length has nothing to answer a byte range with. It is- * cached as it goes, so every later play of it is instant and seekable both.+ * cached as it goes, so every later play of it is instant and seekable both. [growing] is which+ * resource that currently applies to, and `CastingPlayer` takes the seek commands away while it does.+ *+ * **This object does not decide anything about the queue.** It opens the session, answers for bytes,+ * and carries the television's own playback back through [tv] - `CastQueue` and `CastingPlayer` are+ * what turn that into one player on the phone.  */ object CastPlayback { @@ -55,22 +61,45 @@ object CastPlayback {         /** The picker has been dismissed and the session is being negotiated. */         data object Connecting : State -        data class Casting(-            val receiverName: String,-            /**-             * A track is still being encoded in the background.-             *-             * No longer "you are waiting": playback has already started, and this only says the-             * encoder is still working behind it. Worth showing anyway, because it is the window-             * in which seeking does not work and in which a failure can still appear.-             */-            val preparing: Boolean = false,-        ) : State+        data class Casting(val receiverName: String) : State     } +    /**+     * The television's own playback, and when it was true.+     *+     * **The wall clock is the missing half of the message.** Snapshots land twice a second and a seek+     * bar redraws sixty times a second, so a position plotted where it was reported would visibly step;+     * what makes it smooth is knowing when the number was true. The extrapolation itself is+     * `CastingPlayer`'s, because media3 already has a `PositionSupplier` for exactly this.+     */+    data class TvPlayback(val state: PlaybackState, val receivedAtMs: Long)+     private val _state = MutableStateFlow<State>(State.Idle)     val state: StateFlow<State> = _state.asStateFlow() +    private val _tv = MutableStateFlow<TvPlayback?>(null)++    /**+     * What the television's player is doing, or null before it has said anything.+     *+     * The only account of playback there is while casting: the phone's own player is paused and muted,+     * so every surface that shows a position - the now-playing screen, the notification, the+     * lockscreen, a car - is ultimately reading this.+     */+    val tv: StateFlow<TvPlayback?> = _tv.asStateFlow()++    private val _growing = MutableStateFlow<String?>(null)++    /**+     * The resource currently being encoded as the television reads it, or null.+     *+     * Its own value rather than a flag on [State.Casting], because *which* resource matters: a+     * background transcode of a track the user has already skipped past says nothing about whether the+     * track now playing can be seeked. A flow rather than a field so the scrubber comes back the moment+     * the encoder finishes, without waiting for a track change.+     */+    val growing: StateFlow<String?> = _growing.asStateFlow()+     /**      * Owns the background transcodes, and is why they are not launched in the caller's scope.      *@@ -83,17 +112,14 @@ object CastPlayback {     private var client: CastClient? = null      /**-     * The running transcode and the resource it is producing, so a track change can cancel it.+     * The running transcode, so a track change can cancel it.      *-     * Volatile because they are written from the transcode's own completion on `Dispatchers.IO` and-     * read by [play] on the main thread.+     * Volatile because it is written from the transcode's own completion on `Dispatchers.IO` and read+     * by [play] on the main thread. Which resource it is producing is [growing].      */     @Volatile     private var transcodeJob: Job? = null -    @Volatile-    private var transcodingId: String? = null-     /**      * What the TV has been told about, by resource id.      *@@ -150,6 +176,11 @@ object CastPlayback {                 Log.i(TAG, "the TV ended the session")                 clear()             }+            // The television holds the player, so this is where every position, every play/pause and+            // every end-of-track on the phone ultimately comes from.+            newClient.onPlaybackState = { state ->+                _tv.value = TvPlayback(state, System.currentTimeMillis())+            }             client = newClient             _state.value = State.Casting(session.receiverName)             Log.i(TAG, "casting to '${session.receiverName}'")@@ -166,10 +197,14 @@ object CastPlayback {      * Put [song] on the TV, encoding it in the background if it is not already Opus.      *      * Returns as soon as the TV has been told to play, which for a track needing conversion is-     * before any of it has been encoded. [State.Casting.preparing] is what says the encoder is-     * still running behind the playback.+     * before any of it has been encoded. [growing] is what says the encoder is still running behind+     * the playback.+     *+     * [startPositionMs] is what makes starting a cast keep its place rather than restart the track. A+     * resource still being written cannot honour it - there is nothing to seek against - so a track+     * cast for the first time begins at the beginning.      */-    suspend fun play(context: Context, song: Music) {+    suspend fun play(context: Context, song: Music, startPositionMs: Long = 0) {         val active = client ?: return         val id = song.id.toString()         // A transcode for a track the TV has moved on from is a minute of CPU nobody is waiting@@ -178,7 +213,7 @@ object CastPlayback {          val known = offered[id]         if (known != null) {-            active.play(id, known.contentType, song.duration)+            active.play(id, known.contentType, song.duration, startPositionMs)             return         } @@ -186,7 +221,7 @@ object CastPlayback {         val ready = withContext(Dispatchers.IO) { alreadyPlayable(context, uri, song) }         if (ready != null) {             offered[id] = ready-            active.play(id, ready.contentType, song.duration)+            active.play(id, ready.contentType, song.duration, startPositionMs)             return         } @@ -201,10 +236,22 @@ object CastPlayback {             return         }         offered[id] = Prepared(Source.Growing(cached), CONTENT_TYPE)+        // No start position: a growing stream has no length, so the TV would begin at the start+        // whatever it was told, and asking for a position it cannot honour reads as a bug.         active.play(id, CONTENT_TYPE, song.duration)         startTranscode(active, song, id, cached, source)     } +    /**+     * Ask the television to play, pause, seek or change speed.+     *+     * The one way a press on the phone reaches the sound, wherever it was pressed. Silent with no+     * session, like everything else here: `CastingPlayer` cannot know precisely when a session ended.+     */+    fun send(command: PlaybackCommand) {+        client?.sendCommand(command)+    }+     /**      * Encodes into the file the TV is already reading, and says so when it stops.      *@@ -220,8 +267,7 @@ object CastPlayback {         cached: File,         source: ByteArray,     ) {-        _state.update { if (it is State.Casting) it.copy(preparing = true) else it }-        transcodingId = id+        _growing.value = id         transcodeJob = scope.launch {             val length = runCatching {                 FileOutputStream(cached).use { sink ->@@ -244,16 +290,16 @@ object CastPlayback {                     Log.w(TAG, "could not encode '${song.title}' for casting")                 }                 active.resourceComplete(id, length ?: PRODUCER_FAILED)-                if (transcodingId == id) {-                    transcodingId = null-                    _state.update { if (it is State.Casting) it.copy(preparing = false) else it }-                }+                // Compared rather than cleared outright: a later track's transcode may already have+                // claimed this, and clearing it would say the newer one had finished.+                _growing.compareAndSet(id, null)             }         }     }      private fun cancelTranscodeExcept(id: String) {-        if (transcodingId == null || transcodingId == id) return+        val current = _growing.value+        if (current == null || current == id) return         transcodeJob?.cancel()     } @@ -264,12 +310,13 @@ object CastPlayback {      private fun clear() {         // Cancelled before the state is published: the transcode's own completion clears-        // `preparing`, and letting it run on would leave it writing into a session that has gone.+        // `growing`, and letting it run on would leave it writing into a session that has gone.         transcodeJob?.cancel()         transcodeJob = null-        transcodingId = null+        _growing.value = null         client = null         offered.clear()+        _tv.value = null         _state.value = State.Idle     } 
music/src/main/java/com/vayunmathur/music/platform/MusicUiContract.kt
diff --git a/music/src/main/java/com/vayunmathur/music/platform/MusicUiContract.kt b/music/src/main/java/com/vayunmathur/music/platform/MusicUiContract.ktindex 09328f85b9..25b86bde72 100644--- a/music/src/main/java/com/vayunmathur/music/platform/MusicUiContract.kt+++ b/music/src/main/java/com/vayunmathur/music/platform/MusicUiContract.kt@@ -85,14 +85,6 @@ interface MusicActions {     fun toggleShuffle() {}     fun toggleRepeat() {} -    /**-     * Stop local playback, because a television has taken over.-     *-     * Its own action rather than reusing [togglePlayPause]: the phone must end up stopped whatever-     * it was doing, and a toggle would start it playing if it happened to be paused.-     */-    fun pausePlayback() {}-     companion object {         val Noop: MusicActions = object : MusicActions {}     }
music/src/main/java/com/vayunmathur/music/platform/MusicViewModel.kt
diff --git a/music/src/main/java/com/vayunmathur/music/platform/MusicViewModel.kt b/music/src/main/java/com/vayunmathur/music/platform/MusicViewModel.ktindex a795c80990..cb1240e000 100644--- a/music/src/main/java/com/vayunmathur/music/platform/MusicViewModel.kt+++ b/music/src/main/java/com/vayunmathur/music/platform/MusicViewModel.kt@@ -79,7 +79,6 @@ class MusicViewModel(         playbackManager.playShuffled(songs, sourceId, sourceName)      override fun togglePlayPause() { playbackManager.togglePlayPause() }-    override fun pausePlayback() { playbackManager.pause() }     override fun seekTo(pos: Long) = playbackManager.seekTo(pos)     override fun skipNext() { playbackManager.skipNext() }     override fun skipPrevious() { playbackManager.skipPrevious() }
music/src/main/java/com/vayunmathur/music/platform/PlaybackManager.kt
diff --git a/music/src/main/java/com/vayunmathur/music/platform/PlaybackManager.kt b/music/src/main/java/com/vayunmathur/music/platform/PlaybackManager.ktindex 03955b1cd5..d55fa96dbd 100644--- a/music/src/main/java/com/vayunmathur/music/platform/PlaybackManager.kt+++ b/music/src/main/java/com/vayunmathur/music/platform/PlaybackManager.kt@@ -189,15 +189,6 @@ class PlaybackManager private constructor(context: Context) {      fun togglePlayPause() = controller?.let { if (it.isPlaying) it.pause() else it.play() } -    /**-     * Stop, without regard for what it was doing.-     *-     * For the cast handoff: the phone has to end up silent whether or not it was playing, and a-     * toggle would start it if it happened to be paused.-     */-    fun pause() {-        controller?.pause()-    }     fun seekTo(pos: Long) {         controller?.seekTo(pos)         _currentPosition.value = pos
music/src/main/java/com/vayunmathur/music/service/CastQueue.kt
diff --git a/music/src/main/java/com/vayunmathur/music/service/CastQueue.kt b/music/src/main/java/com/vayunmathur/music/service/CastQueue.ktnew file mode 100644index 0000000000..0e2ca8c4f3--- /dev/null+++ b/music/src/main/java/com/vayunmathur/music/service/CastQueue.kt@@ -0,0 +1,177 @@+package com.vayunmathur.music.service++import android.content.Context+import android.util.Log+import androidx.media3.common.MediaItem+import androidx.media3.common.Player+import androidx.media3.exoplayer.ExoPlayer+import com.vayunmathur.music.data.Music+import com.vayunmathur.music.data.MusicRepository+import com.vayunmathur.music.platform.CastPlayback+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.cancel+import kotlinx.coroutines.launch++private const val TAG = "CastQueue"++/**+ * The relationship between the phone's queue and the television, on the service's main thread.+ *+ * [CastingPlayer] makes the phone's five transports describe and drive the television's player; this+ * is the other half - the handover in each direction, and the things only a queue owner can do. They+ * are separate because they answer to different objects: the wrapper is asked questions by media3 and+ * must answer synchronously, while everything here is a decision made in reaction to a change.+ *+ * **It drives the local [ExoPlayer] directly, not through the wrapper.** That is the point: pausing+ * and muting the phone must not be routed to the television, and seeking the phone back to where the+ * television got to must not be routed anywhere at all.+ */+class CastQueue(context: Context, private val local: ExoPlayer) {++    private val app = context.applicationContext+    private val scope = CoroutineScope(Dispatchers.Main + SupervisorJob())++    /**+     * The library by id, so a queue item can be turned back into something castable.+     *+     * Mirrored rather than queried per track change, and populated long before it is needed: this+     * object is built with the service, which exists because something is already playing, and a cast+     * cannot be started until the now-playing screen has a track on it.+     */+    private var library: Map<Long, Music> = emptyMap()++    private var casting = false++    /** The local player's own gain, restored when the cast ends. */+    private var localVolume = 1f++    /** What the television was last told to play, so an `ended` is attributed to the right item. */+    private var offered: String? = null++    /**+     * Whether the current `ended` has already been acted on.+     *+     * **Cleared by the first snapshot that is *not* ended, and by nothing else.** The obvious guard -+     * remembering which item was skipped - does not work: the television goes on reporting `ended` for+     * up to a heartbeat after the phone has moved on, because the next `PLAY_MEDIA` has an IPC hop, a+     * LAN round trip and possibly the start of a transcode to get through first. A guard re-armed by+     * the offer would see that stale snapshot against the *new* item and skip a track that never+     * played. Only the television saying it is no longer ended proves it has moved.+     */+    private var advancedOnEnded = false++    /** Where the television got to, and whether it meant to be playing, for handing playback back. */+    private var tvPositionMs = 0L+    private var tvPlaying = false++    /**+     * The one hook that makes the queue work.+     *+     * Whatever moved the local player - the app's own next button, a headset, a car, the auto-advance+     * in [onTvPlayback] - ends here, and the television is told to play what the phone has moved to. A+     * field rather than an anonymous object so [release] can undo what [init] did.+     */+    private val transitions = object : Player.Listener {+        override fun onMediaItemTransition(mediaItem: MediaItem?, reason: Int) {+            if (casting) offer(mediaItem, startPositionMs = 0)+        }+    }++    init {+        scope.launch {+            MusicRepository.get(app).music.collect { songs ->+                library = songs.associateBy { it.id }+            }+        }+        scope.launch { CastPlayback.state.collect { onCastState(it) } }+        scope.launch { CastPlayback.tv.collect { onTvPlayback(it) } }+        local.addListener(transitions)+    }++    fun release() {+        scope.cancel()+        local.removeListener(transitions)+    }++    private fun onCastState(state: CastPlayback.State) {+        val nowCasting = state is CastPlayback.State.Casting+        if (nowCasting == casting) return+        casting = nowCasting+        if (nowCasting) begin() else end()+    }++    /**+     * Hand playback to the television, keeping the place.+     *+     * Paused **and** muted, which is not belt and braces: pausing is what stops the sound now, and+     * muting is what keeps it stopped if anything starts the delegate again - an audio-focus change,+     * or a path into the local player this class has not thought of. A track coming out of the phone+     * and the television at once is the one failure a user cannot miss.+     */+    private fun begin() {+        localVolume = local.volume+        local.pause()+        local.volume = 0f+        tvPositionMs = local.currentPosition+        tvPlaying = true+        offer(local.currentMediaItem, startPositionMs = local.currentPosition)+    }++    /**+     * Take playback back, at the position the television had reached.+     *+     * Without the seek the phone rewinds to wherever it was paused, which is 0:00 if the cast began+     * with the track - straight after a notification that read 2:31.+     */+    private fun end() {+        offered = null+        advancedOnEnded = false+        local.volume = localVolume+        if (local.currentMediaItem != null) {+            local.seekTo(tvPositionMs)+            if (tvPlaying) local.play()+        }+    }++    private fun onTvPlayback(playback: CastPlayback.TvPlayback?) {+        val snapshot = playback?.state ?: return+        tvPositionMs = snapshot.positionMs+        // Buffering counts as playing here: it is what the user asked for, and a stall at the moment+        // they disconnect is not a reason to come back paused.+        tvPlaying = snapshot.playing || snapshot.buffering+        if (!snapshot.ended) {+            advancedOnEnded = false+            return+        }+        if (!casting || advancedOnEnded) return+        // Attributed to what the television was last told to play, so an `ended` that arrives before+        // anything was offered - a session that ended before a track loaded - moves nothing.+        if (offered == null) return+        advancedOnEnded = true+        if (local.hasNextMediaItem()) {+            // The transition this causes is what issues the next `PLAY_MEDIA`; nothing is sent here.+            local.seekToNextMediaItem()+        } else {+            Log.i(TAG, "the queue is finished; the television stays where it is")+        }+    }++    /**+     * Tell the television to play what the phone has moved to.+     *+     * A track the library has nothing for is dropped rather than guessed at: the resource id *is* the+     * media id, and Cast answers a request for anything this app did not offer with a `404`.+     */+    private fun offer(item: MediaItem?, startPositionMs: Long) {+        val resourceId = item?.mediaId ?: return+        val song = resourceId.toLongOrNull()?.let { library[it] }+        if (song == null) {+            Log.w(TAG, "nothing in the library for '$resourceId'; the TV was not told to play")+            return+        }+        offered = resourceId+        scope.launch { CastPlayback.play(app, song, startPositionMs) }+    }+}
music/src/main/java/com/vayunmathur/music/service/CastingPlayer.kt
diff --git a/music/src/main/java/com/vayunmathur/music/service/CastingPlayer.kt b/music/src/main/java/com/vayunmathur/music/service/CastingPlayer.ktnew file mode 100644index 0000000000..dd6fb5d28f--- /dev/null+++ b/music/src/main/java/com/vayunmathur/music/service/CastingPlayer.kt@@ -0,0 +1,326 @@+package com.vayunmathur.music.service++import androidx.annotation.OptIn+import androidx.media3.common.ForwardingSimpleBasePlayer+import androidx.media3.common.PlaybackParameters+import androidx.media3.common.Player+import androidx.media3.common.SimpleBasePlayer.PositionSupplier+import androidx.media3.common.util.UnstableApi+import com.google.common.util.concurrent.Futures+import com.google.common.util.concurrent.ListenableFuture+import com.vayunmathur.music.platform.CastPlayback+import com.vayunmathur.sdk.cast.PlaybackAction+import com.vayunmathur.sdk.cast.PlaybackCommand+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.cancel+import kotlinx.coroutines.flow.combine+import kotlinx.coroutines.launch+import kotlin.math.abs++/**+ * The phone's one player, whichever end is actually making the sound.+ *+ * **Wrapping the session's player is what fixes every surface at once.** `:music` has three+ * independent paths to its transport - the app's own UI through `PlaybackManager`, the mini-player's+ * media3 controller, and the notification, lockscreen, headset and Android Auto through+ * `MediaLibrarySession` - and they converge in exactly one place: the [Player] handed to+ * `MediaLibrarySession.Builder`. Intercepting anywhere higher fixes the first path and leaves the+ * notification claiming "paused" while the television plays, with its play button resuming the phone+ * so the track comes out of both.+ *+ * **[ForwardingSimpleBasePlayer] rather than `ForwardingPlayer`, and that is the load-bearing+ * choice.** The wrong one compiles and then fails silently: `ForwardingPlayer` delegates+ * `addListener` to the player it wraps, so it owns no listener registry and can never tell media3+ * that a getter changed value. `MediaSession` snapshots its `PlayerInfo` when the *wrapped* player+ * fires an event, and a paused local `ExoPlayer` fires almost nothing - so every controller would sit+ * on a frozen `playing = false` however good the getters were. This class gives [getState] for reads,+ * `invalidateState` for announcing them, and `handle*` for routing writes.+ *+ * Reads are synthesised and writes are routed, and only while casting. Everything that is the+ * *phone's* - the timeline, the metadata, the artwork, shuffle, repeat, the queue - is left entirely+ * to the delegate, which is what keeps the notification's title and cover working.+ */+@OptIn(UnstableApi::class)+class CastingPlayer(private val local: Player) : ForwardingSimpleBasePlayer(local) {++    private val scope = CoroutineScope(Dispatchers.Main + SupervisorJob())++    /** True between a cast starting and ending; nothing below applies otherwise. */+    private var casting = false++    /** The television's last word about its own player, or null before it has said anything. */+    private var tv: CastPlayback.TvPlayback? = null++    /** The resource still being encoded, which is the one that cannot be seeked. */+    private var growing: String? = null++    /**+     * Where playback is, extrapolating between snapshots.+     *+     * Rebuilt per snapshot so the bar moves smoothly rather than stepping twice a second - the same+     * idea as the protocol's own interpolation, one layer down, and media3 already has the primitive.+     */+    private var positions: PositionSupplier = PositionSupplier.ZERO++    /** A jump to announce once, so a seek on the TV's remote does not read as normal progress. */+    private var discontinuityMs: Long? = null++    init {+        // Plain `Main` rather than `Main.immediate`: a `StateFlow` hands over its current value on+        // subscription, and running that inline would call `invalidateState` from inside this+        // constructor. One posted tick later costs nothing.+        scope.launch {+            combine(+                CastPlayback.state,+                CastPlayback.tv,+                CastPlayback.growing,+            ) { state, snapshot, growingId -> Triple(state, snapshot, growingId) }+                .collect { (state, snapshot, growingId) -> onCast(state, snapshot, growingId) }+        }+    }++    private fun onCast(+        state: CastPlayback.State,+        snapshot: CastPlayback.TvPlayback?,+        growingId: String?,+    ) {+        casting = state is CastPlayback.State.Casting+        growing = growingId+        val current = snapshot.takeIf { casting }+        if (current == null) {+            tv = null+            positions = PositionSupplier.ZERO+            discontinuityMs = null+            invalidateState()+            return+        }+        // Compared against where the *old* supplier says we should be, before it is replaced. A press+        // on the television's remote is the case this exists for: without it a five-second jump is+        // indistinguishable from five seconds of ordinary progress, and nothing seeks.+        if (tv != null && isDiscontinuity(current.state.positionMs, positions.get())) {+            discontinuityMs = current.state.positionMs+        }+        tv = current+        positions = supplierFor(current)+        invalidateState()+    }++    /**+     * Everything the delegate says, with the television's player written over the parts it owns.+     *+     * The overridden set is deliberately small. Duration comes from the delegate's `MediaItem` and+     * never from the television, because a growing Opus stream has no duration and taking it from+     * there collapses every seek bar to zero on a first play. The timeline, the media ids, the+     * metadata and the artwork are the delegate's for the reason the class note gives - and because+     * unstable ids here would make every snapshot read as a timeline change, storming+     * `onTimelineChanged` and making Android Auto re-query its browse tree twice a second.+     */+    override fun getState(): State {+        val base = super.getState()+        val snapshot = tv ?: return base+        // Nothing loaded is nothing to describe, and `State` forbids a non-idle player with an empty+        // playlist anyway.+        if (base.timeline.isEmpty) return base+        val playback = snapshot.state+        val playbackState = playbackStateFor(playback.buffering, playback.ended)+        val builder = base.buildUpon()+            // `isPlaying` is media3's own derivation from these two, which is what keeps every surface+            // in step - and the foreground-service lifecycle, which reads `playWhenReady` and takes+            // the notification away mid-track if it is wrong.+            .setPlayWhenReady(+                playWhenReady(playback.playing, playback.buffering),+                Player.PLAY_WHEN_READY_CHANGE_REASON_REMOTE,+            )+            .setPlaybackState(playbackState)+            // The local player is paused and may be suppressed or hold an old error; neither says+            // anything about the television, and `State` forbids an error outside `STATE_IDLE`.+            .setPlaybackSuppressionReason(Player.PLAYBACK_SUPPRESSION_REASON_NONE)+            .setPlayerError(null)+            // Read off the state rather than off `buffering`, because `State` forbids loading in+            // `STATE_ENDED` - and a track that finished while its last read was outstanding reports+            // both, so this would throw on the application thread rather than merely look wrong.+            .setIsLoading(playbackState == Player.STATE_BUFFERING)+            .setPlaybackParameters(PlaybackParameters(playback.speed))+            .setContentPositionMs(positions)+            // The television reports no buffered extent, so the honest answer is "as far as it has+            // played" - and a buffered position behind the current one is rejected outright.+            .setContentBufferedPositionMs(positions)+            .setTotalBufferedDurationMs(PositionSupplier.ZERO)+            .setAvailableCommands(+                seekCommands(+                    base.availableCommands,+                    seekable(growing, local.currentMediaItem?.mediaId),+                ),+            )+        discontinuityMs?.let {+            discontinuityMs = null+            builder.setPositionDiscontinuity(Player.DISCONTINUITY_REASON_SEEK, it)+        }+        return builder.build()+    }++    /**+     * Play and pause become a command to the television, because that is where the player is.+     *+     * Not forwarded as well: the local player is what must stay silent, and starting it would put the+     * track through both the phone and the television at once.+     *+     * The future completes at once rather than when the television confirms, so media3 drops its+     * optimistic placeholder immediately and the next snapshot is what makes the change stick. That is+     * fine because the television reports on change rather than only on its heartbeat, so the+     * confirmation is one LAN round trip away - but it is the one thing here that can only be judged+     * with a television in the room: a press that visibly bounces back would mean waiting for the+     * confirming snapshot instead.+     */+    override fun handleSetPlayWhenReady(playWhenReady: Boolean): ListenableFuture<*> {+        if (!casting) return super.handleSetPlayWhenReady(playWhenReady)+        CastPlayback.send(+            PlaybackCommand(if (playWhenReady) PlaybackAction.Play else PlaybackAction.Pause),+        )+        return Futures.immediateVoidFuture()+    }++    /**+     * A seek inside the current track goes to the television; anything that changes item does not.+     *+     * Next and previous are **always** forwarded, because the queue is the phone's: the local player+     * moves, and the item transition is what issues a fresh `PLAY_MEDIA`. Routing them would ask a+     * television that has never seen the queue to guess at it.+     */+    override fun handleSeek(+        mediaItemIndex: Int,+        positionMs: Long,+        seekCommand: Int,+    ): ListenableFuture<*> {+        if (!casting || !isWithinCurrentItem(seekCommand)) {+            return super.handleSeek(mediaItemIndex, positionMs, seekCommand)+        }+        CastPlayback.send(PlaybackCommand(PlaybackAction.SeekTo, positionMs.toDouble()))+        return Futures.immediateVoidFuture()+    }++    override fun handleSetPlaybackParameters(+        playbackParameters: PlaybackParameters,+    ): ListenableFuture<*> {+        if (!casting) return super.handleSetPlaybackParameters(playbackParameters)+        CastPlayback.send(+            PlaybackCommand(PlaybackAction.SetSpeed, playbackParameters.speed.toDouble()),+        )+        return Futures.immediateVoidFuture()+    }++    override fun handleRelease(): ListenableFuture<*> {+        scope.cancel()+        return super.handleRelease()+    }++    /**+     * Where playback will be as the clock runs on, anchored at the moment the snapshot was true.+     *+     * Anchored rather than taken as "now" because the number crossed a LAN and an IPC hop to get here.+     * A paused player is a constant rather than an extrapolation at speed zero, because the seek bar+     * must hold still even if the television reports a speed it is not currently applying.+     */+    private fun supplierFor(playback: CastPlayback.TvPlayback): PositionSupplier {+        val state = playback.state+        val elapsed = System.currentTimeMillis() - playback.receivedAtMs+        val from = anchoredPositionMs(state.positionMs, state.speed, state.playing, elapsed)+        if (!state.playing) return PositionSupplier.getConstant(from)+        return PositionSupplier.getExtrapolating(from, state.speed)+    }++    private fun isWithinCurrentItem(seekCommand: Int): Boolean =+        seekCommand == Player.COMMAND_SEEK_IN_CURRENT_MEDIA_ITEM ||+            seekCommand == Player.COMMAND_SEEK_BACK ||+            seekCommand == Player.COMMAND_SEEK_FORWARD++    internal companion object {++        /**+         * Whether the user is asking for playback, from the two flags a snapshot carries.+         *+         * The television reports its player's own `isPlaying`, which is already false while it stalls -+         * so buffering has to count as wanting to play, or a stall would read as a pause and take the+         * notification's play button with it. Together with [playbackStateFor] this is what media3+         * derives `isPlaying` from, and it comes back out false while buffering because the state is+         * `STATE_BUFFERING` rather than because this said so.+         */+        internal fun playWhenReady(playing: Boolean, buffering: Boolean): Boolean =+            playing || buffering++        /**+         * A television's snapshot as a media3 playback state.+         *+         * `STATE_IDLE` is deliberately unreachable: it would mean a player with nothing prepared, and+         * `State` forbids both an error and `isLoading` outside it - so a snapshot mapped there would+         * throw rather than render.+         */+        internal fun playbackStateFor(buffering: Boolean, ended: Boolean): Int = when {+            ended -> Player.STATE_ENDED+            buffering -> Player.STATE_BUFFERING+            else -> Player.STATE_READY+        }++        /**+         * Whether the track now playing can be seeked at all.+         *+         * **The gate is which resource is growing, not whether anything is.** A background transcode+         * of a track the user has already skipped past says nothing about the one they are listening+         * to, and greying the scrubber out for it would be wrong in the annoying direction.+         */+        internal fun seekable(growingResourceId: String?, currentResourceId: String?): Boolean =+            growingResourceId == null || growingResourceId != currentResourceId++        /**+         * The delegate's commands, minus the seeks, when the playing resource is still being encoded.+         *+         * Honest rather than restrictive: a stream with no stated length has nothing to answer a byte+         * range against, so a seek would fail rather than be slow. Removing the commands is also what+         * greys the scrubber out and drops the matching actions from the lockscreen and from Android+         * Auto, which no amount of refusing a seek afterwards would do.+         */+        internal fun seekCommands(base: Player.Commands, seekable: Boolean): Player.Commands {+            if (seekable) return base+            return base.buildUpon()+                .remove(Player.COMMAND_SEEK_IN_CURRENT_MEDIA_ITEM)+                .remove(Player.COMMAND_SEEK_BACK)+                .remove(Player.COMMAND_SEEK_FORWARD)+                .build()+        }++        /**+         * Where a snapshot's position had got to [elapsedMs] after it was true.+         *+         * A pure function of four numbers, which is the point: it is the only arithmetic in this class+         * and the one thing about a seek bar that can be pinned down without a television in the room.+         * Paused holds still, and [speed] scales the advance - a track at 2x whose anchor did not+         * account for it would have its bar corrected backwards on every snapshot.+         *+         * A negative [elapsedMs] is a clock that went backwards, and answers where playback was.+         */+        internal fun anchoredPositionMs(+            positionMs: Long,+            speed: Float,+            playing: Boolean,+            elapsedMs: Long,+        ): Long {+            if (!playing) return positionMs+            return positionMs + (elapsedMs.coerceAtLeast(0) * speed).toLong()+        }++        /**+         * Whether a reported position is a jump rather than ordinary progress.+         *+         * A pure function of two numbers, and the whole of the decision. Snapshots land twice a second+         * against an estimate that keeps running, so the two are never exactly equal even when nothing+         * happened; a window wide enough to cover that and narrow enough to catch the smallest scrub+         * the TV's remote can make - five seconds - is what tells them apart.+         */+        internal fun isDiscontinuity(reportedMs: Long, extrapolatedMs: Long): Boolean =+            abs(reportedMs - extrapolatedMs) > DISCONTINUITY_MS++        internal const val DISCONTINUITY_MS = 1_000L+    }+}
music/src/main/java/com/vayunmathur/music/service/PlaybackService.kt
diff --git a/music/src/main/java/com/vayunmathur/music/service/PlaybackService.kt b/music/src/main/java/com/vayunmathur/music/service/PlaybackService.ktindex 1e654a9082..bbc7fa9a88 100644--- a/music/src/main/java/com/vayunmathur/music/service/PlaybackService.kt+++ b/music/src/main/java/com/vayunmathur/music/service/PlaybackService.kt@@ -33,11 +33,19 @@ import com.vayunmathur.music.MainActivity  * The player and the custom shuffle/repeat notification buttons are unchanged;  * we only widened the session type (MediaLibrarySession is a MediaSession) and  * added the library-browsing callbacks, so phone playback is unaffected.+ *+ * **The player handed to the session is a [CastingPlayer], and that is where casting lives.** Every+ * transport this app has - its own UI, the mini-player, the notification, the lockscreen, a headset,+ * Android Auto - reaches playback through this one object, so wrapping it here is what makes them all+ * describe and drive the television while a cast is running. [CastQueue] holds the raw player for the+ * things that must *not* go to the television: muting the phone, and putting it back where the+ * television got to afterwards.  */ class PlaybackService : MediaLibraryService() {      private var mediaSession: MediaLibrarySession? = null     private lateinit var libraryTree: MusicLibraryTree+    private var castQueue: CastQueue? = null     private val mainHandler = Handler(Looper.getMainLooper())      // Custom Command Constants@@ -57,11 +65,13 @@ class PlaybackService : MediaLibraryService() {             .setContentType(C.AUDIO_CONTENT_TYPE_MUSIC)             .build() -        val player = ExoPlayer.Builder(this)+        val local = ExoPlayer.Builder(this)             .setDeviceVolumeControlEnabled(true)             .setAudioAttributes(audioAttributes, true)             .setHandleAudioBecomingNoisy(true)             .build()+        val player = CastingPlayer(local)+        castQueue = CastQueue(this, local)          // Create the session with our custom callback         val intent = Intent(this, MainActivity::class.java)@@ -234,7 +244,10 @@ class PlaybackService : MediaLibraryService() {      override fun onDestroy() {         libraryTree.release()+        castQueue?.release()+        castQueue = null         mediaSession?.run {+            // Releasing the wrapper releases what it wraps, so the local player goes with it.             player.release()             release()             mediaSession = null
music/src/main/java/com/vayunmathur/music/ui/NowPlayingScreen.kt
diff --git a/music/src/main/java/com/vayunmathur/music/ui/NowPlayingScreen.kt b/music/src/main/java/com/vayunmathur/music/ui/NowPlayingScreen.ktindex 8ed70a0370..ab2c629a87 100644--- a/music/src/main/java/com/vayunmathur/music/ui/NowPlayingScreen.kt+++ b/music/src/main/java/com/vayunmathur/music/ui/NowPlayingScreen.kt@@ -96,7 +96,7 @@ fun NowPlayingScreen(                 title = { },                 navigationIcon = { IconNavigation(backStack) },                 actions = {-                    CastButton(state = state, actions = actions)+                    CastButton(state = state)                     val sourceName = state.sourceName                     if (state.sourceId != null && sourceName != null) {                         TextButton(onClick = {@@ -267,14 +267,20 @@ fun NowPlayingScreen(  * does: the picker is an `ActivityResultContract`, so the launcher has to live in a composable, and  * routing the session through the ViewModel would buy nothing but a second copy of its state.  *+ * **All this does is open and close the session.** What plays, and where it starts from, is+ * `CastQueue`'s - it hands the current item over as the cast begins and follows the queue from then+ * on. Issuing a `PLAY_MEDIA` from here as well would make two writers of it and restart the track+ * every time this screen was composed.+ *  * Absent entirely when Cast is not installed. An icon that only ever opened a store listing would be  * an advertisement in the middle of a transport bar.  */ @Composable-private fun CastButton(state: NowPlayingUiState, actions: MusicActions) {+private fun CastButton(state: NowPlayingUiState) {     val context = LocalContext.current     val scope = rememberCoroutineScope()     val castState by CastPlayback.state.collectAsState()+    val growing by CastPlayback.growing.collectAsState()      val supported = remember { CastPlayback.support(context) == CastClient.Support.READY }     if (!supported) return@@ -282,19 +288,15 @@ private fun CastButton(state: NowPlayingUiState, actions: MusicActions) {     val song = state.song      val picker = rememberLauncherForActivityResult(CastPickerContract()) { connected ->-        if (!connected || song == null) return@rememberLauncherForActivityResult-        scope.launch {-            if (CastPlayback.open(context)) {-                // The phone stops before the TV starts, so the track is never coming out of both.-                actions.pausePlayback()-                CastPlayback.play(context, song)-            }-        }+        if (!connected) return@rememberLauncherForActivityResult+        scope.launch { CastPlayback.open(context) }     } -    when (val current = castState) {+    when (castState) {         is CastPlayback.State.Casting -> IconButton(onClick = { CastPlayback.close() }) {-            if (current.preparing) {+            // A track still being encoded is the window in which seeking does not work and in which a+            // failure can still appear, so it is worth showing even though playback has started.+            if (growing != null) {                 CircularProgressIndicator(modifier = Modifier.size(20.dp))             } else {                 IconCastConnected(tint = MaterialTheme.colorScheme.primary)
music/src/test/java/com/vayunmathur/music/service/CastingPlayerTest.kt
diff --git a/music/src/test/java/com/vayunmathur/music/service/CastingPlayerTest.kt b/music/src/test/java/com/vayunmathur/music/service/CastingPlayerTest.ktnew file mode 100644index 0000000000..efdca66f2a--- /dev/null+++ b/music/src/test/java/com/vayunmathur/music/service/CastingPlayerTest.kt@@ -0,0 +1,158 @@+package com.vayunmathur.music.service++import androidx.media3.common.Player+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * The arithmetic and the derivations behind the one player the phone presents while casting.+ *+ * These are the parts of [CastingPlayer] that can be pinned down without a television and without a+ * looper. Everything else in that class is media3 asking it questions on the application thread, which+ * needs a device - so what is testable is deliberately factored out rather than left inline: a+ * `playWhenReady` derived wrongly takes the notification away mid-track, and a position anchored+ * wrongly makes every seek bar in the app jerk twice a second, and neither is obvious from reading it.+ *+ * `availableCommands` is exercised through [CastingPlayer.seekable], which is the whole of the+ * decision. The `Player.Commands` object it feeds is not built here: media3's flag sets are backed by+ * `SparseBooleanArray`, so constructing one on a plain JVM gets a stubbed Android class rather than a+ * failure, which would make the assertion say nothing.+ */+class CastingPlayerTest {++    // ---- what the phone reports ----++    @Test+    fun `a playing television is a player that is playing`() {+        val playWhenReady = CastingPlayer.playWhenReady(playing = true, buffering = false)+        val state = CastingPlayer.playbackStateFor(buffering = false, ended = false)+        assertTrue(playWhenReady)+        assertEquals(Player.STATE_READY, state)+        assertTrue(isPlaying(playWhenReady, state))+    }++    @Test+    fun `a paused television is a player that wants to be paused`() {+        // `playWhenReady` false is the load-bearing half: media3's foreground-service lifecycle reads+        // it, so a pause reported as anything else leaves a notification for a player making no sound.+        val playWhenReady = CastingPlayer.playWhenReady(playing = false, buffering = false)+        val state = CastingPlayer.playbackStateFor(buffering = false, ended = false)+        assertFalse(playWhenReady)+        assertEquals(Player.STATE_READY, state)+        assertFalse(isPlaying(playWhenReady, state))+    }++    @Test+    fun `a stall still wants to play, and still is not playing`() {+        // The television reports its player's own `isPlaying`, which is already false while it stalls.+        // Read as a pause that would grey out the notification's pause button mid-track; what makes it+        // come out right is the state, not the flag.+        val playWhenReady = CastingPlayer.playWhenReady(playing = false, buffering = true)+        val state = CastingPlayer.playbackStateFor(buffering = true, ended = false)+        assertTrue(playWhenReady, "a buffering television is still trying to play")+        assertEquals(Player.STATE_BUFFERING, state)+        assertFalse(isPlaying(playWhenReady, state), "a stall is not playback")+    }++    @Test+    fun `a finished track ends rather than buffers`() {+        // `ended` is what makes the queue advance, so it must win: a track that finished while its+        // last read was outstanding reports both, and STATE_BUFFERING would wait for ever.+        assertEquals(+            Player.STATE_ENDED,+            CastingPlayer.playbackStateFor(buffering = true, ended = true),+        )+    }++    /** media3's own derivation, spelled out here rather than duplicated into the player. */+    private fun isPlaying(playWhenReady: Boolean, playbackState: Int): Boolean =+        playWhenReady && playbackState == Player.STATE_READY++    // ---- where the seek bar is ----++    @Test+    fun `a paused snapshot holds still however long it is held`() {+        for (elapsed in listOf(0L, 500L, 600_000L)) {+            assertEquals(+                30_000,+                CastingPlayer.anchoredPositionMs(30_000, speed = 1f, playing = false, elapsedMs = elapsed),+            )+        }+    }++    @Test+    fun `a playing snapshot advances with the wall clock`() {+        assertEquals(30_000, CastingPlayer.anchoredPositionMs(30_000, 1f, playing = true, elapsedMs = 0))+        assertEquals(30_500, CastingPlayer.anchoredPositionMs(30_000, 1f, playing = true, elapsedMs = 500))+    }++    @Test+    fun `speed scales the advance, so a 2x track does not lag its own bar`() {+        assertEquals(1_000, CastingPlayer.anchoredPositionMs(0, 2f, playing = true, elapsedMs = 500))+        assertEquals(250, CastingPlayer.anchoredPositionMs(0, 0.5f, playing = true, elapsedMs = 500))+    }++    @Test+    fun `a clock that went backwards answers where playback was`() {+        assertEquals(1_000, CastingPlayer.anchoredPositionMs(1_000, 1f, playing = true, elapsedMs = -500))+    }++    // ---- what counts as a jump ----++    @Test+    fun `ordinary drift between snapshots is not a discontinuity`() {+        // Snapshots land twice a second against an estimate that keeps running, so the two are never+        // exactly equal. Announcing that as a seek would make every heartbeat a discontinuity.+        assertFalse(CastingPlayer.isDiscontinuity(reportedMs = 30_000, extrapolatedMs = 30_000))+        assertFalse(CastingPlayer.isDiscontinuity(reportedMs = 30_120, extrapolatedMs = 30_000))+        assertFalse(CastingPlayer.isDiscontinuity(reportedMs = 29_880, extrapolatedMs = 30_000))+        // The boundary itself is drift, not a jump.+        assertFalse(+            CastingPlayer.isDiscontinuity(30_000 + CastingPlayer.DISCONTINUITY_MS, 30_000),+        )+    }++    @Test+    fun `a scrub on the television's remote is a discontinuity in both directions`() {+        // The smallest thing the remote can do is five seconds, so the window has room to spare.+        assertTrue(CastingPlayer.isDiscontinuity(reportedMs = 35_000, extrapolatedMs = 30_000))+        assertTrue(CastingPlayer.isDiscontinuity(reportedMs = 25_000, extrapolatedMs = 30_000))+    }++    @Test+    fun `the window is narrower than the smallest scrub the remote can make`() {+        assertTrue(+            CastingPlayer.DISCONTINUITY_MS < 5_000L,+            "a scrub the remote can make must not be mistaken for drift",+        )+    }++    // ---- whether the track can be seeked ----++    @Test+    fun `a track with nothing being encoded can be seeked`() {+        assertTrue(CastingPlayer.seekable(growingResourceId = null, currentResourceId = "12"))+    }++    @Test+    fun `the track being encoded cannot be seeked`() {+        // A stream with no stated length has nothing to answer a byte range against, so the scrubber+        // is taken away rather than left to fail.+        assertFalse(CastingPlayer.seekable(growingResourceId = "12", currentResourceId = "12"))+    }++    @Test+    fun `another track being encoded does not take this one's scrubber away`() {+        // The case the gate exists for: a background transcode keeps running after the user has+        // skipped past it, and greying out the track they are actually listening to would be wrong.+        assertTrue(CastingPlayer.seekable(growingResourceId = "12", currentResourceId = "13"))+    }++    @Test+    fun `the scrubber comes back when the encode finishes`() {+        assertFalse(CastingPlayer.seekable("12", "12"))+        assertTrue(CastingPlayer.seekable(null, "12"), "no track change should be needed")+    }+}