Modern Apps git

← Modern-Apps.git

music: cast the library to a TV without re-encoding it

Commit
98cc83618fb86e3da615362fe2efa484dc823433
Author
vayun-mathur <[email protected]>
When
2026-08-23 18:42 UTC (3 months ago)
Parents
990d5ff

Diff

cast/src/main/java/com/vayunmathur/cast/service/ContentCastService.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/service/ContentCastService.kt b/cast/src/main/java/com/vayunmathur/cast/service/ContentCastService.ktindex ee53d36d60..635753f6db 100644--- a/cast/src/main/java/com/vayunmathur/cast/service/ContentCastService.kt+++ b/cast/src/main/java/com/vayunmathur/cast/service/ContentCastService.kt@@ -13,6 +13,7 @@ import android.os.RemoteException import android.util.Log import com.vayunmathur.cast.platform.CastController import com.vayunmathur.cast.platform.ContentSessionResult+import com.vayunmathur.cast.protocol.PlayMedia import com.vayunmathur.cast.protocol.PlaybackAction import com.vayunmathur.cast.protocol.PlaybackCommand import com.vayunmathur.cast.protocol.PlaybackState@@ -86,6 +87,14 @@ class ContentCastService : Service() {                     resources.onResponse(msg.data)                     true                 }+                CastContract.MSG_PLAY_MEDIA -> {+                    // Dropped with no session, for the same reason a state snapshot is: there is no+                    // TV to play it on, and a client may send one a tick after the session ended.+                    if (sessionOpen) {+                        msg.data?.let { CastController.playMedia(it.toPlayMedia()) }+                    }+                    true+                }                 else -> false             }         },@@ -266,6 +275,15 @@ private fun Bundle.toPlaybackState(): PlaybackState = PlaybackState(     hasPrevious = getBoolean(CastContract.KEY_HAS_PREVIOUS), ) +/** The item a client asked for, as the message the TV understands. See [Bundle.toPlaybackState]. */+private fun Bundle.toPlayMedia(): PlayMedia = PlayMedia(+    resourceId = getString(CastContract.KEY_RESOURCE_ID).orEmpty(),+    // A default rather than a refusal: ExoPlayer sniffs when it is not told, which costs a round+    // trip but plays, where a refused item would simply be silence.+    mimeType = getString(CastContract.KEY_RESOURCE_TYPE).orEmpty(),+    durationMs = getLong(CastContract.KEY_MEDIA_DURATION_MS),+)+ /** The command the TV sent, as the `Message` the SDK reads. See [Bundle.toPlaybackState]. */ private fun playbackCommand(command: PlaybackCommand): Message =     Message.obtain(null, CastContract.MSG_PLAYBACK_COMMAND).apply {
music/build.gradle.kts
diff --git a/music/build.gradle.kts b/music/build.gradle.ktsindex 5a0d7d5fb5..1cf27884ff 100644--- a/music/build.gradle.kts+++ b/music/build.gradle.kts@@ -27,4 +27,10 @@ dependencies {     implementation(libs.androidx.media3.ui.compose.material3)      implementation(project(":library:image"))++    // Casting. `:sdk:cast` owns no sockets and needs no network permission - which is the point,+    // because this app deliberately has no INTERNET permission. `:library:media` is here for the+    // Opus transcoder: every cast audio track is 48 kHz Opus, and most of the library is not.+    implementation(project(":sdk:cast"))+    implementation(project(":library:media")) }\ No newline at end of file
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.ktnew file mode 100644index 0000000000..f6f00c7cd7--- /dev/null+++ b/music/src/main/java/com/vayunmathur/music/platform/CastPlayback.kt@@ -0,0 +1,267 @@+package com.vayunmathur.music.platform++import android.content.Context+import android.net.Uri+import android.os.ParcelFileDescriptor+import android.util.Log+import androidx.core.net.toUri+import com.vayunmathur.library.media.OpusTranscoder+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 kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.flow.update+import kotlinx.coroutines.withContext+import java.io.File+import java.util.concurrent.ConcurrentHashMap++private const val TAG = "CastPlayback"++/**+ * Plays this library on a television, by serving it rather than streaming pixels.+ *+ * Casting music was not possible before: the SDK's only session handed back a `Surface` to draw+ * into, and a music player has nothing to draw. A content session has no surface at all - Cast runs+ * an HTTPS proxy, asks this app for a descriptor per track, and the TV decodes the original bytes.+ * So the phone starts no encoder, and the one thing it does encode is Opus, once per file.+ *+ * **Preparation happens before the TV is told to play, deliberately.** Cast's proxy holds an HTTP+ * request open while it waits for a descriptor, so transcoding inside that wait would turn a slow+ * conversion into a stalled fetch. Doing it first makes the delay this app's own, where it can be+ * shown as one.+ */+object CastPlayback {++    sealed interface State {++        data object Idle : State++        /** The picker has been dismissed and the session is being negotiated. */+        data object Connecting : State++        data class Casting(+            val receiverName: String,+            /**+             * A track is being converted to Opus.+             *+             * Worth a state of its own because it is the only part of casting that takes visible+             * time, and a first play with no explanation looks like a hang.+             */+            val preparing: Boolean = false,+        ) : State+    }++    private val _state = MutableStateFlow<State>(State.Idle)+    val state: StateFlow<State> = _state.asStateFlow()++    private var client: CastClient? = null++    /**+     * What the TV has been told about, by resource id.+     *+     * Also the authorisation list: a request for anything this app did not offer is answered with+     * nothing, which the TV sees as a `404`. Cast is trusted, but a bug on either side should not be+     * able to turn the proxy into a reader of the whole music library.+     */+    private val offered = ConcurrentHashMap<String, Prepared>()++    /** A track that is ready to be served, and where its bytes are. */+    private class Prepared(+        val source: Source,+        val contentType: String,+    )++    private sealed interface Source {+        /** Already 48 kHz Opus, so the file itself is served with no processing at all. */+        class Original(val uri: Uri) : Source++        /** Converted once and cached, keyed by track id. */+        class Cached(val file: File) : Source+    }++    fun support(context: Context): CastClient.Support = CastClient(context).support()++    val isCasting: Boolean get() = _state.value is State.Casting++    /**+     * Open an audio-only session on the TV the user picked.+     *+     * Requires a TV already connected, which the picker Activity is for. Returns false with the state+     * back at [State.Idle] if Cast refused - most usefully when the television has no Opus decoder,+     * which it now says rather than playing silence.+     */+    suspend fun open(context: Context): Boolean {+        close()+        _state.value = State.Connecting+        val newClient = CastClient(context)+        return try {+            val session = newClient.openContentSession(+                resources = { resourceId -> openResource(context, resourceId) },+                // No picture. This is the case the Surface contract could not express at all.+                video = false,+            )+            newClient.onEnded = {+                Log.i(TAG, "the TV ended the session")+                clear()+            }+            client = newClient+            _state.value = State.Casting(session.receiverName)+            Log.i(TAG, "casting to '${session.receiverName}'")+            true+        } catch (e: CastException) {+            Log.w(TAG, "could not start casting", e)+            newClient.close()+            _state.value = State.Idle+            false+        }+    }++    /**+     * Put [song] on the TV, converting it first if it is not already Opus.+     *+     * Suspends for as long as the conversion takes, which is why the state carries a `preparing`+     * flag: a four-minute track is a second or two the first time and nothing at all afterwards.+     */+    suspend fun play(context: Context, song: Music) {+        val active = client ?: return+        val id = song.id.toString()+        val known = offered[id]+        if (known != null) {+            active.play(id, known.contentType, song.duration)+            return+        }++        _state.update { if (it is State.Casting) it.copy(preparing = true) else it }+        val prepared = withContext(Dispatchers.IO) { prepare(context, song) }+        _state.update { if (it is State.Casting) it.copy(preparing = false) else it }++        if (prepared == null) {+            Log.w(TAG, "'${song.title}' could not be prepared for casting")+            return+        }+        offered[id] = prepared+        active.play(id, prepared.contentType, song.duration)+    }++    fun close() {+        client?.close()+        clear()+    }++    private fun clear() {+        client = null+        offered.clear()+        _state.value = State.Idle+    }++    // ------------------------------------------------------------------+    // Getting a track into a shape the TV can play+    // ------------------------------------------------------------------++    /**+     * Serve an Opus file as it is; convert anything else, once.+     *+     * Converting to a file rather than streaming a live encode is the whole reason scrubbing works: a+     * live transcode has no length and no seekable offsets, so `Range` - and therefore the seek bar -+     * would have nothing to answer with.+     */+    private fun prepare(context: Context, song: Music): Prepared? {+        val uri = song.uri.toUri()+        if (isOpus(context, uri)) {+            Log.i(TAG, "'${song.title}' is already Opus; serving it unchanged")+            return Prepared(Source.Original(uri), CONTENT_TYPE)+        }++        val cached = cacheFile(context, song.id)+        if (cached.length() > 0) {+            Log.i(TAG, "'${song.title}' was converted on an earlier cast; reusing it")+            return Prepared(Source.Cached(cached), CONTENT_TYPE)+        }++        val source = runCatching {+            context.contentResolver.openInputStream(uri)?.use { it.readBytes() }+        }.getOrNull() ?: return null++        val encoded = OpusTranscoder.transcode(source, isStopped = { false }) {} ?: return null+        return runCatching {+            cached.parentFile?.mkdirs()+            cached.writeBytes(encoded)+            Log.i(TAG, "converted '${song.title}' to ${encoded.size} bytes of Opus")+            Prepared(Source.Cached(cached), CONTENT_TYPE)+        }.getOrNull()+    }++    /**+     * Answers Cast's request for a track's bytes.+     *+     * Called on Cast's own background thread and expected to be quick, which it is: everything slow+     * already happened in [prepare]. The descriptor must be seekable, because the TV asks for byte+     * ranges - both branches here give a real file, and neither is a pipe.+     */+    private fun openResource(context: Context, resourceId: String): CastResource? {+        val prepared = offered[resourceId] ?: run {+            Log.w(TAG, "asked for '$resourceId', which was never offered")+            return null+        }+        return runCatching {+            when (val source = prepared.source) {+                is Source.Original -> {+                    val descriptor = context.contentResolver.openFileDescriptor(source.uri, "r")+                        ?: return null+                    CastResource(descriptor, descriptor.statSize, prepared.contentType)+                }+                is Source.Cached -> CastResource(+                    ParcelFileDescriptor.open(source.file, ParcelFileDescriptor.MODE_READ_ONLY),+                    source.file.length(),+                    prepared.contentType,+                )+            }+        }.onFailure { Log.w(TAG, "could not open '$resourceId'", it) }.getOrNull()+    }++    /**+     * Whether the file is already Ogg/Opus, from its first bytes rather than its name.+     *+     * `MediaStore` has no column for this and `getType` reports `audio/ogg` for Vorbis too, so the+     * container is read: an Ogg page header, then `OpusHead` inside the first page. Getting this+     * wrong in the permissive direction would serve a Vorbis file as Opus and the TV would refuse+     * it, so the check errs towards converting.+     */+    private fun isOpus(context: Context, uri: Uri): Boolean = runCatching {+        context.contentResolver.openInputStream(uri)?.use { input ->+            val head = ByteArray(SNIFF_BYTES)+            val read = input.read(head)+            if (read < 36) return@use false+            val magic = String(head, 0, 4, Charsets.ISO_8859_1)+            magic == "OggS" && String(head, 0, read, Charsets.ISO_8859_1).contains("OpusHead")+        } == true+    }.getOrDefault(false)++    private fun cacheFile(context: Context, songId: Long): File =+        File(File(context.cacheDir, CACHE_DIR), "$songId.opus")++    /**+     * Clears converted tracks.+     *+     * The cache is what makes a second cast of the same track free, so it is kept across sessions -+     * but it is a cache, and 256 kbps Opus of a whole library would not be small.+     */+    fun clearCache(context: Context) {+        runCatching { File(context.cacheDir, CACHE_DIR).deleteRecursively() }+    }++    /** Enough to cover an Ogg page header and the `OpusHead` packet that follows it. */+    private const val SNIFF_BYTES = 64++    private const val CACHE_DIR = "cast-opus"++    /**+     * `audio/ogg` rather than `audio/opus`: the container is Ogg, and that is what decides which+     * extractor the TV's player reaches for.+     */+    private const val CONTENT_TYPE = "audio/ogg"+}
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 ca79243417..09328f85b9 100644--- a/music/src/main/java/com/vayunmathur/music/platform/MusicUiContract.kt+++ b/music/src/main/java/com/vayunmathur/music/platform/MusicUiContract.kt@@ -60,6 +60,13 @@ data class NowPlayingUiState(     val sourceName: String? = null,     /** Raw embedded lyrics (LRC or plain), empty when the file carries none. */     val lyrics: String = "",+    /**+     * The library row for the loaded track, or null when it is not in the library.+     *+     * Carried because casting needs the file itself - its URI to read and its id to name it by -+     * where the rest of this state only needs what to draw.+     */+    val song: Music? = null, )  /**@@ -78,6 +85,14 @@ 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 9891287e10..a795c80990 100644--- a/music/src/main/java/com/vayunmathur/music/platform/MusicViewModel.kt+++ b/music/src/main/java/com/vayunmathur/music/platform/MusicViewModel.kt@@ -79,6 +79,7 @@ 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() }@@ -122,6 +123,7 @@ class MusicViewModel(             sourceId = sourceId,             sourceName = sourceName,             lyrics = lyrics,+            song = song,         )     } 
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 554abf0254..03955b1cd5 100644--- a/music/src/main/java/com/vayunmathur/music/platform/PlaybackManager.kt+++ b/music/src/main/java/com/vayunmathur/music/platform/PlaybackManager.kt@@ -188,6 +188,16 @@ 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/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 9a59420eec..8ed70a0370 100644--- a/music/src/main/java/com/vayunmathur/music/ui/NowPlayingScreen.kt+++ b/music/src/main/java/com/vayunmathur/music/ui/NowPlayingScreen.kt@@ -1,6 +1,17 @@ package com.vayunmathur.music.ui +import androidx.compose.material3.CircularProgressIndicator+import androidx.compose.runtime.collectAsState+import androidx.compose.ui.platform.LocalContext+import androidx.compose.runtime.rememberCoroutineScope+import com.vayunmathur.library.ui.IconCast+import com.vayunmathur.library.ui.IconCastConnected+import com.vayunmathur.music.platform.CastPlayback+import com.vayunmathur.sdk.cast.CastClient+import com.vayunmathur.sdk.cast.CastPickerContract+import kotlinx.coroutines.launch import android.util.Log+import androidx.activity.compose.rememberLauncherForActivityResult import androidx.compose.animation.Crossfade import androidx.compose.foundation.background import androidx.compose.foundation.clickable@@ -85,6 +96,7 @@ fun NowPlayingScreen(                 title = { },                 navigationIcon = { IconNavigation(backStack) },                 actions = {+                    CastButton(state = state, actions = actions)                     val sourceName = state.sourceName                     if (state.sourceId != null && sourceName != null) {                         TextButton(onClick = {@@ -248,6 +260,60 @@ fun NowPlayingScreen(     } } +/**+ * Puts this track on a television, or stops doing so.+ *+ * Talks to [CastPlayback] directly rather than through [MusicActions], the way YouPipe's player+ * 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.+ *+ * 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) {+    val context = LocalContext.current+    val scope = rememberCoroutineScope()+    val castState by CastPlayback.state.collectAsState()++    val supported = remember { CastPlayback.support(context) == CastClient.Support.READY }+    if (!supported) return++    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)+            }+        }+    }++    when (val current = castState) {+        is CastPlayback.State.Casting -> IconButton(onClick = { CastPlayback.close() }) {+            if (current.preparing) {+                CircularProgressIndicator(modifier = Modifier.size(20.dp))+            } else {+                IconCastConnected(tint = MaterialTheme.colorScheme.primary)+            }+        }+        CastPlayback.State.Connecting -> IconButton(onClick = {}) {+            CircularProgressIndicator(modifier = Modifier.size(20.dp))+        }+        CastPlayback.State.Idle -> IconButton(+            onClick = { picker.launch(Unit) },+            // Nothing loaded means nothing to send, and a button that silently did nothing would be+            // worse than one that is plainly unavailable.+            enabled = song != null,+        ) {+            IconCast()+        }+    }+}+ /** Parses LRC lyric content. Public so [LyricsView] tests can reuse it if needed. */ fun parseLyrics(lrcContent: String): List<LyricLine> {     val lines = mutableListOf<LyricLine>()
sdk/cast/src/main/java/com/vayunmathur/sdk/cast/CastClient.kt
diff --git a/sdk/cast/src/main/java/com/vayunmathur/sdk/cast/CastClient.kt b/sdk/cast/src/main/java/com/vayunmathur/sdk/cast/CastClient.ktindex 9464e63db2..6b93ad5428 100644--- a/sdk/cast/src/main/java/com/vayunmathur/sdk/cast/CastClient.kt+++ b/sdk/cast/src/main/java/com/vayunmathur/sdk/cast/CastClient.kt@@ -327,6 +327,32 @@ class CastClient(context: Context) {         }     } +    /**+     * Tell the TV to play a resource, in a content session.+     *+     * [resourceId] is this app's own name for it: whatever [CastResourceProvider] will be asked for.+     * Call it again for the next item - there is no playlist, because the queue stays here where the+     * ordering, the artwork and the metadata are.+     *+     * Silent and non-throwing, like [reportPlaybackState]: a session that has just ended is the+     * common reason for this to go nowhere, and the client already learns that through [onEnded].+     */+    fun play(resourceId: String, mimeType: String, durationMs: Long = 0) {+        if (!open) return+        val remote = service ?: return+        val message = Message.obtain(null, CastContract.MSG_PLAY_MEDIA).apply {+            data = Bundle().apply {+                putString(CastContract.KEY_RESOURCE_ID, resourceId)+                putString(CastContract.KEY_RESOURCE_TYPE, mimeType)+                putLong(CastContract.KEY_MEDIA_DURATION_MS, durationMs)+            }+        }+        try {+            remote.send(message)+        } catch (_: RemoteException) {+        }+    }+     /**      * End the session and unbind. Idempotent, and safe if [openSession] never succeeded.      *
sdk/cast/src/main/java/com/vayunmathur/sdk/cast/CastContract.kt
diff --git a/sdk/cast/src/main/java/com/vayunmathur/sdk/cast/CastContract.kt b/sdk/cast/src/main/java/com/vayunmathur/sdk/cast/CastContract.ktindex 551cf2afe5..a1e0fe8796 100644--- a/sdk/cast/src/main/java/com/vayunmathur/sdk/cast/CastContract.kt+++ b/sdk/cast/src/main/java/com/vayunmathur/sdk/cast/CastContract.kt@@ -116,6 +116,17 @@ object CastContract {      */     const val MSG_RESOURCE_RESPONSE = 8 +    /**+     * Play a resource, in a content session.+     *+     * Carries [KEY_RESOURCE_ID], [KEY_RESOURCE_TYPE] and optionally [KEY_MEDIA_DURATION_MS]. Sent+     * once per item rather than as a playlist, because the queue stays with the app: it owns the+     * ordering, the artwork and the metadata, so advancing is a decision the app makes and reports.+     *+     * Ignored without a session, so a client need not track readiness itself.+     */+    const val MSG_PLAY_MEDIA = 9+     // ---- service → client ----      /**@@ -252,6 +263,14 @@ object CastContract {     /** The resource's MIME type, which decides which extractor the TV's player reaches for. */     const val KEY_RESOURCE_TYPE = "resourceType" +    /**+     * How long the item runs, in milliseconds, or absent when the app does not know.+     *+     * Sent even though the container states it, so the TV can draw a seek bar before the first byte+     * arrives rather than having it appear a moment into playback.+     */+    const val KEY_MEDIA_DURATION_MS = "mediaDurationMs"+     // ---- MSG_SESSION_ENDED payload ----      /** One of the `REASON_` constants. */