package link.roadio.riff.player.auto import link.roadio.riff.player.storage.PlaybackQueueSnapshot import link.roadio.riff.ui.BrowserItem import link.roadio.riff.ui.BrowserKind import link.roadio.riff.ui.BrowserRows import link.roadio.riff.ui.rowById import link.roadio.riff.ui.rowKey import java.util.Base64 internal data class AutoMediaEntry( val id: String, val title: String, val subtitle: String = "", val browsable: Boolean = false, val playable: Boolean = false, ) internal sealed interface AutoPlayRequest { data class Context( val container: BrowserItem, val selectedId: String, ) : AutoPlayRequest data class Occurrence( val revision: Long, val occurrenceId: Long, val ordinal: Int, ) : AutoPlayRequest } /** * Bounded, context-preserving host view over existing catalog rows and the active execution. * Tokens include a view epoch: snapshot-local row indices never escape into a replacement view. * https://wiki.271.pics/Riff/LATEST/android-auto#bounds-and-failure-ownership */ internal class AndroidAutoCatalog( val epoch: Long, private val root: BrowserItem, private val playlists: BrowserItem, val queue: PlaybackQueueSnapshot?, private val queueTrack: (Int) -> BrowserItem?, ) { private val queueOrder = queue?.takeIf { it.checkpoint.shuffle }?.let { current -> IntArray(current.occurrences.size).also { order -> current.occurrences.forEachIndexed { index, occurrence -> order[occurrence.shuffleOrdinal] = index } } } fun occurrenceAt(position: Int) = requireNotNull(queue).occurrences[queueOrder?.get(position) ?: position] fun activePosition(occurrenceId: Long?): Int = (0 until (queue?.occurrences?.size ?: 0)).firstOrNull { occurrenceAt(it).occurrenceId == occurrenceId } ?: 0 fun children(parentId: String): List = when (parentId) { ROOT -> { listOf( AutoMediaEntry(ALBUM, "Album", browsable = true), AutoMediaEntry(ARTIST, "Artist", browsable = true), AutoMediaEntry(FOLDER, "Folder", browsable = true), AutoMediaEntry(QUEUE, "Queue", browsable = true), ) } QUEUE -> { listOf( AutoMediaEntry(node(ACTIVE), "Current queue", browsable = true), AutoMediaEntry(node(PLAYLISTS), "Playlists", browsable = true), ) } ALBUM -> { collection("category:albums", 0, null) } ARTIST -> { collection("category:artists", 0, null) } FOLDER -> { collection("category:folders", 0, null) } else -> { val parts = parts(parentId) require(parts[2] == "b") { "Not a browse node" } collection(decode(parts[3]), parts[4].toInt(), parts[5].toInt().takeIf { it >= 0 }) } } fun selection(mediaId: String): AutoPlayRequest { val parts = parts(mediaId) return when (parts[2]) { "q" -> { val current = requireNotNull(queue) { "Queue unavailable" } val ordinal = parts[4].toInt() val occurrence = current.occurrences[ordinal] require(parts[3].toLong() == current.revisionId && parts[5].toLong() == occurrence.occurrenceId) AutoPlayRequest.Occurrence(current.revisionId, occurrence.occurrenceId, ordinal) } "p" -> { val selected = resolve(decode(parts[3])) require(selected.enabled && selected.kind in PLAYABLE_CONTAINERS) AutoPlayRequest.Context( BrowserItem("auto-parent", "", BrowserKind.ROOT, children = listOf(selected)), selected.id, ) } "t" -> { val container = resolve(decode(parts[3])) val selected = requireNotNull(container.children.rowById(decode(parts[4]))) require(selected.enabled && selected.playable && selected.kind == BrowserKind.TRACK) AutoPlayRequest.Context(container, selected.id) } else -> { error("Not a playable item") } } } fun activeEntry(ordinal: Int): AutoMediaEntry { val current = requireNotNull(queue) val occurrence = occurrenceAt(ordinal) val row = queueTrack(occurrence.ordinal) return AutoMediaEntry( "aa:$epoch:q:${current.revisionId}:${occurrence.ordinal}:${occurrence.occurrenceId}", row?.label ?: "Unavailable track", row?.artist.orEmpty(), playable = row?.playable == true, ) } private fun collection( id: String, offset: Int, requestedCount: Int?, ): List { val container = if (id == ACTIVE) null else resolve(id) val rows = container?.children (rows as? BrowserRows)?.prepare() val size = if (id == ACTIVE) queue?.occurrences?.size ?: 0 else requireNotNull(rows).size require(offset in 0..size) val count = requestedCount ?: (size - offset) require(count in 0..(size - offset)) val result = mutableListOf() if (offset == 0 && requestedCount == null && container?.enabled == true && container.kind in PLAYABLE_CONTAINERS) { result += AutoMediaEntry("aa:$epoch:p:${encode(id)}", "Play all", playable = true) } val limit = MAX_CHILDREN - 1 if (count > limit) { val step = ((count.toLong() + limit - 1) / limit).toInt() var start = offset while (start < offset + count) { val length = minOf(step, offset + count - start) val first = if (rows == null) (start + 1).toString() else rows.rowKey(start).label val last = if (rows == null) (start + length).toString() else rows.rowKey(start + length - 1).label result += AutoMediaEntry(node(id, start, length), "$first … $last", browsable = true) start += length } } else { for (index in offset until offset + count) { result += if (rows == null) activeEntry(index) else entry(id, rows[index]) } } return result } private fun entry( parent: String, row: BrowserItem, ): AutoMediaEntry = if (row.kind == BrowserKind.TRACK) { AutoMediaEntry( "aa:$epoch:t:${encode(parent)}:${encode(row.id)}", row.label, row.artist, playable = row.enabled && row.playable, ) } else { AutoMediaEntry(node(row.id), row.label, browsable = row.enabled) } private fun resolve(id: String): BrowserItem = requireNotNull( when (id) { PLAYLISTS -> { playlists } else -> { root.children.rowById(id) ?: playlists.children.rowById(id) ?: root.catalog?.find(id) ?: (if (root.catalog == null) findSmallTree(root, id) else null) } }, ) { "Catalog item is no longer available" } private fun findSmallTree( item: BrowserItem, id: String, ): BrowserItem? = item.takeIf { it.id == id } ?: item.children.firstNotNullOfOrNull { findSmallTree(it, id) } private fun parts(id: String): List { require(id.length <= 4096) val parts = id.split(':') require(parts.size >= 4 && parts[0] == "aa" && parts[1].toLong() == epoch) { "Catalog changed; reopen the section" } return parts } private fun node( id: String, offset: Int = 0, count: Int = -1, ) = "aa:$epoch:b:${encode(id)}:$offset:$count" private fun encode(value: String) = Base64.getUrlEncoder().withoutPadding().encodeToString(value.toByteArray(Charsets.UTF_8)) private fun decode(value: String) = String(Base64.getUrlDecoder().decode(value), Charsets.UTF_8) companion object { const val ROOT = "aa-root" const val ALBUM = "aa-album" const val ARTIST = "aa-artist" const val FOLDER = "aa-folder" const val QUEUE = "aa-queue" const val MAX_CHILDREN = 50 private const val ACTIVE = "active" private const val PLAYLISTS = "playlists" private val PLAYABLE_CONTAINERS = setOf(BrowserKind.ALBUM, BrowserKind.ARTIST, BrowserKind.FOLDER, BrowserKind.PLAYLIST) } } internal fun androidAutoQueueWindow( size: Int, current: Int, limit: Int = 41, ): IntRange { require(size >= 0 && limit > 0) if (size == 0) return IntRange.EMPTY val start = (current.coerceIn(0, size - 1) - limit / 2).coerceIn(0, maxOf(0, size - limit)) return start until minOf(size, start + limit) }