Modern Apps git

← Modern-Apps.git

music: move util/ -> platform/ (MusicViewModel, UiContract, managers, workers) (canonical structure)

Commit
374ef1cdf04b2e199d4854e6fa225537997a6d1e
Author
vayun-mathur <[email protected]>
When
2026-08-15 18:01 UTC (3 months ago)
Parents
9a5b5cf

Diff

music/src/main/java/com/vayunmathur/music/platform/EmbeddedLyrics.kt
diff --git a/music/src/main/java/com/vayunmathur/music/platform/EmbeddedLyrics.kt b/music/src/main/java/com/vayunmathur/music/platform/EmbeddedLyrics.ktnew file mode 100644index 0000000000..767d9f577a--- /dev/null+++ b/music/src/main/java/com/vayunmathur/music/platform/EmbeddedLyrics.kt@@ -0,0 +1,272 @@+package com.vayunmathur.music.platform++import android.content.Context+import android.net.Uri+import java.io.FileInputStream+import java.io.InputStream+import java.nio.ByteBuffer+import java.nio.ByteOrder+import java.nio.channels.FileChannel++/**+ * Reads embedded lyrics out of the currently playing file.+ *+ * The musicbrainz downloader writes synced LRC text into a `LYRICS` tag - a Vorbis comment+ * in `.opus`/`.flac`, or an iTunes `©lyr` atom in the `.m4a` fallback - and this pulls it+ * back out so the now-playing screen can scroll along. Only the metadata region at the head+ * of the file is scanned; the audio body is never read, because this runs every time the+ * track changes.+ *+ * This mirrors the parsers in the musicbrainz app's `TagReader`, duplicated rather than+ * shared because the two apps are separate modules with no common dependency.+ */+object EmbeddedLyrics {++    // Large enough to clear an Opus comment header that also embeds cover art, since the+    // lyrics tag sits in that same packet behind the picture.+    private const val OGG_SCAN_BYTES = 1024 * 1024+    private const val MAX_MOOV_BYTES = 16 * 1024 * 1024++    /** Returns the raw LRC/lyrics text, or null when the file carries none this can read. */+    fun read(context: Context, uri: Uri): String? = try {+        when (containerOf(context, uri)) {+            Container.OGG -> context.contentResolver.openInputStream(uri)?.use { readOgg(it) }+            Container.FLAC -> context.contentResolver.openInputStream(uri)?.use { readFlac(it) }+            Container.MP4 -> readMp4(context, uri)+            null -> null+        }+    } catch (_: Exception) {+        null+    }++    private enum class Container { OGG, FLAC, MP4 }++    /** Sniffs the container from the first few bytes rather than trusting a URI's extension. */+    private fun containerOf(context: Context, uri: Uri): Container? {+        val magic = context.contentResolver.openInputStream(uri)?.use { it.readNBytesCompat(12) }+            ?: return null+        if (magic.size < 12) return null+        return when {+            String(magic, 0, 4, Charsets.ISO_8859_1) == "OggS" -> Container.OGG+            String(magic, 0, 4, Charsets.ISO_8859_1) == "fLaC" -> Container.FLAC+            String(magic, 4, 4, Charsets.ISO_8859_1) == "ftyp" -> Container.MP4+            else -> null+        }+    }++    // ------------------------------------------------------------------+    // Ogg (Vorbis comments in the second packet)+    // ------------------------------------------------------------------++    private fun readOgg(input: InputStream): String? {+        val data = input.readNBytesCompat(OGG_SCAN_BYTES)+        var offset = 0+        var packetIndex = 0+        val packet = java.io.ByteArrayOutputStream()+        while (offset + 27 <= data.size) {+            if (String(data, offset, 4, Charsets.ISO_8859_1) != "OggS") break+            val segmentCount = data[offset + 26].toInt() and 0xff+            val tableStart = offset + 27+            if (tableStart + segmentCount > data.size) break+            var payloadSize = 0+            var packetEnds = false+            for (i in 0 until segmentCount) {+                val segment = data[tableStart + i].toInt() and 0xff+                payloadSize += segment+                if (segment < 255) packetEnds = true+            }+            val payloadStart = tableStart + segmentCount+            if (payloadStart + payloadSize > data.size) break+            packet.write(data, payloadStart, payloadSize)+            if (packetEnds) {+                val bytes = packet.toByteArray()+                packet.reset()+                if (packetIndex == 1) return lyricsFromCommentPacket(bytes)+                packetIndex+++            }+            offset = payloadStart + payloadSize+        }+        return null+    }++    private fun lyricsFromCommentPacket(packet: ByteArray): String? = when {+        packet.size > 8 && String(packet, 0, 8, Charsets.ISO_8859_1) == "OpusTags" ->+            lyricsFromVorbisComments(packet, 8)+        packet.size > 7 && String(packet, 1, 6, Charsets.ISO_8859_1) == "vorbis" ->+            lyricsFromVorbisComments(packet, 7)+        else -> null+    }++    // ------------------------------------------------------------------+    // FLAC (Vorbis comment metadata block)+    // ------------------------------------------------------------------++    private fun readFlac(input: InputStream): String? {+        val magic = input.readNBytesCompat(4)+        if (magic.size < 4 || String(magic, Charsets.ISO_8859_1) != "fLaC") return null+        while (true) {+            val header = input.readNBytesCompat(4)+            if (header.size < 4) return null+            val flags = header[0].toInt() and 0xff+            val isLast = flags and 0x80 != 0+            val blockType = flags and 0x7f+            val length = ((header[1].toInt() and 0xff) shl 16) or+                ((header[2].toInt() and 0xff) shl 8) or+                (header[3].toInt() and 0xff)+            if (length < 0 || length > OGG_SCAN_BYTES) return null+            val block = input.readNBytesCompat(length)+            if (block.size < length) return null+            if (blockType == 4) return lyricsFromVorbisComments(block, 0)+            if (isLast) return null+        }+    }++    private fun lyricsFromVorbisComments(buf: ByteArray, start: Int): String? {+        var offset = start+        if (offset + 4 > buf.size) return null+        val vendorLength = readIntLe(buf, offset)+        offset += 4 + vendorLength+        if (offset + 4 > buf.size || vendorLength < 0) return null+        val count = readIntLe(buf, offset)+        offset += 4+        if (count < 0 || count > 10_000) return null+        repeat(count) {+            if (offset + 4 > buf.size) return null+            val length = readIntLe(buf, offset)+            offset += 4+            if (length < 0 || offset + length > buf.size) return null+            val entry = String(buf, offset, length, Charsets.UTF_8)+            offset += length+            val separator = entry.indexOf('=')+            if (separator > 0 && entry.substring(0, separator).equals("LYRICS", ignoreCase = true)) {+                return entry.substring(separator + 1).ifBlank { null }+            }+        }+        return null+    }++    // ------------------------------------------------------------------+    // MP4 / M4A (iTunes ©lyr atom)+    // ------------------------------------------------------------------++    private fun readMp4(context: Context, uri: Uri): String? =+        context.contentResolver.openFileDescriptor(uri, "r")?.use { pfd ->+            FileInputStream(pfd.fileDescriptor).use { input -> readMp4(input.channel) }+        }++    private fun readMp4(channel: FileChannel): String? {+        val size = channel.size()+        var position = 0L+        while (position < size) {+            if (position + 8 > size) break+            val head = ByteBuffer.allocate(8)+            channel.position(position)+            while (head.hasRemaining()) {+                if (channel.read(head) < 0) return null+            }+            head.flip()+            val declared = head.int.toLong() and 0xffffffffL+            val type = String(ByteArray(4) { head.get() }, Charsets.ISO_8859_1)+            val contentStart = position + 8+            val end = when {+                declared == 1L -> {+                    val ext = ByteBuffer.allocate(8)+                    channel.position(position + 8)+                    while (ext.hasRemaining()) {+                        if (channel.read(ext) < 0) return null+                    }+                    ext.flip()+                    position + ext.long+                }+                declared == 0L -> size+                declared < 8L -> return null+                else -> position + declared+            }+            if (end <= position || end > size) return null+            if (type == "moov") {+                val payloadSize = end - contentStart+                if (payloadSize <= 0 || payloadSize > MAX_MOOV_BYTES) return null+                val buffer = ByteBuffer.allocate(payloadSize.toInt())+                channel.position(contentStart)+                while (buffer.hasRemaining()) {+                    if (channel.read(buffer) < 0) return null+                }+                val ilst = findIlst(buffer.array()) ?: return null+                return lyricsFromIlst(ilst)+            }+            position = end+        }+        return null+    }++    private fun findIlst(moov: ByteArray): ByteArray? {+        fun descend(start: Int, end: Int, path: List<String>): ByteArray? {+            var offset = start+            while (offset + 8 <= end) {+                val size = readIntBe(moov, offset)+                val type = String(moov, offset + 4, 4, Charsets.ISO_8859_1)+                val boxEnd = if (size == 0) end else offset + size+                if (size < 8 || boxEnd > end) return null+                if (type == path.first()) {+                    val contentStart = if (type == "meta") offset + 12 else offset + 8+                    if (path.size == 1) {+                        return moov.copyOfRange(contentStart.coerceAtMost(boxEnd), boxEnd)+                    }+                    descend(contentStart, boxEnd, path.drop(1))?.let { return it }+                }+                offset = boxEnd+            }+            return null+        }+        return descend(0, moov.size, listOf("udta", "meta", "ilst"))+    }++    private fun lyricsFromIlst(ilst: ByteArray): String? {+        var offset = 0+        while (offset + 8 <= ilst.size) {+            val size = readIntBe(ilst, offset)+            if (size < 8 || offset + size > ilst.size) break+            val type = String(ilst, offset + 4, 4, Charsets.ISO_8859_1)+            if (type == "\u00A9lyr") {+                var inner = offset + 8+                while (inner + 8 <= offset + size) {+                    val dataSize = readIntBe(ilst, inner)+                    if (dataSize < 8 || inner + dataSize > offset + size) break+                    if (String(ilst, inner + 4, 4, Charsets.ISO_8859_1) == "data") {+                        val payloadStart = inner + 16+                        val payloadEnd = inner + dataSize+                        if (payloadStart < payloadEnd) {+                            return String(ilst, payloadStart, payloadEnd - payloadStart, Charsets.UTF_8)+                                .ifBlank { null }+                        }+                    }+                    inner += dataSize+                }+            }+            offset += size+        }+        return null+    }++    // ------------------------------------------------------------------++    private fun readIntBe(buf: ByteArray, offset: Int): Int =+        ((buf[offset].toInt() and 0xff) shl 24) or+            ((buf[offset + 1].toInt() and 0xff) shl 16) or+            ((buf[offset + 2].toInt() and 0xff) shl 8) or+            (buf[offset + 3].toInt() and 0xff)++    private fun readIntLe(buf: ByteArray, offset: Int): Int =+        ByteBuffer.wrap(buf, offset, 4).order(ByteOrder.LITTLE_ENDIAN).int++    private fun InputStream.readNBytesCompat(count: Int): ByteArray {+        val out = ByteArray(count)+        var read = 0+        while (read < count) {+            val n = read(out, read, count - read)+            if (n < 0) break+            read += n+        }+        return if (read == count) out else out.copyOf(read)+    }+}
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.ktnew file mode 100644index 0000000000..ca79243417--- /dev/null+++ b/music/src/main/java/com/vayunmathur/music/platform/MusicUiContract.kt@@ -0,0 +1,84 @@+package com.vayunmathur.music.platform++import android.net.Uri+import androidx.media3.common.Player+import com.vayunmathur.music.data.Music++/**+ * The UI contract between [MusicViewModel] and the screens.+ *+ * Screens take a state value plus an actions interface rather than the ViewModel itself,+ * so they can be rendered by a `@Preview` — which is what the store listing images are+ * generated from. It lives in `util` rather than `ui` so the dependency runs one way:+ * `ui` depends on `util`, and the ViewModel implements the actions interface.+ */++/** Everything the songs list draws. */+data class SongsUiState(+    val songs: List<Music> = emptyList(),+    /** Row to highlight — the loaded track, but only while it is playing from this list. */+    val playingSongId: Long? = null,+)++/** Everything the album detail screen draws. */+data class AlbumDetailUiState(+    val albumId: Long = 0,+    val name: String = "",+    val artUri: Uri? = null,+    /** Artist name(s) for the album, shown under the title. */+    val artistName: String = "",+    /** The artist to open when the name is tapped, or null when there isn't a single one. */+    val artistId: Long? = null,+    /** Pre-formatted "year • n songs • duration" line (see `album_info_format`). */+    val info: String = "",+    val tracks: List<Music> = emptyList(),+    val playingSongId: Long? = null,+)++/**+ * The loaded track plus transport state, shared by the now-playing bar and the full+ * player screen. Absent (null) when the queue is empty.+ */+data class NowPlayingUiState(+    val title: String = "",+    val artist: String = "",+    /** Album name of the loaded track, empty when unknown. */+    val album: String = "",+    val artworkUri: Uri? = null,+    val isPlaying: Boolean = false,+    val positionMs: Long = 0,+    val durationMs: Long = 0,+    val shuffle: Boolean = false,+    val repeatMode: Int = Player.REPEAT_MODE_OFF,+    /** The artist to open when the name is tapped, or null when the track isn't in the library. */+    val artistId: Long? = null,+    /** The album to open when tapped, or null when the track isn't in the library. */+    val albumId: Long? = null,+    /** Queue origin, as stored on the queue — see [PlaybackSource.parse]. */+    val sourceId: String? = null,+    /** Human-readable name of the queue origin, for the "Go to …" shortcut. */+    val sourceName: String? = null,+    /** Raw embedded lyrics (LRC or plain), empty when the file carries none. */+    val lyrics: String = "",+)++/**+ * Playback callbacks. Every method has a no-op default so a preview can render a screen+ * without supplying behaviour — [Noop] is the whole implementation a preview needs. The+ * signatures match [MusicViewModel]'s existing methods, which is why the ViewModel can+ * implement this directly rather than through an adapter.+ */+interface MusicActions {+    fun playSong(songs: List<Music>, startWithIndex: Int, sourceId: String? = null, sourceName: String? = null) {}+    fun playShuffled(songs: List<Music>, sourceId: String? = null, sourceName: String? = null) {}+    fun togglePlayPause() {}+    fun seekTo(pos: Long) {}+    fun skipNext() {}+    fun skipPrevious() {}+    fun toggleShuffle() {}+    fun toggleRepeat() {}++    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.ktnew file mode 100644index 0000000000..c4249f23da--- /dev/null+++ b/music/src/main/java/com/vayunmathur/music/platform/MusicViewModel.kt@@ -0,0 +1,229 @@+package com.vayunmathur.music.platform++import android.app.Application+import androidx.compose.runtime.Composable+import androidx.compose.runtime.State+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.derivedStateOf+import androidx.compose.runtime.getValue+import androidx.compose.runtime.produceState+import androidx.compose.runtime.remember+import androidx.compose.ui.res.stringResource+import androidx.core.net.toUri+import androidx.lifecycle.AndroidViewModel+import androidx.lifecycle.ViewModel+import androidx.lifecycle.ViewModelProvider+import androidx.lifecycle.viewModelScope+import androidx.media3.common.MediaItem+import com.vayunmathur.library.util.ManyManyMatching+import com.vayunmathur.music.R+import com.vayunmathur.music.data.Album+import com.vayunmathur.music.data.Artist+import com.vayunmathur.music.data.Music+import com.vayunmathur.music.data.MusicRepository+import com.vayunmathur.music.data.Playlist+import com.vayunmathur.music.data.TYPE_ALBUM_ARTIST+import com.vayunmathur.music.data.TYPE_MUSIC_PLAYLIST+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.flow.SharingStarted+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.stateIn+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext++/**+ * ViewModel for the Music app.+ *+ * Owns:+ *  - direct repo access for all four entities (Music, Album, Artist, Playlist)+ *  - playlist editing actions (create, rename, add track) routed through the repo+ *+ * Mirrors (does not duplicate the source of truth):+ *  - [PlaybackManager] state and playback actions.+ */+class MusicViewModel(+    application: Application,+    private val repository: MusicRepository,+    private val playbackManager: PlaybackManager,+) : AndroidViewModel(application), MusicActions {++    // --- Entity StateFlows ---+    val music: StateFlow<List<Music>> = repository.music+        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())+    val albums: StateFlow<List<Album>> = repository.albums+        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())+    val artists: StateFlow<List<Artist>> = repository.artists+        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())+    val playlists: StateFlow<List<Playlist>> = repository.playlists+        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())++    private val matchings: StateFlow<List<ManyManyMatching>> = repository.matchings+        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())++    // --- PlaybackManager state mirror ---+    val isPlaying: StateFlow<Boolean> = playbackManager.isPlaying+    val currentPosition: StateFlow<Long> = playbackManager.currentPosition+    val duration: StateFlow<Long> = playbackManager.duration+    val shuffleMode: StateFlow<Boolean> = playbackManager.shuffleMode+    val repeatMode: StateFlow<Int> = playbackManager.repeatMode+    val currentMediaItem: StateFlow<MediaItem?> = playbackManager.currentMediaItem+    val currentSource: StateFlow<String?> = playbackManager.currentSource+    val currentSourceName: StateFlow<String?> = playbackManager.currentSourceName++    override fun playSong(songs: List<Music>, startWithIndex: Int, sourceId: String?, sourceName: String?) =+        playbackManager.playSong(songs, startWithIndex, sourceId, sourceName)++    override fun playShuffled(songs: List<Music>, sourceId: String?, sourceName: String?) =+        playbackManager.playShuffled(songs, sourceId, sourceName)++    override fun togglePlayPause() { playbackManager.togglePlayPause() }+    override fun seekTo(pos: Long) = playbackManager.seekTo(pos)+    override fun skipNext() { playbackManager.skipNext() }+    override fun skipPrevious() { playbackManager.skipPrevious() }+    override fun toggleShuffle() = playbackManager.toggleShuffle()+    override fun toggleRepeat() = playbackManager.toggleRepeat()++    @Composable+    fun nowPlayingState(): NowPlayingUiState? {+        val item by currentMediaItem.collectAsState()+        val playing by isPlaying.collectAsState()+        val position by currentPosition.collectAsState()+        val total by duration.collectAsState()+        val shuffle by shuffleMode.collectAsState()+        val repeat by repeatMode.collectAsState()+        val sourceId by currentSource.collectAsState()+        val sourceName by currentSourceName.collectAsState()+        val unknownTitle = stringResource(R.string.unknown_title)+        val unknownArtist = stringResource(R.string.unknown_artist)+        val metadata = item?.mediaMetadata ?: return null+        val songs by music.collectAsState()+        val song = item?.mediaId?.let { id -> songs.firstOrNull { it.id.toString() == id } }+        val songUri = song?.uri+        val application = getApplication<Application>()+        val lyrics by produceState("", songUri) {+            value = songUri?.let { uri ->+                withContext(Dispatchers.IO) { EmbeddedLyrics.read(application, uri.toUri()) }+            }.orEmpty()+        }+        return NowPlayingUiState(+            title = metadata.title?.toString() ?: unknownTitle,+            artist = metadata.artist?.toString() ?: unknownArtist,+            album = song?.album ?: metadata.albumTitle?.toString() ?: "",+            artworkUri = metadata.artworkUri,+            isPlaying = playing,+            positionMs = position,+            durationMs = total,+            shuffle = shuffle,+            repeatMode = repeat,+            artistId = song?.artistId,+            albumId = song?.albumId,+            sourceId = sourceId,+            sourceName = sourceName,+            lyrics = lyrics,+        )+    }++    @Composable+    fun playingSongIdFrom(sourceId: String): Long? {+        val item by currentMediaItem.collectAsState()+        val source by currentSource.collectAsState()+        return item?.mediaId?.toLongOrNull()?.takeIf { source == sourceId }+    }++    @Composable+    fun musicState(id: Long): State<Music?> {+        val list by music.collectAsState()+        return remember(id, list) { derivedStateOf { list.firstOrNull { it.id == id } } }+    }++    @Composable+    fun albumState(id: Long): State<Album?> {+        val list by albums.collectAsState()+        return remember(id, list) { derivedStateOf { list.firstOrNull { it.id == id } } }+    }++    @Composable+    fun artistState(id: Long): State<Artist?> {+        val list by artists.collectAsState()+        return remember(id, list) { derivedStateOf { list.firstOrNull { it.id == id } } }+    }++    @Composable+    fun playlistState(id: Long): State<Playlist?> {+        val list by playlists.collectAsState()+        return remember(id, list) { derivedStateOf { list.firstOrNull { it.id == id } } }+    }++    @Composable+    fun matchedAlbumsForArtist(artistId: Long): State<List<Long>> {+        val all by matchings.collectAsState()+        return remember(artistId, all) {+            derivedStateOf { all.filter { it.rightID == artistId && it.type == TYPE_ALBUM_ARTIST }.map { it.leftID } }+        }+    }++    @Composable+    fun matchedArtistsForAlbum(albumId: Long): State<List<Long>> {+        val all by matchings.collectAsState()+        return remember(albumId, all) {+            derivedStateOf { all.filter { it.leftID == albumId && it.type == TYPE_ALBUM_ARTIST }.map { it.rightID } }+        }+    }++    @Composable+    fun matchedMusicForPlaylist(playlistId: Long): State<List<Long>> {+        val all by matchings.collectAsState()+        return remember(playlistId, all) {+            derivedStateOf { all.filter { it.rightID == playlistId && it.type == TYPE_MUSIC_PLAYLIST }.map { it.leftID } }+        }+    }++    suspend fun getMusicInPlaylist(playlistId: Long): List<Long> =+        repository.getFromRight(playlistId, TYPE_MUSIC_PLAYLIST)++    fun createPlaylist(name: String, onCreated: (Long) -> Unit = {}) {+        viewModelScope.launch(Dispatchers.IO) {+            val id = repository.upsertPlaylist(Playlist(name = name))+            onCreated(id)+        }+    }++    fun renamePlaylist(playlist: Playlist, newName: String) {+        viewModelScope.launch(Dispatchers.IO) { repository.upsertPlaylist(playlist.copy(name = newName)) }+    }++    fun deletePlaylist(playlist: Playlist, onDone: () -> Unit = {}) {+        viewModelScope.launch(Dispatchers.IO) {+            repository.deleteFromRight(playlist.id, TYPE_MUSIC_PLAYLIST)+            repository.deletePlaylistById(playlist.id)+            onDone()+        }+    }++    fun addMusicToPlaylist(playlistId: Long, musicId: Long, onDone: () -> Unit = {}) {+        viewModelScope.launch(Dispatchers.IO) {+            repository.upsertMatching(ManyManyMatching(musicId, playlistId, TYPE_MUSIC_PLAYLIST))+            onDone()+        }+    }++    fun removeMusicFromPlaylist(playlistId: Long, musicId: Long, onDone: () -> Unit = {}) {+        viewModelScope.launch(Dispatchers.IO) {+            repository.deleteMatch(musicId, playlistId, TYPE_MUSIC_PLAYLIST)+            onDone()+        }+    }+}++/** Factory for constructing [MusicViewModel] with shared dependencies. */+class MusicViewModelFactory(+    private val application: Application,+    private val repository: MusicRepository,+    private val playbackManager: PlaybackManager,+) : ViewModelProvider.Factory {+    @Suppress("UNCHECKED_CAST")+    override fun <T : ViewModel> create(modelClass: Class<T>): T {+        require(modelClass.isAssignableFrom(MusicViewModel::class.java)) { "Unexpected ViewModel class: $modelClass" }+        return MusicViewModel(application, repository, playbackManager) as T+    }+}
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.ktnew file mode 100644index 0000000000..078968fbb9--- /dev/null+++ b/music/src/main/java/com/vayunmathur/music/platform/PlaybackManager.kt@@ -0,0 +1,199 @@+package com.vayunmathur.music.platform+import android.annotation.SuppressLint+import android.content.ComponentName+import android.content.Context+import androidx.core.net.toUri+import androidx.media3.common.MediaItem+import androidx.media3.common.MediaMetadata+import androidx.media3.common.Player+import androidx.media3.session.MediaController+import androidx.media3.session.SessionToken+import com.google.common.util.concurrent.MoreExecutors+import com.vayunmathur.music.data.Music+import com.vayunmathur.music.service.PlaybackService+import kotlinx.coroutines.*+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.flow.collectLatest+import kotlin.random.Random++/** Typed model of a playback queue's origin, encoded as the string id stored on each queue. */+sealed interface PlaybackSource {+    val id: String++    data object AllSongs : PlaybackSource {+        override val id = "all_songs"+    }++    data class Album(val albumId: Long) : PlaybackSource {+        override val id = "album_$albumId"+    }++    data class Playlist(val playlistId: Long) : PlaybackSource {+        override val id = "playlist_$playlistId"+    }++    data class Artist(val artistId: Long) : PlaybackSource {+        override val id = "artist_$artistId"+    }++    companion object {+        fun parse(id: String?): PlaybackSource? = when {+            id == null -> null+            id == AllSongs.id -> AllSongs+            id.startsWith("album_") -> id.removePrefix("album_").toLongOrNull()?.let(::Album)+            id.startsWith("playlist_") -> id.removePrefix("playlist_").toLongOrNull()?.let(::Playlist)+            id.startsWith("artist_") -> id.removePrefix("artist_").toLongOrNull()?.let(::Artist)+            else -> null+        }+    }+}++class PlaybackManager private constructor(context: Context) {++    private var controller: MediaController? = null+    private val scope = CoroutineScope(Dispatchers.Main + SupervisorJob())++    // Observables for the UI+    private val _isPlaying = MutableStateFlow(false)+    val isPlaying = _isPlaying.asStateFlow()++    private val _currentPosition = MutableStateFlow(0L)+    val currentPosition = _currentPosition.asStateFlow()++    private val _duration = MutableStateFlow(0L)+    val duration = _duration.asStateFlow()++    private val _shuffleMode = MutableStateFlow(false)+    val shuffleMode = _shuffleMode.asStateFlow()++    private val _repeatMode = MutableStateFlow(Player.REPEAT_MODE_OFF)+    val repeatMode = _repeatMode.asStateFlow()++    private val _currentMediaItem = MutableStateFlow<MediaItem?>(null)+    val currentMediaItem = _currentMediaItem.asStateFlow()++    private val _currentSource = MutableStateFlow<String?>(null)+    val currentSource = _currentSource.asStateFlow()++    private val _currentSourceName = MutableStateFlow<String?>(null)+    val currentSourceName = _currentSourceName.asStateFlow()++    init {+        val appContext = context.applicationContext+        val sessionToken = SessionToken(appContext, ComponentName(appContext, PlaybackService::class.java))+        val controllerFuture = MediaController.Builder(appContext, sessionToken).buildAsync()++        controllerFuture.addListener({+            try {+                controller = controllerFuture.get().apply {+                    addListener(object : Player.Listener {+                        override fun onIsPlayingChanged(playing: Boolean) {+                            _isPlaying.value = playing+                        }+                        override fun onMediaItemTransition(mediaItem: MediaItem?, reason: Int) {+                            _currentMediaItem.value = mediaItem+                        }++                        override fun onShuffleModeEnabledChanged(enabled: Boolean) {+                            _shuffleMode.value = enabled+                        }++                        override fun onRepeatModeChanged(mode: Int) {+                            _repeatMode.value = mode+                        }+                    })+                }+                startProgressUpdateLoop()+            } catch (e: Exception) {+                android.util.Log.e("PlaybackManager", "Error initializing MediaController", e)+            }+        }, MoreExecutors.directExecutor())+    }++    private fun startProgressUpdateLoop() {+        scope.launch {+            _isPlaying.collectLatest { playing ->+                if (!playing) return@collectLatest+                while (true) {+                    controller?.let {+                        _currentPosition.value = it.currentPosition+                        _duration.value = it.duration.coerceAtLeast(0L)+                    }+                    delay(1000)+                }+            }+        }+    }++    fun playSong(songs: List<Music>, startWithIndex: Int, sourceId: String? = null, sourceName: String? = null) {+        if (songs.isEmpty() || startWithIndex !in songs.indices) return+        _currentSource.value = sourceId+        _currentSourceName.value = sourceName+        playSongsInternal(songs, startWithIndex, shuffle = false)+    }++    fun playShuffled(songs: List<Music>, sourceId: String? = null, sourceName: String? = null) {+        if (songs.isEmpty()) return+        _currentSource.value = sourceId+        _currentSourceName.value = sourceName+        val startWithIndex = Random.nextInt(songs.size)+        playSongsInternal(songs, startWithIndex, shuffle = true)+    }++    private fun playSongsInternal(songs: List<Music>, startWithIndex: Int, shuffle: Boolean) {+        if (songs.isEmpty() || startWithIndex !in songs.indices) return+        val player = controller ?: return++        player.repeatMode = Player.REPEAT_MODE_ALL+        player.shuffleModeEnabled = shuffle++        val mediaItems = songs.map { song ->+            MediaItem.Builder()+                .setMediaId(song.id.toString())+                .setUri(song.uri.toUri())+                .setMediaMetadata(+                    MediaMetadata.Builder()+                        .setTitle(song.title)+                        .setArtist(song.artist)+                        .setArtworkUri(song.uri.toUri())+                        .build()+                )+                .build()+        }++        player.stop()+        player.setMediaItems(mediaItems, startWithIndex, 0L)+        player.prepare()+        player.play()+    }++    fun togglePlayPause() = controller?.let { if (it.isPlaying) it.pause() else it.play() }+    fun seekTo(pos: Long) {+        controller?.seekTo(pos)+        _currentPosition.value = pos+    }+    fun skipNext() = controller?.seekToNext()+    fun skipPrevious() = controller?.seekToPrevious()++    fun toggleShuffle() {+        controller?.let { it.shuffleModeEnabled = !it.shuffleModeEnabled }+    }++    fun toggleRepeat() {+        controller?.let {+            it.repeatMode = when (it.repeatMode) {+                Player.REPEAT_MODE_OFF -> Player.REPEAT_MODE_ONE+                Player.REPEAT_MODE_ONE -> Player.REPEAT_MODE_ALL+                else -> Player.REPEAT_MODE_OFF+            }+        }+    }++    companion object {+        @SuppressLint("StaticFieldLeak")+        @Volatile private var INSTANCE: PlaybackManager? = null+        fun getInstance(context: Context): PlaybackManager =+            INSTANCE ?: synchronized(this) { INSTANCE ?: PlaybackManager(context).also { INSTANCE = it } }+    }+}\ No newline at end of file
music/src/main/java/com/vayunmathur/music/platform/SyncWorker.kt
diff --git a/music/src/main/java/com/vayunmathur/music/platform/SyncWorker.kt b/music/src/main/java/com/vayunmathur/music/platform/SyncWorker.ktnew file mode 100644index 0000000000..37d9381ff9--- /dev/null+++ b/music/src/main/java/com/vayunmathur/music/platform/SyncWorker.kt@@ -0,0 +1,224 @@+package com.vayunmathur.music.platform+import android.content.ContentUris+import android.content.Context+import android.net.Uri+import android.provider.MediaStore+import android.util.Log+import androidx.work.Constraints+import androidx.work.CoroutineWorker+import androidx.work.ExistingWorkPolicy+import androidx.work.OneTimeWorkRequestBuilder+import androidx.work.WorkManager+import androidx.work.WorkerParameters+import androidx.work.ListenableWorker.Result as WorkResult+import com.vayunmathur.library.util.DataStoreUtils+import com.vayunmathur.library.util.ManyManyMatching+import com.vayunmathur.music.data.Music+import com.vayunmathur.music.data.MusicRepository+import com.vayunmathur.music.data.TYPE_ALBUM_ARTIST+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext+import java.util.concurrent.TimeUnit++class SyncWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) {+    override suspend fun doWork(): WorkResult = withContext(Dispatchers.IO) {+        val repo = MusicRepository.get(applicationContext)++        val dataStore = DataStoreUtils.getInstance(applicationContext)+        val lastGeneration = dataStore.getLong("last_music_generation") ?: 0L+        val currentGeneration = MediaStore.getGeneration(applicationContext, MediaStore.VOLUME_EXTERNAL)++        val triggeredUris = triggeredContentUris+        if (triggeredUris.isNotEmpty()) {+            syncMusic(applicationContext, repo, triggeredUris.toList())+        } else {+            syncMusic(applicationContext, repo, null, lastGeneration)+        }++        dataStore.setLong("last_music_generation", currentGeneration)++        // Enqueue next observation+        enqueue(applicationContext)++        WorkResult.success()+    }++    companion object {+        private const val WORK_NAME = "MusicSyncWorker"++        fun enqueue(context: Context) {+            val constraints = Constraints.Builder()+                .addContentUriTrigger(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, true)+                .addContentUriTrigger(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, true)+                .addContentUriTrigger(MediaStore.Audio.Artists.EXTERNAL_CONTENT_URI, true)+                .setTriggerContentUpdateDelay(1, TimeUnit.SECONDS)+                .setTriggerContentMaxDelay(5, TimeUnit.SECONDS)+                .build()++            val request = OneTimeWorkRequestBuilder<SyncWorker>()+                .setConstraints(constraints)+                .build()++            WorkManager.getInstance(context).enqueueUniqueWork(+                WORK_NAME,+                ExistingWorkPolicy.REPLACE,+                request+            )+        }++        fun runOnce(context: Context) {+            val request = OneTimeWorkRequestBuilder<SyncWorker>().build()+            WorkManager.getInstance(context).enqueue(request)+        }+    }+}++suspend fun syncMusic(context: Context, repo: MusicRepository, uris: List<Uri>? = null, lastGeneration: Long = 0L) {++    // 1. Get all current IDs in MediaStore to handle deletions correctly+    val allMediaStoreIds = mutableSetOf<Long>()+    try {+        context.contentResolver.query(+            MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,+            arrayOf(MediaStore.Audio.Media._ID),+            "${MediaStore.Audio.Media.IS_MUSIC} != 0",+            null,+            null+        )?.use { cursor ->+            val idCol = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID)+            while (cursor.moveToNext()) {+                allMediaStoreIds.add(cursor.getLong(idCol))+            }+        }+    } catch (e: Exception) {+        Log.e("MusicSyncWorker", "Error querying MediaStore for music IDs", e)+    }++    // 2. Handle deletions+    val toDelete = if (uris != null) {+        val triggeredIds = uris.mapNotNull { runCatching { ContentUris.parseId(it) }.getOrNull() }.toSet()+        triggeredIds - allMediaStoreIds+    } else {+        val localIds = repo.getAllMusic().map { it.id }.toSet()+        localIds - allMediaStoreIds+    }++    if (toDelete.isNotEmpty()) {+        toDelete.chunked(900).forEach { chunk ->+            repo.deleteMusicByIds(chunk)+        }+    }++    // 3. Process incremental or full updates for Music+    val musicList = mutableListOf<Music>()+    val projection = arrayOf(+        MediaStore.Audio.Media._ID,+        MediaStore.Audio.Media.TITLE,+        MediaStore.Audio.Media.ARTIST,+        MediaStore.Audio.Media.ARTIST_ID,+        MediaStore.Audio.Media.ALBUM,+        MediaStore.Audio.Media.ALBUM_ID,+        MediaStore.Audio.Media.DURATION,+        MediaStore.Audio.Media.TRACK,+        MediaStore.Audio.Media.YEAR+    )++    val selection = when {+        uris != null -> {+            val ids = uris.mapNotNull { runCatching { ContentUris.parseId(it) }.getOrNull() }+            if (ids.isEmpty()) "${MediaStore.Audio.Media.IS_MUSIC} != 0"+            else "${MediaStore.Audio.Media.IS_MUSIC} != 0 AND ${MediaStore.Audio.Media._ID} IN (${ids.joinToString(",")})"+        }+        lastGeneration > 0 -> {+            "${MediaStore.Audio.Media.IS_MUSIC} != 0 AND ${MediaStore.MediaColumns.GENERATION_MODIFIED} > $lastGeneration"+        }+        else -> "${MediaStore.Audio.Media.IS_MUSIC} != 0"+    }++    try {+        context.contentResolver.query(+            MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,+            projection,+            selection,+            null,+            null+        )?.use { cursor ->+            val idColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID)+            val titleColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE)+            val artistColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST)+            val albumColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM)+            val artistIDColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST_ID)+            val albumIDColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID)+            val durationColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION)+            val trackColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TRACK)+            val yearColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.YEAR)++            while (cursor.moveToNext()) {+                val id = cursor.getLong(idColumn)+                val title = cursor.getString(titleColumn)+                val artist = cursor.getString(artistColumn)+                val album = cursor.getString(albumColumn)+                val artistID = cursor.getLong(artistIDColumn)+                val albumID = cursor.getLong(albumIDColumn)+                val contentUriObject = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, id)+                val contentUri = contentUriObject.toString()++                var duration = cursor.getLong(durationColumn)++                if (duration == 0L) {+                    duration = getRealAudioDuration(context, contentUriObject)+                }++                val rawTrack = cursor.getInt(trackColumn)+                // MediaStore encodes multi-disc numbers as disc*1000 + track, so a value of+                // 2005 is disc 2, track 5. Split them apart instead of discarding the disc.+                val discNumber = if (rawTrack >= 1000) rawTrack / 1000 else 1+                val trackNumber = if (rawTrack >= 1000) rawTrack % 1000 else rawTrack+                // Read the year straight from MediaStore. Only fall back to the+                // (expensive, per-file) metadata retriever when it's missing.+                val year = cursor.getInt(yearColumn).takeIf { it > 0 }+                    ?: getAudioYear(context, contentUriObject)++                musicList.add(Music(id, title, artist, artistID, album, albumID, contentUri, duration, trackNumber, year, discNumber))+            }+        }+    } catch (e: Exception) {+        Log.e("MusicSyncWorker", "Error querying MediaStore for music", e)+    }++    if (uris == null && lastGeneration == 0L) {+        // Full refresh: wipe + reinsert.+        repo.deleteAllMusic()+        repo.upsertAllMusic(musicList)+    } else {+        repo.upsertAllMusic(musicList)+        // Incremental trigger that changed nothing relevant: skip the (whole-+        // library) album/artist + matching rebuild below.+        if (musicList.isEmpty() && toDelete.isEmpty()) return+    }++    // 4. Always refresh Albums and Artists completely to ensure consistency+    val albums = getAlbums(context)+    val artists = getArtists(context)++    repo.deleteAllAlbums()+    repo.upsertAllAlbums(albums)+    repo.deleteAllArtists()+    repo.upsertAllArtists(artists)++    // 5. Rebuild relationship matchings+    val allMusic = repo.getAllMusic()+    val allAlbums = repo.getAllAlbums()+    val allArtists = repo.getAllArtists()++    Log.d("MusicSyncWorker", "Rebuilding matchings: Music=${allMusic.size}, Albums=${allAlbums.size}, Artists=${allArtists.size}")++    val pairs = albumArtistPairs(allMusic, allArtists, allAlbums)+    Log.d("MusicSyncWorker", "Rebuilding matchings: ${pairs.size} pairs found")++    // Album index (1) < Artist index (2) → album is left, artist is right.+    repo.deleteByType(TYPE_ALBUM_ARTIST)+    repo.upsertMatchings(pairs.map { (album, artist) ->+        ManyManyMatching(album.id, artist.id, TYPE_ALBUM_ARTIST)+    })+}
music/src/main/java/com/vayunmathur/music/platform/Util.kt
diff --git a/music/src/main/java/com/vayunmathur/music/platform/Util.kt b/music/src/main/java/com/vayunmathur/music/platform/Util.ktnew file mode 100644index 0000000000..beaefabbd0--- /dev/null+++ b/music/src/main/java/com/vayunmathur/music/platform/Util.kt@@ -0,0 +1,307 @@+package com.vayunmathur.music.platform+import com.vayunmathur.music.R+import android.content.ContentUris+import android.content.Context+import android.graphics.Bitmap+import android.graphics.Canvas+import android.graphics.Rect+import android.media.MediaMetadataRetriever+import android.net.Uri+import android.provider.MediaStore+import android.util.Log+import android.util.Size+import androidx.collection.LruCache+import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.fillMaxSize+import com.vayunmathur.library.ui.IconAlbum+import com.vayunmathur.library.ui.IconMoreVert+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.MaterialTheme+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.platform.LocalInspectionMode+import androidx.core.graphics.createBitmap+import com.vayunmathur.library.image.compose.AsyncImage+import com.vayunmathur.library.image.ImageRequest+import com.vayunmathur.library.image.Size as CoilSize+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.music.Route+import com.vayunmathur.music.data.Album+import com.vayunmathur.music.data.Artist+import com.vayunmathur.music.data.Music+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext+import java.util.Locale+import androidx.compose.ui.res.stringResource++// Process-scope LRU for album thumbnails. Bounded so we don't retain decoded+// bitmaps for the entire library; 64 entries covers a typical visible list.+private val albumArtCache = LruCache<Uri, Bitmap>(64)++fun getThumbnail(context: Context, uri: Uri): Bitmap? {+    return try {+        context.contentResolver.loadThumbnail(+            uri,+            Size(300, 300),+            null+        )+    } catch (_: Exception) {+        null // Fallback to a placeholder+    }+}++fun albumArtistPairs(music: List<Music>, artists: List<Artist>, albums: List<Album>): List<Pair<Album, Artist>> {+    val albumMap = albums.associateBy { it.id }+    val artistMap = artists.associateBy { it.id }+    return music.mapNotNull { song ->+        val album = albumMap[song.albumId]+        val artist = artistMap[song.artistId]+        if (album != null && artist != null) album to artist+        else {+            if (album == null) Log.w("MusicUtil", "Song '${song.title}' has albumId ${song.albumId} but no matching album found")+            if (artist == null) Log.w("MusicUtil", "Song '${song.title}' has artistId ${song.artistId} but no matching artist found")+            null+        }+    }.distinct().also {+        Log.d("MusicUtil", "Computed ${it.size} unique album-artist pairs from ${music.size} songs")+    }+}++suspend fun getAlbums(context: Context): List<Album> = withContext(Dispatchers.IO) {+    val musicList = mutableListOf<Album>()+    val projection = arrayOf(+        MediaStore.Audio.Albums._ID,+        MediaStore.Audio.Albums.ALBUM,+        MediaStore.Audio.Albums.ARTIST,+        MediaStore.Audio.Albums.ARTIST_ID,+    )++    // Filter to only get music files+    val sortOrder = "${MediaStore.Audio.Albums.ALBUM} ASC"++    try {+        context.contentResolver.query(+            MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,+            projection,+            null,+            null,+            sortOrder+        )?.use { cursor ->+            val idColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Albums._ID)+            val titleColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Albums.ALBUM)++            while (cursor.moveToNext()) {+                val id = cursor.getLong(idColumn)+                val title = cursor.getString(titleColumn)+                val contentUri = ContentUris.withAppendedId(+                    MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,+                    id+                ).toString()+                musicList.add(Album(id, title, contentUri))+            }+        }+    } catch (e: Exception) {+        Log.e("MusicUtil", "Error querying albums", e)+    }+    return@withContext musicList+}++suspend fun getArtists(context: Context): List<Artist> = withContext(Dispatchers.IO) {+    val artistList = mutableListOf<Artist>()+    val projection = arrayOf(+        MediaStore.Audio.Artists._ID,+        MediaStore.Audio.Artists.ARTIST,+    )++    // Filter to only get music files+    val sortOrder = "${MediaStore.Audio.Artists.ARTIST} ASC"++    try {+        context.contentResolver.query(+            MediaStore.Audio.Artists.EXTERNAL_CONTENT_URI,+            projection,+            null,+            null,+            sortOrder+        )?.use { cursor ->+            val idColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Artists._ID)+            val titleColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Artists.ARTIST)++            while (cursor.moveToNext()) {+                val id = cursor.getLong(idColumn)+                val title = cursor.getString(titleColumn)+                val contentUri = ContentUris.withAppendedId(+                    MediaStore.Audio.Artists.EXTERNAL_CONTENT_URI,+                    id+                ).toString()+                artistList.add(Artist(id, title, contentUri))+            }+        }+    } catch (e: Exception) {+        Log.e("MusicUtil", "Error querying artists", e)+    }+    return@withContext artistList+}++/**+ * Stand-in for artwork that isn't there — either still decoding, or genuinely absent+ * (plenty of files carry no embedded cover). A blank gap reads as a layout bug; a tinted+ * tile with a record glyph reads as "no cover".+ */+@Composable+private fun AlbumArtPlaceholder(modifier: Modifier) {+    Box(+        modifier.background(MaterialTheme.colorScheme.surfaceContainerHighest),+        contentAlignment = Alignment.Center,+    ) {+        IconAlbum(+            modifier = Modifier.fillMaxSize(0.55f),+            tint = MaterialTheme.colorScheme.onSurfaceVariant,+        )+    }+}++@Composable+fun AlbumArt(artUri: Uri?, modifier: Modifier) {+    // Previews — including the ones the store listing images are rendered from — have no+    // MediaStore behind them, so skip the load entirely rather than churning through a+    // guaranteed-failing thumbnail read.+    if (artUri == null || LocalInspectionMode.current) {+        AlbumArtPlaceholder(modifier)+        return+    }+    val context = LocalContext.current+    // contentResolver.loadThumbnail handles MediaStore.Audio.Albums URIs (which+    // resolve to the underlying album art) where Coil's default fetcher+    // doesn't. Cache the decoded bitmap in a process-scope LRU keyed by URI so+    // the same album doesn't re-decode each time it scrolls in/out.+    var bitmap: Bitmap? by remember(artUri) { mutableStateOf(albumArtCache.get(artUri)) }+    LaunchedEffect(artUri) {+        if (bitmap == null) {+            val loaded = withContext(Dispatchers.IO) { getThumbnail(context, artUri) }+            if (loaded != null) albumArtCache.put(artUri, loaded)+            bitmap = loaded+        }+    }+    val loaded = bitmap+    if (loaded == null) {+        AlbumArtPlaceholder(modifier)+        return+    }+    AsyncImage(+        model = loaded,+        contentDescription = stringResource(R.string.content_desc_album_art),+        modifier = modifier+    )+}+@Composable+fun AlbumArt(artUris: List<Uri>, modifier: Modifier) {+    if (artUris.isEmpty() || LocalInspectionMode.current) {+        AlbumArtPlaceholder(modifier)+        return+    }+    val context = LocalContext.current+    var bitmap: Bitmap? by remember { mutableStateOf(null) }++    // Re-run whenever the list of URIs changes+    LaunchedEffect(artUris) {+        withContext(Dispatchers.IO) {+            bitmap = if (artUris.size > 1) {+                createCollageBitmap(context, artUris.take(4))+            } else {+                // Fallback for single image+                artUris.firstOrNull()?.let { getThumbnail(context, it) }+            }+        }+    }++    val loaded = bitmap+    if (loaded == null) {+        AlbumArtPlaceholder(modifier)+        return+    }+    AsyncImage(+        model = loaded,+        contentDescription = stringResource(R.string.content_desc_album_art_grid),+        modifier = modifier+    )+}++/**+ * Creates a 2x2 grid bitmap from a list of Uris+ */+fun createCollageBitmap(context: Context, uris: List<Uri>): Bitmap {+    val size = 512 // Define a standard size for the output square+    val halfSize = size / 2+    val result = createBitmap(size, size)+    val canvas = Canvas(result)++    uris.forEachIndexed { index, uri ->+        val thumb = getThumbnail(context, uri) ?: return@forEachIndexed++        // Calculate grid position+        val left = (index % 2) * halfSize+        val top = (index / 2) * halfSize++        val rect = Rect(left, top, left + halfSize, top + halfSize)+        canvas.drawBitmap(thumb, null, rect, null)+    }++    return result+}++@Composable+fun AddToPlaylistButton(backStack: NavBackStack<Route>, music: Music) {+    IconButton(onClick = { backStack.add(Route.AddToPlaylistDialog(music.id)) }) {+        IconMoreVert()+    }+}++private inline fun <T> withAudioMetadata(+    context: Context,+    uri: Uri,+    default: T,+    extract: (MediaMetadataRetriever) -> T+): T = try {+    MediaMetadataRetriever().use { retriever ->+        retriever.setDataSource(context, uri)+        extract(retriever)+    }+} catch (e: Exception) {+    default+}++fun getRealAudioDuration(context: Context, uri: Uri): Long =+    withAudioMetadata(context, uri, 0L) {+        it.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)?.toLong() ?: 0L+    }++fun formatDuration(durationMs: Long): String {+    val totalSeconds = durationMs / 1000+    val minutes = (totalSeconds % 3600) / 60+    val seconds = totalSeconds % 60+    val hours = totalSeconds / 3600++    return if (hours > 0) {+        String.format(Locale.US, "%d:%02d:%02d", hours, minutes, seconds)+    } else {+        String.format(Locale.US, "%d:%02d", minutes, seconds)+    }+}++fun getAudioYear(context: Context, uri: Uri): Int =+    withAudioMetadata(context, uri, 0) {+        // Some containers (e.g. Opus/Vorbis) expose the release date only via DATE, not+        // YEAR, so fall back to it and pull the first four-digit year out of either.+        val raw = it.extractMetadata(MediaMetadataRetriever.METADATA_KEY_YEAR)+            ?: it.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DATE)+        raw?.let { value -> Regex("\\d{4}").find(value)?.value?.toIntOrNull() } ?: 0+    }\ No newline at end of file