Modern Apps git

← Modern-Apps.git

musicbrainz: file every download as a tagged Opus file

Commit
dc63a438a7fe9e9add41c0ca7473e96b936c517a
Author
vayun-mathur <[email protected]>
When
2026-08-20 17:36 UTC (3 months ago)
Parents
f84c7fb

Diff

musicbrainz/src/main/java/com/vayunmathur/musicbrainz/Navigation.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/Navigation.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/Navigation.ktindex f33b24ab0a..8134043947 100644--- a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/Navigation.kt+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/Navigation.kt@@ -10,6 +10,7 @@ import com.vayunmathur.musicbrainz.ui.ReleaseGroupPage import com.vayunmathur.musicbrainz.ui.ReleasePage import com.vayunmathur.musicbrainz.ui.SearchPage import com.vayunmathur.musicbrainz.ui.SettingsPage+import com.vayunmathur.musicbrainz.ui.TidalLoginPage  @Composable fun Navigation(viewModel: MusicBrainzViewModel) {@@ -21,5 +22,6 @@ fun Navigation(viewModel: MusicBrainzViewModel) {         entry<Route.Release> { ReleasePage(backStack, viewModel, it.releaseId) }         entry<Route.Downloads> { DownloadsPage(backStack, viewModel) }         entry<Route.Settings> { SettingsPage(backStack, viewModel) }+        entry<Route.TidalLogin> { TidalLoginPage(backStack, viewModel) }     } }
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/Route.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/Route.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/Route.ktindex ab5d7676f4..7397c5f79e 100644--- a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/Route.kt+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/Route.kt@@ -14,6 +14,9 @@ sealed interface Route : NavKey {     @Serializable     data object Settings : Route +    @Serializable+    data object TidalLogin : Route+     @Serializable     data class Artist(val artistId: String) : Route 
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/AudioSource.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/AudioSource.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/AudioSource.ktnew file mode 100644index 0000000000..16f891ce99--- /dev/null+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/AudioSource.kt@@ -0,0 +1,61 @@+package com.vayunmathur.musicbrainz.data.download++import com.vayunmathur.musicbrainz.platform.DownloadSource++/**+ * What a source is asked to find.+ *+ * Bundled rather than passed as loose parameters so a source that needs a signal the+ * others ignore - Tidal matches on [isrcs], YouTube cannot - does not change every+ * signature between here and the worker.+ */+data class AudioQuery(+    val artist: String,+    val title: String,+    val album: String?,+    /**+     * The MusicBrainz recording length. Search alone happily returns hour-long+     * compilations and sped-up edits of the same title, and duration is the one signal+     * every source can use to separate them from the actual track.+     */+    val durationMs: Int?,+    /**+     * The recording's ISRCs. An exact identity match when the source catalogues them,+     * which beats every other signal; empty for recordings MusicBrainz has none for.+     */+    val isrcs: List<String> = emptyList(),+)++/** A resolved, directly fetchable audio stream. */+data class ResolvedAudio(+    /**+     * The stream's parts, in order, to be concatenated. A progressive stream is a+     * one-element list; a DASH stream is one entry per segment.+     */+    val urls: List<String>,+    val suffix: String,+    val mimeType: String,+    val bitrate: Int,+    val sourceTitle: String,+    val source: DownloadSource,+    /**+     * True when the stream is already 48 kHz Opus, just in a WebM container, so it only needs+     * remuxing to Ogg rather than transcoding. Re-encoding it would be a second lossy+     * generation for no gain, so this is the one stream that keeps its bits.+     */+    val isOpusPassthrough: Boolean = false,+)++/**+ * One place a track's audio can be fetched from.+ *+ * The seam exists so the sources stay independent of the download pipeline: everything+ * after [resolve] - buffered fetch, tagging, SAF write, index upsert - is the same+ * whichever source produced the URLs.+ */+interface AudioSource {+    val id: DownloadSource++    /** Returns null when this source has no match, so the caller can try the next one. */+    suspend fun resolve(query: AudioQuery): ResolvedAudio?+}
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/AudioSources.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/AudioSources.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/AudioSources.ktnew file mode 100644index 0000000000..7396313225--- /dev/null+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/AudioSources.kt@@ -0,0 +1,21 @@+package com.vayunmathur.musicbrainz.data.download++import android.content.Context+import com.vayunmathur.musicbrainz.platform.DownloadSource++/**+ * The download-source fallback policy, in one place.+ *+ * Tidal is a catalogue lookup, so it can simply not carry a recording, and a subscription+ * can lapse. It is therefore always backed by YouTube: a download quietly falling through+ * to a lossy source is better than one disappearing.+ */+object AudioSources {++    /** The sources to try, in order, for a user who prefers [preferred]. */+    fun ordered(context: Context, preferred: DownloadSource): List<AudioSource> =+        when (preferred) {+            DownloadSource.Tidal -> listOf(TidalAudioSource(context), YouTubeAudioSource)+            DownloadSource.YouTube -> listOf(YouTubeAudioSource)+        }+}
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/Mp4Tagger.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/Mp4Tagger.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/Mp4Tagger.ktdeleted file mode 100644index d09f92e2dd..0000000000--- a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/Mp4Tagger.kt+++ /dev/null@@ -1,293 +0,0 @@-package com.vayunmathur.musicbrainz.data.download--import java.io.ByteArrayOutputStream--/** Everything the tagger will write. Null fields are simply omitted. */-data class Mp4Tags(-    val title: String? = null,-    val artist: String? = null,-    val album: String? = null,-    val albumArtist: String? = null,-    val date: String? = null,-    val lyrics: String? = null,-    val trackNumber: Int? = null,-    val trackTotal: Int? = null,-    val discNumber: Int? = null,-    val discTotal: Int? = null,-    val coverArt: ByteArray? = null,-    val coverIsPng: Boolean = false,-    /** iTunes-style custom tags, which is where the MusicBrainz identifiers live. */-    val freeform: Map<String, String> = emptyMap(),-)--/**- * Writes iTunes-style metadata into an MP4/M4A file.- *- * The repo deliberately ships no ffmpeg - it was removed because the prebuilt binary- * blocks F-Droid publication - and Android's own `MediaMuxer` cannot write these atoms,- * so the container is edited directly.- *- * This matters beyond cosmetics: the MusicBrainz IDs written here are exactly what the- * library scan reads back, so a downloaded track is recognised as owned on the next scan- * without the app keeping a private ledger.- */-object Mp4Tagger {--    private const val MEAN_DOMAIN = "com.apple.iTunes"--    /** Text payloads are UTF-8; the well-known type codes for the others. */-    private const val TYPE_UTF8 = 1-    private const val TYPE_BINARY = 0-    private const val TYPE_JPEG = 13-    private const val TYPE_PNG = 14--    /**-     * Returns the tagged file, or null when the input is not an MP4 this can rewrite.-     *-     * Callers fall back to the untagged bytes: a file with poor metadata is still worth-     * keeping, and every non-MP4 container YouTube can serve lands here.-     */-    fun tag(source: ByteArray, tags: Mp4Tags): ByteArray? {-        val boxes = topLevelBoxes(source) ?: return null-        val moov = boxes.firstOrNull { it.type == "moov" } ?: return null-        val mdat = boxes.firstOrNull { it.type == "mdat" }--        val newMoov = rebuildMoov(source, moov, tags) ?: return null-        val delta = newMoov.size - (moov.end - moov.start)--        // Sample offsets in `stco`/`co64` are absolute file positions. Growing `moov`-        // pushes a following `mdat` further down the file, so every offset has to move-        // with it; when `moov` already sits after the audio, nothing has shifted.-        if (mdat != null && mdat.start > moov.start && delta != 0) {-            shiftChunkOffsets(newMoov, delta.toLong())-        }--        val out = ByteArrayOutputStream(source.size + newMoov.size)-        for (box in boxes) {-            if (box.type == "moov") out.write(newMoov) else out.write(source, box.start, box.end - box.start)-        }-        return out.toByteArray()-    }--    private class Box(val type: String, val start: Int, val contentStart: Int, val end: Int)--    private fun topLevelBoxes(buf: ByteArray): List<Box>? {-        val boxes = ArrayList<Box>()-        var offset = 0-        while (offset + 8 <= buf.size) {-            val declared = readInt(buf, offset).toLong() and 0xffffffffL-            val type = String(buf, offset + 4, 4, Charsets.ISO_8859_1)-            val (contentStart, end) = when {-                declared == 1L -> {-                    if (offset + 16 > buf.size) return null-                    offset + 16 to (offset + readLong(buf, offset + 8)).toInt()-                }-                declared == 0L -> offset + 8 to buf.size-                declared < 8L -> return null-                else -> offset + 8 to (offset + declared).toInt()-            }-            if (end <= offset || end > buf.size) return null-            boxes.add(Box(type, offset, contentStart, end))-            offset = end-        }-        return boxes.takeIf { it.isNotEmpty() }-    }--    /** Copies `moov` through, dropping any existing `udta` and appending a freshly built one. */-    private fun rebuildMoov(source: ByteArray, moov: Box, tags: Mp4Tags): ByteArray? {-        val children = childBoxes(source, moov.contentStart, moov.end) ?: return null-        val body = ByteArrayOutputStream()-        for (child in children) {-            if (child.type == "udta") continue-            body.write(source, child.start, child.end - child.start)-        }-        body.write(buildUdta(tags))-        return box("moov", body.toByteArray())-    }--    private fun childBoxes(buf: ByteArray, start: Int, end: Int): List<Box>? {-        val boxes = ArrayList<Box>()-        var offset = start-        while (offset + 8 <= end) {-            val declared = readInt(buf, offset)-            if (declared < 8 || offset + declared > end) return null-            boxes.add(-                Box(-                    String(buf, offset + 4, 4, Charsets.ISO_8859_1),-                    offset,-                    offset + 8,-                    offset + declared,-                ),-            )-            offset += declared-        }-        return boxes-    }--    // -------------------------------------------------------------------    // Building-    // --------------------------------------------------------------------    private fun buildUdta(tags: Mp4Tags): ByteArray {-        val meta = ByteArrayOutputStream()-        meta.write(byteArrayOf(0, 0, 0, 0)) // `meta` is a full box: version and flags.-        meta.write(handlerBox())-        meta.write(box("ilst", buildIlst(tags)))-        return box("udta", box("meta", meta.toByteArray()))-    }--    /**-     * The `mdir`/`appl` handler.-     *-     * Players use it to recognise the metadata as iTunes-style; without it several-     * ignore the `ilst` entirely.-     */-    private fun handlerBox(): ByteArray {-        val content = ByteArrayOutputStream()-        content.write(byteArrayOf(0, 0, 0, 0)) // version and flags-        content.write(byteArrayOf(0, 0, 0, 0)) // pre_defined-        content.write("mdir".toByteArray(Charsets.ISO_8859_1))-        content.write("appl".toByteArray(Charsets.ISO_8859_1))-        content.write(ByteArray(8)) // reserved-        content.write(0) // empty handler name-        return box("hdlr", content.toByteArray())-    }--    private fun buildIlst(tags: Mp4Tags): ByteArray {-        val ilst = ByteArrayOutputStream()-        fun text(atom: String, value: String?) {-            if (!value.isNullOrBlank()) {-                ilst.write(box(atom, dataBox(TYPE_UTF8, value.toByteArray(Charsets.UTF_8))))-            }-        }--        text("\u00A9nam", tags.title)-        text("\u00A9ART", tags.artist)-        text("\u00A9alb", tags.album)-        text("aART", tags.albumArtist)-        text("\u00A9day", tags.date)-        text("\u00A9lyr", tags.lyrics)--        tags.trackNumber?.let { number ->-            val payload = ByteArray(8)-            writeShort(payload, 2, number)-            writeShort(payload, 4, tags.trackTotal ?: 0)-            ilst.write(box("trkn", dataBox(TYPE_BINARY, payload)))-        }-        tags.discNumber?.let { number ->-            val payload = ByteArray(6)-            writeShort(payload, 2, number)-            writeShort(payload, 4, tags.discTotal ?: 0)-            ilst.write(box("disk", dataBox(TYPE_BINARY, payload)))-        }-        tags.coverArt?.let { cover ->-            val type = if (tags.coverIsPng) TYPE_PNG else TYPE_JPEG-            ilst.write(box("covr", dataBox(type, cover)))-        }-        for ((name, value) in tags.freeform) {-            if (value.isNotBlank()) ilst.write(freeformBox(name, value))-        }-        return ilst.toByteArray()-    }--    private fun dataBox(type: Int, payload: ByteArray): ByteArray {-        val content = ByteArrayOutputStream(payload.size + 8)-        content.write(intBytes(type)) // version and type indicator-        content.write(ByteArray(4)) // locale-        content.write(payload)-        return box("data", content.toByteArray())-    }--    /** A `----` box: the namespace, the tag name, then the value. */-    private fun freeformBox(name: String, value: String): ByteArray {-        val content = ByteArrayOutputStream()-        content.write(box("mean", ByteArray(4) + MEAN_DOMAIN.toByteArray(Charsets.UTF_8)))-        content.write(box("name", ByteArray(4) + name.toByteArray(Charsets.UTF_8)))-        content.write(dataBox(TYPE_UTF8, value.toByteArray(Charsets.UTF_8)))-        return box("----", content.toByteArray())-    }--    private fun box(type: String, content: ByteArray): ByteArray {-        val out = ByteArrayOutputStream(content.size + 8)-        out.write(intBytes(content.size + 8))-        out.write(type.toByteArray(Charsets.ISO_8859_1))-        out.write(content)-        return out.toByteArray()-    }--    // -------------------------------------------------------------------    // Chunk offset fixups-    // --------------------------------------------------------------------    /** Walks the rebuilt `moov` and adds [delta] to every sample chunk offset it holds. */-    private fun shiftChunkOffsets(moov: ByteArray, delta: Long) {-        fun walk(start: Int, end: Int) {-            var offset = start-            while (offset + 8 <= end) {-                val size = readInt(moov, offset)-                if (size < 8 || offset + size > end) return-                val type = String(moov, offset + 4, 4, Charsets.ISO_8859_1)-                when (type) {-                    "stco" -> {-                        val count = readInt(moov, offset + 12)-                        for (i in 0 until count) {-                            val at = offset + 16 + i * 4-                            if (at + 4 > offset + size) break-                            val shifted = (readInt(moov, at).toLong() and 0xffffffffL) + delta-                            writeInt(moov, at, shifted.toInt())-                        }-                    }-                    "co64" -> {-                        val count = readInt(moov, offset + 12)-                        for (i in 0 until count) {-                            val at = offset + 16 + i * 8-                            if (at + 8 > offset + size) break-                            writeLong(moov, at, readLong(moov, at) + delta)-                        }-                    }-                    // Only the containers on the path to `stbl` are worth descending into.-                    "trak", "mdia", "minf", "stbl" -> walk(offset + 8, offset + size)-                }-                offset += size-            }-        }-        walk(8, moov.size)-    }--    // --------------------------------------------------------------------    private fun intBytes(value: Int): ByteArray = byteArrayOf(-        (value ushr 24).toByte(),-        (value ushr 16).toByte(),-        (value ushr 8).toByte(),-        value.toByte(),-    )--    private fun readInt(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 writeInt(buf: ByteArray, offset: Int, value: Int) {-        buf[offset] = (value ushr 24).toByte()-        buf[offset + 1] = (value ushr 16).toByte()-        buf[offset + 2] = (value ushr 8).toByte()-        buf[offset + 3] = value.toByte()-    }--    private fun readLong(buf: ByteArray, offset: Int): Long {-        var result = 0L-        for (i in 0 until 8) result = (result shl 8) or (buf[offset + i].toLong() and 0xff)-        return result-    }--    private fun writeLong(buf: ByteArray, offset: Int, value: Long) {-        for (i in 0 until 8) buf[offset + i] = (value ushr (56 - i * 8)).toByte()-    }--    private fun writeShort(buf: ByteArray, offset: Int, value: Int) {-        buf[offset] = (value ushr 8).toByte()-        buf[offset + 1] = value.toByte()-    }-}
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/OggOpusTagger.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/OggOpusTagger.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/OggOpusTagger.ktindex 0c10c7c272..980c1c8a89 100644--- a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/OggOpusTagger.kt+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/OggOpusTagger.kt@@ -97,8 +97,7 @@ object OggOpusTagger {      /** An Opus comment packet: the `OpusTags` magic followed by the shared comment list. */     fun buildOpusTagsPacket(tags: VorbisTags): ByteArray =-        "OpusTags".toByteArray(Charsets.ISO_8859_1) +-            VorbisComments.buildCommentList(tags, includePicture = true)+        "OpusTags".toByteArray(Charsets.ISO_8859_1) + VorbisComments.buildCommentList(tags)      // ------------------------------------------------------------------     // Ogg pages
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/TidalAudioSource.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/TidalAudioSource.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/TidalAudioSource.ktnew file mode 100644index 0000000000..7500d4d2ed--- /dev/null+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/TidalAudioSource.kt@@ -0,0 +1,106 @@+package com.vayunmathur.musicbrainz.data.download++import android.content.Context+import com.vayunmathur.musicbrainz.data.tidal.TidalSession+import com.vayunmathur.musicbrainz.network.api.TidalApi+import com.vayunmathur.musicbrainz.network.api.TidalTrack+import com.vayunmathur.musicbrainz.platform.DownloadSource+import com.vayunmathur.musicbrainz.platform.MusicBrainzPrefs+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.withContext+import kotlin.math.abs++/**+ * Finds a downloadable stream on Tidal for a signed-in subscriber.+ *+ * Tidal is a catalogue with structured metadata, so matching is far surer than YouTube's:+ * a track carries its ISRC, which is an exact identity match, and failing that its real+ * album title and an exact duration. When no session exists this returns null immediately+ * so [AudioSources] falls straight through to YouTube without a wasted request.+ */+class TidalAudioSource(context: Context) : AudioSource {++    override val id = DownloadSource.Tidal++    private val appContext = context.applicationContext+    private val session = TidalSession(appContext)+    private val prefs = MusicBrainzPrefs(appContext)++    override suspend fun resolve(query: AudioQuery): ResolvedAudio? = withContext(Dispatchers.IO) {+        val token = session.accessToken() ?: return@withContext null+        val country = session.countryCode() ?: return@withContext null++        val results = runCatching {+            TidalApi.search(searchQuery(query), token, country).tracks.items+        }.getOrNull().orEmpty()+        if (results.isEmpty()) return@withContext null++        val match = pick(results, query) ?: return@withContext null++        val quality = prefs.tidalQuality.first()+        val playback = runCatching {+            TidalApi.playbackInfo(match.id, quality.apiValue, token, country)+        }.getOrNull() ?: return@withContext null++        val stream = runCatching {+            TidalManifest.decode(playback.manifestMimeType, playback.manifest, playback.audioQuality)+        }.getOrNull() ?: return@withContext null++        ResolvedAudio(+            urls = stream.urls,+            suffix = stream.suffix,+            mimeType = stream.mimeType,+            bitrate = 0,+            sourceTitle = match.title,+            source = id,+        )+    }++    private fun searchQuery(query: AudioQuery): String = "${query.artist} ${query.title}".trim()++    /**+     * Picks the best candidate, strongest signal first.+     *+     * An ISRC match is an exact identity match and is taken outright. Otherwise the album+     * title breaks ties - the right album's pressing is almost always what the user wants -+     * and duration rejects anything too far off, reusing the same thresholds as the YouTube+     * source so both reject a mismatch alike. Tidal durations are seconds, not ms.+     */+    internal fun pick(candidates: List<TidalTrack>, query: AudioQuery): TidalTrack? {+        val isrcs = query.isrcs.map { it.uppercase() }.toSet()+        if (isrcs.isNotEmpty()) {+            candidates.firstOrNull { it.isrc?.uppercase() in isrcs }?.let { return it }+        }++        val targetSeconds = query.durationMs?.takeIf { it > 0 }?.let { it / 1000L }+        val scored = candidates.withIndex().map { (index, track) ->+            val delta = if (targetSeconds != null && track.duration > 0) {+                abs(track.duration - targetSeconds)+            } else {+                Long.MAX_VALUE+            }+            val albumMatch = query.album != null &&+                track.album?.title?.equals(query.album, ignoreCase = true) == true+            ScoredTrack(track, delta, albumMatch, index)+        }++        val withinTolerance = scored.filter {+            targetSeconds == null || it.delta <= YouTubeAudioSource.MAX_DURATION_DIFF_SECONDS+        }+        val pool = withinTolerance.ifEmpty { scored }++        return pool.sortedWith(+            compareByDescending<ScoredTrack> { it.albumMatch }+                .thenBy { if (it.delta <= YouTubeAudioSource.MATCH_TOLERANCE_SECONDS) 0L else it.delta }+                .thenBy { it.index },+        ).firstOrNull()?.track+    }++    private data class ScoredTrack(+        val track: TidalTrack,+        val delta: Long,+        val albumMatch: Boolean,+        val index: Int,+    )+}
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/TidalManifest.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/TidalManifest.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/TidalManifest.ktnew file mode 100644index 0000000000..2422d9dff4--- /dev/null+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/TidalManifest.kt@@ -0,0 +1,134 @@+package com.vayunmathur.musicbrainz.data.download++import kotlinx.serialization.json.Json+import kotlinx.serialization.json.JsonArray+import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.contentOrNull+import kotlinx.serialization.json.jsonPrimitive+import org.xml.sax.InputSource+import java.io.StringReader+import java.util.Base64+import javax.xml.parsers.DocumentBuilderFactory++/** A decoded Tidal stream: the segment URLs in order, and the file extension to save under. */+data class TidalStream(+    val urls: List<String>,+    val suffix: String,+    val mimeType: String,+)++/**+ * Decodes a Tidal playback manifest into fetchable URLs.+ *+ * Ported from tiddl's `core/utils/parse.py`. Tidal returns the manifest base64-encoded in+ * one of two shapes, distinguished by the response's `manifestMimeType`:+ *+ * | Quality         | Container | manifestMimeType          |+ * | --------------- | --------- | ------------------------- |+ * | LOW / HIGH      | m4a (AAC) | application/vnd.tidal.bts |+ * | LOSSLESS        | flac      | application/vnd.tidal.bts |+ * | HI_RES_LOSSLESS | m4a       | application/dash+xml      |+ *+ * The BTS shape is a small JSON blob with the URLs already listed; DASH is an MPD whose+ * segment template has to be expanded into one URL per segment.+ *+ * A manifest whose `encryptionType` is anything other than `NONE` is rejected: the app has+ * no key to decrypt it, so the bytes would be unplayable, and writing them into the user's+ * music folder is worse than failing the download.+ */+object TidalManifest {++    private val DOLBY_CODECS = setOf("eac3", "ac4")+    private val json = Json { ignoreUnknownKeys = true; isLenient = true }++    /**+     * @param audioQuality the quality Tidal actually served (its own value, e.g. `LOSSLESS`),+     *   which decides whether a FLAC-codec hi-res stream is filed as `.flac` or `.m4a`.+     * @throws IllegalArgumentException on an encrypted or unrecognised manifest.+     */+    fun decode(manifestMimeType: String, manifestBase64: String, audioQuality: String): TidalStream {+        val decoded = String(Base64.getDecoder().decode(manifestBase64), Charsets.UTF_8)+        return when (manifestMimeType) {+            "application/vnd.tidal.bts" -> decodeBts(decoded, audioQuality)+            "application/dash+xml" -> decodeDash(decoded, audioQuality)+            else -> throw IllegalArgumentException("Unknown Tidal manifest type: $manifestMimeType")+        }+    }++    private fun decodeBts(manifest: String, audioQuality: String): TidalStream {+        val root = json.parseToJsonElement(manifest) as JsonObject+        val encryption = (root["encryptionType"] as? kotlinx.serialization.json.JsonPrimitive)+            ?.contentOrNull+        if (encryption != null && encryption != "NONE") {+            throw IllegalArgumentException("Tidal stream is encrypted ($encryption)")+        }+        val codecs = (root["codecs"] as? kotlinx.serialization.json.JsonPrimitive)?.contentOrNull.orEmpty()+        val urls = (root["urls"] as? JsonArray)+            ?.mapNotNull { it.jsonPrimitive.contentOrNull }+            .orEmpty()+        require(urls.isNotEmpty()) { "Tidal BTS manifest has no URLs" }+        return TidalStream(urls, suffixFor(codecs, audioQuality), mimeFor(codecs, audioQuality))+    }++    private fun decodeDash(manifest: String, audioQuality: String): TidalStream {+        val (codecs, urls) = parseMpd(manifest)+        require(urls.isNotEmpty()) { "Tidal DASH manifest has no segments" }+        return TidalStream(urls, suffixFor(codecs, audioQuality), mimeFor(codecs, audioQuality))+    }++    /**+     * Expands a Tidal MPD into segment URLs.+     *+     * Tidal's MPD has a single Representation with a SegmentTemplate: an initialization plus+     * a `media` URL containing `$Number$`, and a SegmentTimeline whose `S` elements each+     * describe one segment plus an optional `r` repeat count. The total is every `S` plus+     * its repeats, and `$Number$` runs `0..total` inclusive - the first index is the+     * initialization segment.+     */+    private fun parseMpd(xml: String): Pair<String, List<String>> {+        val factory = DocumentBuilderFactory.newInstance().apply {+            isNamespaceAware = false+        }+        val doc = factory.newDocumentBuilder().parse(InputSource(StringReader(xml)))++        val representation = doc.getElementsByTagName("Representation").item(0)+            ?: throw IllegalArgumentException("Tidal DASH manifest has no Representation")+        val codecs = representation.attributes?.getNamedItem("codecs")?.nodeValue.orEmpty()++        // Reject DRM the same way the BTS path rejects a non-NONE encryptionType: a protected+        // stream would download into an unplayable file, which is worse than failing.+        if (doc.getElementsByTagName("ContentProtection").length > 0) {+            throw IllegalArgumentException("Tidal DASH stream is protected")+        }++        val template = doc.getElementsByTagName("SegmentTemplate").item(0)+            ?: throw IllegalArgumentException("Tidal DASH manifest has no SegmentTemplate")+        val mediaTemplate = template.attributes?.getNamedItem("media")?.nodeValue+            ?: throw IllegalArgumentException("Tidal DASH manifest has no media template")++        val timeline = doc.getElementsByTagName("S")+        var total = 0+        for (i in 0 until timeline.length) {+            total += 1+            val repeat = timeline.item(i).attributes?.getNamedItem("r")?.nodeValue?.toIntOrNull()+            if (repeat != null) total += repeat+        }++        val urls = (0..total).map { mediaTemplate.replace("\$Number\$", it.toString()) }+        return codecs to urls+    }++    private fun suffixFor(codecs: String, audioQuality: String): String = when {+        codecs.equals("flac", ignoreCase = true) ->+            if (audioQuality == "HI_RES_LOSSLESS") "m4a" else "flac"+        codecs.startsWith("mp4", ignoreCase = true) -> "m4a"+        codecs.lowercase() in DOLBY_CODECS -> "m4a"+        else -> throw IllegalArgumentException("Unknown Tidal codecs: $codecs")+    }++    private fun mimeFor(codecs: String, audioQuality: String): String =+        when (suffixFor(codecs, audioQuality)) {+            "flac" -> "audio/flac"+            else -> "audio/mp4"+        }+}
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/VorbisComments.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/VorbisComments.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/VorbisComments.ktnew file mode 100644index 0000000000..c408280f4a--- /dev/null+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/VorbisComments.kt@@ -0,0 +1,98 @@+package com.vayunmathur.musicbrainz.data.download++import java.io.ByteArrayOutputStream+import java.util.Base64++/**+ * The Vorbis-comment metadata written into every download.+ *+ * A `.opus` file carries its metadata as a Vorbis comment list, with the cover art+ * base64-encoded into a `METADATA_BLOCK_PICTURE` comment wrapping a FLAC-style picture+ * block. The keys match what [com.vayunmathur.musicbrainz.data.library.TagReader] reads back,+ * so a download is recognised as owned on the next library scan.+ */+internal object VorbisComments {++    const val VENDOR = "ModernApps musicbrainz"++    /**+     * Builds the comment list: vendor string, a count, then each `KEY=value` entry, all with+     * little-endian length prefixes. This is the body of an Opus comment packet, after its+     * `OpusTags` magic.+     */+    fun buildCommentList(tags: VorbisTags): ByteArray {+        val out = ByteArrayOutputStream()+        val vendor = VENDOR.toByteArray(Charsets.UTF_8)+        out.write(intLe(vendor.size))+        out.write(vendor)++        val comments = ArrayList<ByteArray>()+        fun add(key: String, value: String?) {+            if (!value.isNullOrBlank()) {+                comments.add("$key=$value".toByteArray(Charsets.UTF_8))+            }+        }+        // Text tags first, so a reader with a bounded scan window sees the identifying+        // fields before the much larger cover-art comment.+        add("TITLE", tags.title)+        add("ARTIST", tags.artist)+        add("ALBUM", tags.album)+        add("ALBUMARTIST", tags.albumArtist)+        add("DATE", tags.date)+        tags.trackNumber?.let { add("TRACKNUMBER", it.toString()) }+        tags.trackTotal?.let { add("TRACKTOTAL", it.toString()) }+        tags.discNumber?.let { add("DISCNUMBER", it.toString()) }+        add("MUSICBRAINZ_TRACKID", tags.recordingId)+        add("MUSICBRAINZ_ALBUMID", tags.releaseId)+        add("MUSICBRAINZ_RELEASETRACKID", tags.releaseTrackId)+        add("LYRICS", tags.lyrics)+        tags.coverArt?.takeIf { it.isNotEmpty() }?.let {+            add(+                "METADATA_BLOCK_PICTURE",+                Base64.getEncoder().encodeToString(buildPictureBlock(it, tags.coverIsPng)),+            )+        }++        out.write(intLe(comments.size))+        for (comment in comments) {+            out.write(intLe(comment.size))+            out.write(comment)+        }+        return out.toByteArray()+    }++    /**+     * The FLAC PICTURE block body: a front-cover image with big-endian length fields. The+     * dimensions are left at zero, which players read from the image itself. Opus carries+     * this base64-encoded in a `METADATA_BLOCK_PICTURE` comment.+     */+    private fun buildPictureBlock(image: ByteArray, isPng: Boolean): ByteArray {+        val mime = (if (isPng) "image/png" else "image/jpeg").toByteArray(Charsets.ISO_8859_1)+        val block = ByteArrayOutputStream()+        block.write(intBe(3)) // picture type: front cover+        block.write(intBe(mime.size))+        block.write(mime)+        block.write(intBe(0)) // description length+        block.write(intBe(0)) // width+        block.write(intBe(0)) // height+        block.write(intBe(0)) // colour depth+        block.write(intBe(0)) // indexed colours+        block.write(intBe(image.size))+        block.write(image)+        return block.toByteArray()+    }++    fun intLe(value: Int): ByteArray = byteArrayOf(+        value.toByte(),+        (value ushr 8).toByte(),+        (value ushr 16).toByte(),+        (value ushr 24).toByte(),+    )++    private fun intBe(value: Int): ByteArray = byteArrayOf(+        (value ushr 24).toByte(),+        (value ushr 16).toByte(),+        (value ushr 8).toByte(),+        value.toByte(),+    )+}
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/YouTubeAudioSource.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/AudioResolver.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/YouTubeAudioSource.ktsimilarity index 73%rename from musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/AudioResolver.ktrename to musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/YouTubeAudioSource.ktindex 4074686fd8..383c689744 100644--- a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/AudioResolver.kt+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/YouTubeAudioSource.kt@@ -1,5 +1,6 @@ package com.vayunmathur.musicbrainz.data.download +import com.vayunmathur.musicbrainz.platform.DownloadSource import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import org.schabi.newpipe.extractor.MediaFormat@@ -9,58 +10,36 @@ import org.schabi.newpipe.extractor.stream.DeliveryMethod import org.schabi.newpipe.extractor.stream.StreamInfoItem import kotlin.math.abs -/** A resolved, directly fetchable audio stream. */-data class ResolvedAudio(-    val url: String,-    val suffix: String,-    val mimeType: String,-    val bitrate: Int,-    val sourceTitle: String,-    /**-     * True when the stream is Opus in a WebM container and has to be remuxed to Ogg/Opus-     * before it can be tagged and filed as a `.opus`. False for the `.m4a` fallback, which-     * is already in the container [Mp4Tagger] writes to.-     */-    val needsRemux: Boolean = false,-)- /**- * Finds a downloadable audio stream for a MusicBrainz track.+ * Finds a downloadable audio stream on YouTube, via the extractor YouPipe already vendors.  *- * MusicBrainz catalogues music but hosts none of it, so the audio comes from YouTube via- * the extractor YouPipe already vendors.+ * The source of last resort: it needs no account and carries almost everything, but a+ * YouTube upload is a lossy re-encode of unknown provenance and matching a MusicBrainz+ * recording to one is guesswork, so duration does most of the work in [rank].  *  * Only progressive streams are used. YouTube also serves audio over SABR, which needs a  * stateful session and the PO-token machinery that lives in the YouPipe app; a track that  * is SABR-only is reported as unavailable rather than dragging that whole stack in here.  */-object AudioResolver {+object YouTubeAudioSource : AudioSource {++    override val id = DownloadSource.YouTube      private const val SEARCH_RESULTS_CONSIDERED = 8      // Two uploads within this many seconds are treated as an equal-length match, so YouTube's     // own relevance order breaks the tie rather than an insignificantly closer runtime.-    private const val MATCH_TOLERANCE_SECONDS = 3L+    internal const val MATCH_TOLERANCE_SECONDS = 3L      // A candidate whose runtime differs from the catalogued length by more than this is taken     // to be a different thing - a compilation, an extended mix, a sped-up edit - and dropped,     // because synced lyrics timed to the real track would drift audibly against it.-    private const val MAX_DURATION_DIFF_SECONDS = 15L+    internal const val MAX_DURATION_DIFF_SECONDS = 15L -    /**-     * @param durationMs the MusicBrainz recording length, used to pick between candidates.-     *   Search alone happily returns hour-long compilations and sped-up edits of the same-     *   title, and duration is the one signal that separates them from the actual track.-     */-    suspend fun resolve(-        artist: String,-        title: String,-        album: String?,-        durationMs: Int?,-    ): ResolvedAudio? = withContext(Dispatchers.IO) {-        val candidates = search(buildQuery(artist, title, album))+    override suspend fun resolve(query: AudioQuery): ResolvedAudio? = withContext(Dispatchers.IO) {+        val candidates = search(buildQuery(query.artist, query.title, query.album))         if (candidates.isEmpty()) return@withContext null-        val ordered = rank(candidates, durationMs)+        val ordered = rank(candidates, query.durationMs)         for (candidate in ordered) {             val audio = audioFor(candidate.url) ?: continue             return@withContext audio.copy(sourceTitle = candidate.name)@@ -127,31 +106,32 @@ object AudioResolver {                 it.getContent().isNotBlank()         }         // Prefer the highest-bitrate Opus: YouTube's itag 251 Opus (~160 kbps) beats the-        // best progressive AAC (itag 140, 128 kbps), and remuxing WebM/Opus to Ogg/Opus is-        // a lossless stream copy. It arrives in a WebM container, so it needs remuxing-        // before it can be tagged and filed as `.opus`.+        // best progressive AAC (itag 140, 128 kbps), and it is already 48 kHz Opus, so+        // remuxing WebM to Ogg is a lossless stream copy where transcoding would not be.         val opus = progressive.filter { it.isOpus() }.maxByOrNull { it.effectiveBitrate() }         if (opus != null) {             return ResolvedAudio(-                url = opus.getContent(),+                urls = listOf(opus.getContent()),                 suffix = "opus",                 mimeType = "audio/ogg",                 bitrate = opus.effectiveBitrate(),                 sourceTitle = "",-                needsRemux = true,+                source = id,+                isOpusPassthrough = true,             )         }-        // Fallback: no Opus stream, so keep the best available and let the `.m4a` tagging-        // path handle it. Transcoding to Opus would be lossy, so it is deliberately avoided.+        // Fallback: no Opus stream, so keep the best available and let the transcode path+        // re-encode it to Opus like every other lossy-source download.         val best = progressive.maxByOrNull { it.effectiveBitrate() }         best?.let {             val format = it.getFormat()             ResolvedAudio(-                url = it.getContent(),+                urls = listOf(it.getContent()),                 suffix = format?.getSuffix() ?: "m4a",                 mimeType = format?.mimeType ?: "audio/mp4",                 bitrate = it.effectiveBitrate(),                 sourceTitle = "",+                source = id,             )         }     } catch (_: Exception) {
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/tidal/TidalAuth.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/tidal/TidalAuth.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/tidal/TidalAuth.ktnew file mode 100644index 0000000000..b28b210daa--- /dev/null+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/tidal/TidalAuth.kt@@ -0,0 +1,209 @@+package com.vayunmathur.musicbrainz.data.tidal++import com.vayunmathur.library.network.NetworkClient+import kotlinx.serialization.json.Json+import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.contentOrNull+import kotlinx.serialization.json.longOrNull+import java.net.URLEncoder+import java.util.Base64++/** The tokens a successful sign-in yields, plus who they belong to. */+data class TidalTokens(+    val accessToken: String,+    val refreshToken: String?,+    val expiresAtMs: Long,+    val userId: String,+    val countryCode: String,+    val username: String,+)++/** The device code and where to enter it, from the start of the sign-in. */+data class TidalDeviceCode(+    val deviceCode: String,+    val userCode: String,+    val verificationUri: String,+    val intervalSeconds: Int,+    val expiresInSeconds: Int,+)++/** One poll's outcome while the user completes sign-in on another device. */+sealed interface TidalPollResult {+    /** The user has not finished yet; keep polling. */+    data object Pending : TidalPollResult++    /** The device code's lifetime ran out before the user finished. */+    data object Expired : TidalPollResult++    /** Poll interval was too short; back off before the next poll. */+    data object SlowDown : TidalPollResult++    data class Success(val tokens: TidalTokens) : TidalPollResult++    data class Error(val message: String) : TidalPollResult+}++/**+ * Tidal OAuth 2.0 device authorization grant.+ *+ * Chosen over the redirect/PKCE flow the email app uses because it needs no intent-filter+ * or redirect activity: the user enters a short code at [TidalDeviceCode.verificationUri]+ * and this polls for the token. Ported from tiddl's `core/auth`, including its well-known+ * client credentials - Tidal has no public app registration, so every open client uses+ * the same pair, stored base64-encoded the way tiddl does.+ *+ * [NetworkClient.callJson] throws on any non-2xx, but `authorization_pending` - the normal+ * idle response of a device-code poll - comes back as HTTP 400, so this uses+ * [NetworkClient.performRequest] and reads the JSON body by hand instead.+ */+object TidalAuth {++    private const val AUTH_URL = "https://auth.tidal.com/v1/oauth2"+    private const val LOGOUT_URL = "https://api.tidal.com/v1/logout"+    private const val SCOPE = "r_usr+w_usr+w_sub"+    private const val DEVICE_GRANT = "urn:ietf:params:oauth:grant-type:device_code"++    // client_id;client_secret, base64-encoded exactly as tiddl stores it.+    private const val CREDENTIALS =+        "NE4zbjZRMXg5NUxMNUs3cDtvS09YZkpXMzcxY1g2eGFaMFB5aGdHTkJkTkxsQlpkNEFLS1lvdWdNamlrPQ=="++    private val clientId: String+    private val clientSecret: String++    init {+        val pair = String(Base64.getDecoder().decode(CREDENTIALS), Charsets.UTF_8).split(";", limit = 2)+        clientId = pair[0]+        clientSecret = pair.getOrElse(1) { "" }+    }++    private val json = Json { ignoreUnknownKeys = true; isLenient = true }++    private val formHeaders = mapOf(+        "Content-Type" to "application/x-www-form-urlencoded",+        "Accept" to "application/json",+    )++    private val basicAuthHeaders = formHeaders + mapOf(+        "Authorization" to "Basic " + Base64.getEncoder()+            .encodeToString("$clientId:$clientSecret".toByteArray(Charsets.UTF_8)),+    )++    /** Begins sign-in. Throws on a network or protocol failure. */+    suspend fun requestDeviceCode(): TidalDeviceCode {+        val body = form("client_id" to clientId, "scope" to SCOPE)+        val response = NetworkClient.performRequest(+            "$AUTH_URL/device_authorization",+            method = "POST",+            headers = formHeaders,+            body = body,+        )+        if (!response.isSuccess) {+            throw java.io.IOException("Tidal device auth failed: HTTP ${response.status}")+        }+        val root = json.parseToJsonElement(response.body).jsonObject()+        return TidalDeviceCode(+            deviceCode = root.string("deviceCode").orEmpty(),+            userCode = root.string("userCode").orEmpty(),+            verificationUri = root.string("verificationUriComplete")+                ?.let { if (it.startsWith("http")) it else "https://$it" }+                .orEmpty(),+            intervalSeconds = root.int("interval", 2),+            expiresInSeconds = root.int("expiresIn", 300),+        )+    }++    /** Polls once for the token belonging to [deviceCode]. */+    suspend fun poll(deviceCode: String): TidalPollResult {+        val body = form(+            "client_id" to clientId,+            "device_code" to deviceCode,+            "grant_type" to DEVICE_GRANT,+            "scope" to SCOPE,+        )+        // A network blip mid-sign-in must not end the flow: report it as pending so the+        // caller keeps polling until the device code's own deadline.+        val response = runCatching {+            NetworkClient.performRequest(+                "$AUTH_URL/token",+                method = "POST",+                headers = basicAuthHeaders,+                body = body,+            )+        }.getOrNull() ?: return TidalPollResult.Pending+        val root = runCatching { json.parseToJsonElement(response.body).jsonObject() }.getOrNull()+        if (response.isSuccess && root != null) {+            return TidalPollResult.Success(tokens(root))+        }+        return when (root?.string("error")) {+            "authorization_pending" -> TidalPollResult.Pending+            "slow_down" -> TidalPollResult.SlowDown+            "expired_token" -> TidalPollResult.Expired+            null -> TidalPollResult.Error("HTTP ${response.status}")+            else -> TidalPollResult.Error(+                root.string("error_description") ?: root.string("error").orEmpty(),+            )+        }+    }++    /** Exchanges a refresh token for a fresh access token, or null on failure. */+    suspend fun refresh(refreshToken: String): TidalTokens? {+        val body = form(+            "client_id" to clientId,+            "refresh_token" to refreshToken,+            "grant_type" to "refresh_token",+            "scope" to SCOPE,+        )+        val response = NetworkClient.performRequest(+            "$AUTH_URL/token",+            method = "POST",+            headers = basicAuthHeaders,+            body = body,+        )+        if (!response.isSuccess) return null+        val root = runCatching { json.parseToJsonElement(response.body).jsonObject() }.getOrNull()+            ?: return null+        // A refresh response carries no refresh_token of its own, so the caller keeps the old one.+        return tokens(root, fallbackRefresh = refreshToken)+    }++    /** Tells Tidal to drop the session. Best-effort; failures are ignored. */+    suspend fun logout(accessToken: String) {+        runCatching {+            NetworkClient.performRequest(+                LOGOUT_URL,+                method = "POST",+                headers = mapOf("Authorization" to "Bearer $accessToken"),+            )+        }+    }++    private fun tokens(root: JsonObject, fallbackRefresh: String? = null): TidalTokens {+        val user = (root["user"] as? JsonObject)+        val expiresIn = root.long("expires_in") ?: 86_400L+        return TidalTokens(+            accessToken = root.string("access_token").orEmpty(),+            refreshToken = root.string("refresh_token") ?: fallbackRefresh,+            expiresAtMs = System.currentTimeMillis() + expiresIn * 1000,+            userId = root.string("user_id") ?: user?.string("userId").orEmpty(),+            countryCode = user?.string("countryCode").orEmpty(),+            username = user?.string("username")+                ?: user?.string("email")+                ?: user?.string("nickname").orEmpty(),+        )+    }++    private fun form(vararg pairs: Pair<String, String>): String =+        pairs.joinToString("&") { (k, v) ->+            "${URLEncoder.encode(k, "UTF-8")}=${URLEncoder.encode(v, "UTF-8")}"+        }++    private fun kotlinx.serialization.json.JsonElement.jsonObject(): JsonObject = this as JsonObject++    private fun JsonObject.string(key: String): String? =+        (this[key] as? kotlinx.serialization.json.JsonPrimitive)?.contentOrNull++    private fun JsonObject.long(key: String): Long? =+        (this[key] as? kotlinx.serialization.json.JsonPrimitive)?.longOrNull++    private fun JsonObject.int(key: String, default: Int): Int = long(key)?.toInt() ?: default+}
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/tidal/TidalSession.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/tidal/TidalSession.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/tidal/TidalSession.ktnew file mode 100644index 0000000000..8dbdde1ee8--- /dev/null+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/tidal/TidalSession.kt@@ -0,0 +1,44 @@+package com.vayunmathur.musicbrainz.data.tidal++import android.content.Context+import com.vayunmathur.musicbrainz.platform.MusicBrainzPrefs+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock++/**+ * Hands out a valid Tidal access token, refreshing it when it is about to expire.+ *+ * An album downloads as one worker per track, all running at once, so without the [mutex]+ * they would each notice the same near-expiry token and fire off a wave of refreshes. The+ * lock funnels that to one: the losers re-read the token the winner just persisted.+ */+class TidalSession(context: Context) {++    private val appContext = context.applicationContext+    private val prefs = MusicBrainzPrefs(appContext)++    /** A usable access token, or null when there is no session or the refresh failed. */+    suspend fun accessToken(): String? = mutex.withLock {+        val account = prefs.tidalAccount.first() ?: return null+        if (account.expiresAtMs > System.currentTimeMillis() + EXPIRY_MARGIN_MS &&+            account.accessToken.isNotBlank()+        ) {+            return account.accessToken+        }+        val refresh = account.refreshToken?.takeIf { it.isNotBlank() }+            ?: return account.accessToken.ifBlank { null }+        val refreshed = TidalAuth.refresh(refresh) ?: return account.accessToken.ifBlank { null }+        prefs.updateTidalTokens(refreshed.accessToken, refreshed.refreshToken, refreshed.expiresAtMs)+        refreshed.accessToken.ifBlank { null }+    }++    /** The account's country code, needed on nearly every Tidal API call. */+    suspend fun countryCode(): String? = prefs.tidalAccount.first()?.countryCode?.ifBlank { null }++    private companion object {+        // Refresh a little early so a token cannot expire mid-download.+        const val EXPIRY_MARGIN_MS = 60_000L+        val mutex = Mutex()+    }+}
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/network/api/MusicBrainzApi.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/network/api/MusicBrainzApi.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/network/api/MusicBrainzApi.ktindex 5cba2bfde3..5f0cadfcff 100644--- a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/network/api/MusicBrainzApi.kt+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/network/api/MusicBrainzApi.kt@@ -80,7 +80,7 @@ object MusicBrainzApi {      * just "Various Artists".      */     suspend fun release(id: String): MbRelease =-        get("release/$id?fmt=json&inc=recordings+artists+artist-credits+release-groups")+        get("release/$id?fmt=json&inc=recordings+artists+artist-credits+release-groups+isrcs")      suspend fun recording(id: String): MbRecording =         get("recording/$id?fmt=json&inc=artists+artist-credits+releases")
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/network/api/MusicBrainzModels.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/network/api/MusicBrainzModels.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/network/api/MusicBrainzModels.ktindex 78839c813d..8df519e2f9 100644--- a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/network/api/MusicBrainzModels.kt+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/network/api/MusicBrainzModels.kt@@ -93,6 +93,8 @@ data class MbRecordingRef(     val id: String = "",     val title: String = "",     val length: Int? = null,+    /** Present only when the release was fetched with `inc=isrcs`. */+    val isrcs: List<String> = emptyList(),     @SerialName("artist-credit") val artistCredit: List<MbArtistCredit> = emptyList(), ) 
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/network/api/TidalApi.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/network/api/TidalApi.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/network/api/TidalApi.ktnew file mode 100644index 0000000000..29f1e1ea29--- /dev/null+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/network/api/TidalApi.kt@@ -0,0 +1,47 @@+package com.vayunmathur.musicbrainz.network.api++import com.vayunmathur.library.network.NetworkClient+import java.net.URLEncoder++/**+ * Client for the Tidal v1 API.+ *+ * Every call needs a bearer token and the account's country code, so both are passed in+ * rather than held here - the token can be refreshed between calls, and the object stays+ * stateless like [MusicBrainzApi]. Unlike MusicBrainz, Tidal publishes no per-client rate+ * limit, so there is no gate.+ */+object TidalApi {++    private const val BASE = "https://api.tidal.com/v1"++    private fun headers(token: String) = mapOf(+        "Authorization" to "Bearer $token",+        "Accept" to "application/json",+    )++    private fun encode(value: String): String = URLEncoder.encode(value, "UTF-8")++    suspend fun search(query: String, token: String, countryCode: String, limit: Int = 25): TidalSearchResult =+        NetworkClient.getJson(+            "$BASE/search?query=${encode(query)}&countryCode=$countryCode&limit=$limit",+            headers = headers(token),+        )++    /**+     * The playback manifest for one track at [quality] (Tidal's `audioquality` value).+     * `playbackinfopostpaywall` is the endpoint that returns real stream URLs for a+     * subscriber; Tidal downgrades server-side when the track or plan cannot serve the ask.+     */+    suspend fun playbackInfo(+        trackId: Int,+        quality: String,+        token: String,+        countryCode: String,+    ): TidalPlaybackInfo = NetworkClient.getJson(+        "$BASE/tracks/$trackId/playbackinfopostpaywall" ++            "?audioquality=$quality&playbackmode=STREAM&assetpresentation=FULL" ++            "&countryCode=$countryCode",+        headers = headers(token),+    )+}
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/network/api/TidalModels.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/network/api/TidalModels.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/network/api/TidalModels.ktnew file mode 100644index 0000000000..3710849b74--- /dev/null+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/network/api/TidalModels.kt@@ -0,0 +1,63 @@+package com.vayunmathur.musicbrainz.network.api++import kotlinx.serialization.SerialName+import kotlinx.serialization.Serializable++/**+ * Wire models for the Tidal v1 API.+ *+ * Only the fields the downloader uses are declared; the client decodes with+ * `ignoreUnknownKeys`, so the (very large) responses stay readable.+ */++@Serializable+data class TidalArtist(+    val id: Int = 0,+    val name: String = "",+)++@Serializable+data class TidalAlbum(+    val id: Int = 0,+    val title: String = "",+    /** The cover UID, dashes-to-slashes into a resources.tidal.com image path. */+    val cover: String? = null,+)++@Serializable+data class TidalTrack(+    val id: Int = 0,+    val title: String = "",+    /** Seconds, unlike MusicBrainz's milliseconds. */+    val duration: Int = 0,+    val trackNumber: Int = 0,+    val volumeNumber: Int = 0,+    val isrc: String? = null,+    val audioQuality: String? = null,+    val artist: TidalArtist? = null,+    val artists: List<TidalArtist> = emptyList(),+    val album: TidalAlbum? = null,+)++@Serializable+data class TidalTrackList(+    val items: List<TidalTrack> = emptyList(),+)++@Serializable+data class TidalSearchResult(+    val tracks: TidalTrackList = TidalTrackList(),+)++/**+ * The playback response. [manifest] is base64; [manifestMimeType] says whether it decodes+ * to a Tidal BTS JSON blob or a DASH MPD, which [com.vayunmathur.musicbrainz.data.download.TidalManifest]+ * pulls the stream URLs out of.+ */+@Serializable+data class TidalPlaybackInfo(+    val trackId: Int = 0,+    val audioQuality: String = "",+    @SerialName("manifestMimeType") val manifestMimeType: String = "",+    val manifest: String = "",+)
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/platform/DownloadSource.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/platform/DownloadSource.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/platform/DownloadSource.ktnew file mode 100644index 0000000000..5e8e1ac295--- /dev/null+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/platform/DownloadSource.kt@@ -0,0 +1,30 @@+package com.vayunmathur.musicbrainz.platform++import androidx.annotation.StringRes+import com.vayunmathur.musicbrainz.R++/**+ * Where downloaded audio comes from.+ *+ * MusicBrainz hosts no audio, so a download always needs an outside source. YouTube needs+ * no account but serves lossy re-encodes matched on a search query; Tidal needs a+ * subscription but is a catalogue, so a track is matched on its ISRC and arrives lossless.+ */+enum class DownloadSource(@StringRes val labelRes: Int) {+    YouTube(R.string.download_source_youtube),+    Tidal(R.string.download_source_tidal),+}++/**+ * The best stream to ask Tidal for.+ *+ * [apiValue] is Tidal's own `audioquality` parameter. The request is only ever a ceiling:+ * Tidal downgrades server-side when the subscription or the track cannot serve it, and the+ * response says which quality it actually returned.+ */+enum class TidalQuality(@StringRes val labelRes: Int, val apiValue: String) {+    Low(R.string.tidal_quality_low, "LOW"),+    Normal(R.string.tidal_quality_normal, "HIGH"),+    High(R.string.tidal_quality_high, "LOSSLESS"),+    Max(R.string.tidal_quality_max, "HI_RES_LOSSLESS"),+}
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/platform/MusicBrainzPrefs.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/platform/MusicBrainzPrefs.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/platform/MusicBrainzPrefs.ktindex 57057e3dda..bcb3ee8f5a 100644--- a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/platform/MusicBrainzPrefs.kt+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/platform/MusicBrainzPrefs.kt@@ -10,10 +10,28 @@ import androidx.datastore.preferences.preferencesDataStore import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map+import kotlinx.serialization.Serializable+import kotlinx.serialization.json.Json  private val Context.musicBrainzDataStore: DataStore<Preferences> by     preferencesDataStore(name = "musicbrainz") +/**+ * A signed-in Tidal account.+ *+ * Lives here rather than in `data.tidal` because `TidalSession` reads it from these prefs,+ * so declaring it alongside its store keeps the dependency one-way.+ */+@Serializable+data class TidalAccount(+    val accessToken: String,+    val refreshToken: String?,+    val expiresAtMs: Long,+    val countryCode: String,+    val userId: String,+    val username: String,+)+ /** App settings: where downloads go, and whether lyrics are fetched alongside them. */ class MusicBrainzPrefs(context: Context) {     private val appContext = context.applicationContext@@ -24,6 +42,18 @@ class MusicBrainzPrefs(context: Context) {     val embedCoverArt: Flow<Boolean> =         appContext.musicBrainzDataStore.data.map { it[EMBED_COVER] ?: true } +    /** The signed-in Tidal account, or null when signed out. */+    val tidalAccount: Flow<TidalAccount?> =+        appContext.musicBrainzDataStore.data.map { it[TIDAL_ACCOUNT]?.toAccount() }++    val downloadSource: Flow<DownloadSource> = appContext.musicBrainzDataStore.data.map {+        it[DOWNLOAD_SOURCE].toEnum(DownloadSource.entries, DownloadSource.YouTube)+    }++    val tidalQuality: Flow<TidalQuality> = appContext.musicBrainzDataStore.data.map {+        it[TIDAL_QUALITY].toEnum(TidalQuality.entries, TidalQuality.High)+    }+     suspend fun musicFolderUri(): String? = musicFolder.first()      suspend fun setMusicFolder(uri: String) {@@ -42,9 +72,57 @@ class MusicBrainzPrefs(context: Context) {         appContext.musicBrainzDataStore.edit { it[EMBED_COVER] = value }     } +    suspend fun setTidalAccount(account: TidalAccount) {+        appContext.musicBrainzDataStore.edit { it[TIDAL_ACCOUNT] = json.encodeToString(account) }+    }++    suspend fun clearTidalAccount() {+        appContext.musicBrainzDataStore.edit { it.remove(TIDAL_ACCOUNT) }+    }++    /**+     * Replaces the tokens of the stored account, keeping who it belongs to.+     *+     * Read and write happen inside one [edit] so two workers refreshing at once cannot+     * write over each other's tokens.+     */+    suspend fun updateTidalTokens(accessToken: String, refreshToken: String?, expiresAtMs: Long) {+        appContext.musicBrainzDataStore.edit { prefs ->+            val existing = prefs[TIDAL_ACCOUNT]?.toAccount() ?: return@edit+            prefs[TIDAL_ACCOUNT] = json.encodeToString(+                existing.copy(+                    accessToken = accessToken,+                    refreshToken = refreshToken ?: existing.refreshToken,+                    expiresAtMs = expiresAtMs,+                ),+            )+        }+    }++    suspend fun setDownloadSource(source: DownloadSource) {+        appContext.musicBrainzDataStore.edit { it[DOWNLOAD_SOURCE] = source.name }+    }++    suspend fun setTidalQuality(quality: TidalQuality) {+        appContext.musicBrainzDataStore.edit { it[TIDAL_QUALITY] = quality.name }+    }+     private companion object {         val FOLDER_URI = stringPreferencesKey("music_folder_uri")         val FETCH_LYRICS = booleanPreferencesKey("fetch_lyrics")         val EMBED_COVER = booleanPreferencesKey("embed_cover_art")+        val TIDAL_ACCOUNT = stringPreferencesKey("tidal_account")+        val DOWNLOAD_SOURCE = stringPreferencesKey("download_source")+        val TIDAL_QUALITY = stringPreferencesKey("tidal_quality")++        val json = Json { ignoreUnknownKeys = true }++        /** A value this version cannot read means signed out, which is recoverable. */+        fun String.toAccount(): TidalAccount? =+            runCatching { json.decodeFromString<TidalAccount>(this) }.getOrNull()++        /** Enums are stored by name, so a rename falls back to the default instead of crashing. */+        fun <T : Enum<T>> String?.toEnum(values: List<T>, default: T): T =+            values.firstOrNull { it.name == this } ?: default     } }
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/platform/MusicBrainzUiContract.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/platform/MusicBrainzUiContract.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/platform/MusicBrainzUiContract.ktindex 54f73f428f..ea004e9286 100644--- a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/platform/MusicBrainzUiContract.kt+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/platform/MusicBrainzUiContract.kt@@ -58,6 +58,8 @@ data class TrackRow(     val artist: String,     val durationMs: Int? = null,     val discNumber: Int = 1,+    /** The recording's ISRCs, which let a catalogue source match on identity. */+    val isrcs: List<String> = emptyList(),     val onDevice: Boolean = false,     val download: DownloadItem? = null, )@@ -111,6 +113,20 @@ data class SettingsUiState(     val indexedTracks: Int = 0,     val fetchLyrics: Boolean = true,     val embedCoverArt: Boolean = true,+    val downloadSource: DownloadSource = DownloadSource.YouTube,+    val tidalQuality: TidalQuality = TidalQuality.High,+    /** The signed-in Tidal user, or null when signed out. */+    val tidalUsername: String? = null,+)++/** How far along the Tidal device-code sign-in is. */+enum class TidalLoginStatus { Starting, AwaitingUser, Success, Failed }++data class TidalLoginUiState(+    val status: TidalLoginStatus = TidalLoginStatus.Starting,+    val userCode: String? = null,+    val verificationUri: String? = null,+    val error: String? = null, )  interface MusicBrainzActions {@@ -132,6 +148,9 @@ interface MusicBrainzActions {     fun rescanLibrary() {}     fun setFetchLyrics(value: Boolean) {}     fun setEmbedCoverArt(value: Boolean) {}+    fun setDownloadSource(source: DownloadSource) {}+    fun setTidalQuality(quality: TidalQuality) {}+    fun signOutOfTidal() {}      companion object {         val Noop: MusicBrainzActions = object : MusicBrainzActions {}
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/platform/MusicBrainzViewModel.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/platform/MusicBrainzViewModel.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/platform/MusicBrainzViewModel.ktindex 77f69d1e56..6d6be654e5 100644--- a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/platform/MusicBrainzViewModel.kt+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/platform/MusicBrainzViewModel.kt@@ -8,6 +8,8 @@ import androidx.lifecycle.viewModelScope import com.vayunmathur.musicbrainz.data.library.LibraryIndex import com.vayunmathur.musicbrainz.data.library.LibraryScanner import com.vayunmathur.musicbrainz.data.library.LibrarySnapshot+import com.vayunmathur.musicbrainz.data.tidal.TidalAuth+import com.vayunmathur.musicbrainz.data.tidal.TidalPollResult import com.vayunmathur.musicbrainz.network.api.CoverArt import com.vayunmathur.musicbrainz.network.api.MbRecording import com.vayunmathur.musicbrainz.network.api.MbRelease@@ -18,10 +20,12 @@ import com.vayunmathur.musicbrainz.platform.download.DownloadQueue import com.vayunmathur.musicbrainz.platform.download.DownloadRequest import com.vayunmathur.musicbrainz.platform.SafTree import kotlinx.coroutines.Job+import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.combine+import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.launch@@ -41,12 +45,14 @@ class MusicBrainzViewModel(application: Application) : AndroidViewModel(applicat     private val _artist = MutableStateFlow(ArtistUiState())     private val _releaseGroup = MutableStateFlow(ReleaseGroupUiState())     private val _release = MutableStateFlow(ReleaseUiState())+    private val _tidalLogin = MutableStateFlow(TidalLoginUiState())      private val artistCache = HashMap<String, ArtistUiState>()     private val releaseGroupCache = HashMap<String, ReleaseGroupUiState>()     private val releaseCache = HashMap<String, MbRelease>()      private var searchJob: Job? = null+    private var tidalLoginJob: Job? = null     private var loadedReleaseId: String? = null      /**@@ -62,6 +68,8 @@ class MusicBrainzViewModel(application: Application) : AndroidViewModel(applicat      val artist: StateFlow<ArtistUiState> = _artist.asStateFlow() +    val tidalLogin: StateFlow<TidalLoginUiState> = _tidalLogin.asStateFlow()+     val releaseGroup: StateFlow<ReleaseGroupUiState> =         combine(_releaseGroup, LibraryIndex.snapshot) { state, library ->             state.copy(@@ -90,6 +98,20 @@ class MusicBrainzViewModel(application: Application) : AndroidViewModel(applicat     val downloads: StateFlow<Map<String, com.vayunmathur.musicbrainz.platform.download.DownloadItem>> =         DownloadQueue.items +    /**+     * The Tidal prefs, folded into one flow first: [combine]'s largest typed overload takes+     * five sources and the folder/library group already fills it.+     */+    private val tidalSettings = combine(+        prefs.downloadSource,+        prefs.tidalQuality,+        prefs.tidalAccount,+    ) { source, quality, account ->+        // Falls back to the user id so an account whose payload carried no username still+        // reads as signed in, and so its sign-out row stays reachable.+        Triple(source, quality, account?.let { it.username.ifBlank { it.userId } })+    }+     val settings: StateFlow<SettingsUiState> = combine(         prefs.musicFolder,         prefs.fetchLyrics,@@ -104,6 +126,8 @@ class MusicBrainzViewModel(application: Application) : AndroidViewModel(applicat             fetchLyrics = lyrics,             embedCoverArt = cover,         )+    }.combine(tidalSettings) { state, (source, quality, username) ->+        state.copy(downloadSource = source, tidalQuality = quality, tidalUsername = username)     }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), SettingsUiState())      init {@@ -333,6 +357,7 @@ class MusicBrainzViewModel(application: Application) : AndroidViewModel(applicat             trackTotal = medium.trackCount.takeIf { it > 0 },             discNumber = track.discNumber.takeIf { release.media.size > 1 },             durationMs = track.durationMs,+            isrcs = track.isrcs,         )     } @@ -364,6 +389,108 @@ class MusicBrainzViewModel(application: Application) : AndroidViewModel(applicat         viewModelScope.launch { prefs.setEmbedCoverArt(value) }     } +    override fun setDownloadSource(source: DownloadSource) {+        viewModelScope.launch { prefs.setDownloadSource(source) }+    }++    override fun setTidalQuality(quality: TidalQuality) {+        viewModelScope.launch { prefs.setTidalQuality(quality) }+    }++    override fun signOutOfTidal() {+        viewModelScope.launch {+            prefs.tidalAccount.first()?.accessToken?.takeIf { it.isNotBlank() }?.let {+                TidalAuth.logout(it)+            }+            prefs.clearTidalAccount()+            // The login screen pops itself on Success, so a stale Success left here would+            // pop the next sign-in before the user ever sees a code.+            _tidalLogin.value = TidalLoginUiState()+        }+    }++    // ------------------------------------------------------------------+    // Tidal sign-in+    // ------------------------------------------------------------------++    /**+     * Runs the device-code flow: ask for a code, show it, then poll until the user has+     * entered it elsewhere or the code's own deadline passes.+     */+    fun startTidalLogin() {+        tidalLoginJob?.cancel()+        _tidalLogin.value = TidalLoginUiState()+        tidalLoginJob = viewModelScope.launch {+            val code = try {+                TidalAuth.requestDeviceCode()+            } catch (e: Exception) {+                _tidalLogin.value = TidalLoginUiState(+                    status = TidalLoginStatus.Failed,+                    error = e.readableMessage(),+                )+                return@launch+            }+            _tidalLogin.value = TidalLoginUiState(+                status = TidalLoginStatus.AwaitingUser,+                userCode = code.userCode,+                verificationUri = code.verificationUri,+            )++            val deadline = System.currentTimeMillis() + code.expiresInSeconds * 1000L+            var intervalMs = code.intervalSeconds.coerceAtLeast(1) * 1000L+            while (System.currentTimeMillis() < deadline) {+                delay(intervalMs)+                when (val result = TidalAuth.poll(code.deviceCode)) {+                    TidalPollResult.Pending -> Unit+                    TidalPollResult.SlowDown -> intervalMs += SLOW_DOWN_STEP_MS+                    TidalPollResult.Expired -> {+                        failTidalLogin(null)+                        return@launch+                    }+                    is TidalPollResult.Error -> {+                        failTidalLogin(result.message)+                        return@launch+                    }+                    is TidalPollResult.Success -> {+                        val tokens = result.tokens+                        // A blank token would store an account that reports as signed in but+                        // silently resolves nothing, so treat it as a failed sign-in.+                        if (tokens.accessToken.isBlank()) {+                            failTidalLogin(null)+                            return@launch+                        }+                        prefs.setTidalAccount(+                            TidalAccount(+                                accessToken = tokens.accessToken,+                                refreshToken = tokens.refreshToken,+                                expiresAtMs = tokens.expiresAtMs,+                                countryCode = tokens.countryCode,+                                userId = tokens.userId,+                                username = tokens.username,+                            ),+                        )+                        _tidalLogin.value = TidalLoginUiState(status = TidalLoginStatus.Success)+                        return@launch+                    }+                }+            }+            failTidalLogin(null)+        }+    }++    fun cancelTidalLogin() {+        tidalLoginJob?.cancel()+        tidalLoginJob = null+        _tidalLogin.value = TidalLoginUiState()+    }++    private fun failTidalLogin(message: String?) {+        _tidalLogin.value = TidalLoginUiState(+            status = TidalLoginStatus.Failed,+            error = message?.takeIf { it.isNotBlank() },+        )+    }+     // ------------------------------------------------------------------      /**@@ -401,6 +528,7 @@ class MusicBrainzViewModel(application: Application) : AndroidViewModel(applicat                         ?: artistCredit.display().orEmpty(),                     durationMs = track.length ?: track.recording?.length,                     discNumber = medium.position,+                    isrcs = track.recording?.isrcs.orEmpty(),                 )             }         },@@ -449,5 +577,10 @@ class MusicBrainzViewModel(application: Application) : AndroidViewModel(applicat     private fun readableFolderName(uri: String): String = runCatching {         SafTree.rootDocumentId(uri.toUri()).substringAfterLast(':').ifEmpty { uri }     }.getOrDefault(uri)++    private companion object {+        // Tidal answers `slow_down` when polled too eagerly; back off by a second each time.+        const val SLOW_DOWN_STEP_MS = 1_000L+    } }-+
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/platform/download/DownloadQueue.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/platform/download/DownloadQueue.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/platform/download/DownloadQueue.ktindex 5eef11853e..13b9bbedb5 100644--- a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/platform/download/DownloadQueue.kt+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/platform/download/DownloadQueue.kt@@ -37,6 +37,8 @@ data class DownloadRequest(     val trackTotal: Int?,     val discNumber: Int?,     val durationMs: Int?,+    /** The recording's ISRCs, for sources that match on identity rather than a search. */+    val isrcs: List<String> = emptyList(), ) {     /**      * Stable identity for the queue and for WorkManager's unique work name.@@ -121,6 +123,7 @@ internal fun DownloadRequest.toData(): Data = Data.Builder()     .putInt("trackTotal", trackTotal ?: 0)     .putInt("discNumber", discNumber ?: 0)     .putInt("durationMs", durationMs ?: 0)+    .putStringArray("isrcs", isrcs.toTypedArray())     .build()  internal fun Data.toDownloadRequest(): DownloadRequest? {@@ -140,5 +143,6 @@ internal fun Data.toDownloadRequest(): DownloadRequest? {         trackTotal = getInt("trackTotal", 0).takeIf { it > 0 },         discNumber = getInt("discNumber", 0).takeIf { it > 0 },         durationMs = getInt("durationMs", 0).takeIf { it > 0 },+        isrcs = getStringArray("isrcs")?.toList().orEmpty(),     ) }
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/platform/download/DownloadWorker.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/platform/download/DownloadWorker.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/platform/download/DownloadWorker.ktindex 8ee306ca37..526b35a306 100644--- a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/platform/download/DownloadWorker.kt+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/platform/download/DownloadWorker.kt@@ -7,12 +7,13 @@ import androidx.work.WorkerParameters import com.vayunmathur.library.network.NetworkClient import com.vayunmathur.musicbrainz.data.LocalTrack import com.vayunmathur.musicbrainz.data.MusicBrainzRepository-import com.vayunmathur.musicbrainz.data.download.AudioResolver+import com.vayunmathur.musicbrainz.data.download.AudioQuery+import com.vayunmathur.musicbrainz.data.download.AudioSources import com.vayunmathur.musicbrainz.data.download.Lyrics-import com.vayunmathur.musicbrainz.data.download.Mp4Tagger-import com.vayunmathur.musicbrainz.data.download.Mp4Tags import com.vayunmathur.musicbrainz.data.download.OggOpusTagger import com.vayunmathur.musicbrainz.data.download.OpusRemuxer+import com.vayunmathur.musicbrainz.data.download.OpusTranscoder+import com.vayunmathur.musicbrainz.data.download.ResolvedAudio import com.vayunmathur.musicbrainz.data.download.VorbisTags import com.vayunmathur.musicbrainz.data.library.LibraryScanner import com.vayunmathur.musicbrainz.domain.library.MatchKeys@@ -44,79 +45,40 @@ class DownloadWorker(context: Context, params: WorkerParameters) :                 ?: return@withContext fail(key, "No music folder selected")              DownloadQueue.update(DownloadState.Searching, key)-            val audio = AudioResolver.resolve(-                artist = request.artist,-                title = request.title,-                album = request.album,-                durationMs = request.durationMs,-            ) ?: return@withContext fail(key, "No audio source found")+            val audio = resolveAudio(request, prefs)+                ?: return@withContext fail(key, "No audio source found")              DownloadQueue.update(DownloadState.Downloading, key)-            val raw = download(audio.url) { progress ->+            val raw = download(audio.urls) { progress ->                 DownloadQueue.update(DownloadState.Downloading, key, progress)             } ?: return@withContext fail(key, "Download failed")              DownloadQueue.update(DownloadState.Tagging, key, 1f)-            val cover = if (prefs.embedCoverArt.first()) {-                CoverArtCache.get(request.releaseId, request.releaseGroupId)-            } else {-                null-            }-            val lyrics = if (prefs.fetchLyrics.first()) {-                Lyrics.fetch(request.artist, request.title, request.album, request.durationMs)-            } else {-                null-            }+            val cover = CoverArtCache.get(request.releaseId, request.releaseGroupId)+            val lyrics = Lyrics.fetch(request.artist, request.title, request.album, request.durationMs)             android.util.Log.i(                 "MBDownload",-                "tagging '${request.title}': needsRemux=${audio.needsRemux} suffix=${audio.suffix} " +-                    "bitrate=${audio.bitrate} raw=${raw.size} cover=${cover?.size ?: 0} " +-                    "lyrics=${lyrics?.length ?: 0}",+                "tagging '${request.title}': passthrough=${audio.isOpusPassthrough} " ++                    "source=${audio.suffix} bitrate=${audio.bitrate} raw=${raw.size} " ++                    "cover=${cover?.size ?: 0} lyrics=${lyrics?.length ?: 0}",             ) -            val tagged: ByteArray-            val suffix: String-            val mimeType: String-            when {-                audio.needsRemux -> {-                    val ogg = OpusRemuxer.remux(applicationContext, raw)-                    if (ogg != null) {-                        val startsOggS = ogg.size >= 4 &&-                            String(ogg, 0, 4, Charsets.ISO_8859_1) == "OggS"-                        val out = OggOpusTagger.tag(ogg, request.toVorbisTags(cover, lyrics))-                        android.util.Log.i(-                            "MBDownload",-                            "opus tag: oggStartsOggS=$startsOggS ogg=${ogg.size} " +-                                "taggedNull=${out == null} tagged=${out?.size ?: 0}",-                        )-                        tagged = out ?: ogg-                        suffix = "opus"-                        mimeType = "audio/ogg"-                    } else {-                        // Remuxing a valid Opus stream should not fail, but if the platform-                        // muxer refuses it the download is kept as the WebM it arrived as-                        // rather than lost. It carries no tags, but the scan finds it by name.-                        tagged = raw-                        suffix = "webm"-                        mimeType = "audio/webm"-                    }-                }-                audio.suffix == "m4a" -> {-                    tagged = Mp4Tagger.tag(raw, request.toMp4Tags(cover, lyrics)) ?: raw-                    suffix = "m4a"-                    mimeType = "audio/mp4"-                }-                else -> {-                    // Only MP4 and Ogg/Opus can be annotated here, so anything else is stored-                    // as fetched. It still gets found by the library scan, just on name and path.-                    tagged = raw-                    suffix = audio.suffix-                    mimeType = audio.mimeType-                }-            }-            android.util.Log.i("MBDownload", "writing '${request.title}' as .$suffix ($mimeType)")+            // Every download is filed as a tagged `.opus`. A stream that is already 48 kHz+            // Opus is only rewrapped into Ogg; everything else is re-encoded. A failure here+            // fails the download rather than writing one of the formats being replaced.+            val ogg = if (audio.isOpusPassthrough) {+                OpusRemuxer.remux(applicationContext, raw)+            } else {+                OpusTranscoder.transcode(raw) { isStopped }+            } ?: return@withContext fail(key, "Could not convert the download to Opus")++            val tagged = OggOpusTagger.tag(ogg, request.toVorbisTags(cover, lyrics)) ?: ogg+            android.util.Log.i(+                "MBDownload",+                "writing '${request.title}' as .opus: ogg=${ogg.size} tagged=${tagged.size}",+            ) -            val written = writeToLibrary(treeUri, request, suffix, mimeType, tagged)+            val written = writeToLibrary(treeUri, request, "opus", "audio/ogg", tagged)                 ?: return@withContext fail(key, "Could not write to music folder")              recordInIndex(written, request, tagged.size)@@ -132,6 +94,30 @@ class DownloadWorker(context: Context, params: WorkerParameters) :         return Result.failure()     } +    /**+     * Asks each source in the user's order until one has a match.+     *+     * A source that throws is treated as no match: the point of the fallback order is that+     * a lapsed Tidal subscription degrades the download to YouTube rather than losing it.+     */+    private suspend fun resolveAudio(+        request: DownloadRequest,+        prefs: MusicBrainzPrefs,+    ): ResolvedAudio? {+        val query = AudioQuery(+            artist = request.artist,+            title = request.title,+            album = request.album,+            durationMs = request.durationMs,+            isrcs = request.isrcs,+        )+        for (source in AudioSources.ordered(applicationContext, prefs.downloadSource.first())) {+            val audio = runCatching { source.resolve(query) }.getOrNull()+            if (audio != null && audio.urls.isNotEmpty()) return audio+        }+        return null+    }+     /**      * Streams the audio into memory, reporting progress as it goes.      *@@ -139,29 +125,43 @@ class DownloadWorker(context: Context, params: WorkerParameters) :      * rewrite the container before the file is filed away, and a partially written track      * appearing in the user's music folder would be picked up by every other player on      * the device.+     *+     * [urls] is a single progressive stream for YouTube and one entry per DASH segment for+     * Tidal, so the parts are concatenated in order into the one buffer. A segmented stream+     * reports progress by segments finished: asking each of a few hundred segments for its+     * length first would double the requests and stall the download before it started.      */-    private suspend fun download(url: String, onProgress: (Float) -> Unit): ByteArray? {-        val expected = NetworkClient.getContentLength(url) ?: 0L+    private suspend fun download(urls: List<String>, onProgress: (Float) -> Unit): ByteArray? {+        val expected = if (urls.size == 1) NetworkClient.getContentLength(urls[0]) ?: 0L else 0L         val buffer = ByteArrayOutputStream(if (expected > 0) expected.toInt() else DEFAULT_BUFFER)         var lastReported = 0L-        val response = NetworkClient.stream(url) { stream, resp ->-            if (stream == null || !resp.isSuccess) return@stream-            val chunk = ByteArray(READ_BUFFER)-            while (!stream.isClosedForRead) {-                if (isStopped) return@stream-                val read = stream.read(chunk)-                if (read <= 0) break-                buffer.write(chunk, 0, read)-                if (expected > 0) {-                    val now = System.currentTimeMillis()-                    if (now - lastReported > PROGRESS_INTERVAL_MS) {-                        lastReported = now-                        onProgress((buffer.size().toFloat() / expected).coerceIn(0f, 1f))+        for ((index, url) in urls.withIndex()) {+            if (isStopped) return null+            val response = NetworkClient.stream(url) { stream, resp ->+                if (stream == null || !resp.isSuccess) return@stream+                val chunk = ByteArray(READ_BUFFER)+                while (!stream.isClosedForRead) {+                    if (isStopped) return@stream+                    val read = stream.read(chunk)+                    if (read <= 0) break+                    buffer.write(chunk, 0, read)+                    if (expected > 0) {+                        val now = System.currentTimeMillis()+                        if (now - lastReported > PROGRESS_INTERVAL_MS) {+                            lastReported = now+                            onProgress((buffer.size().toFloat() / expected).coerceIn(0f, 1f))+                        }                     }                 }             }+            // A missing segment would leave a file that stops playing part-way through, so+            // a segmented stream fails outright rather than being written incomplete.+            if (!response.isSuccess && urls.size > 1) return null+            if (urls.size > 1) onProgress((index + 1).toFloat() / urls.size)         }-        if (!response.isSuccess && buffer.size() == 0) return null+        // Being stopped abandons the read mid-segment, so what is buffered is a truncated+        // file; writing it would leave the library holding a track that never plays through.+        if (isStopped) return null         return buffer.toByteArray().takeIf { it.isNotEmpty() }     } @@ -235,25 +235,6 @@ class DownloadWorker(context: Context, params: WorkerParameters) :     } } -private fun DownloadRequest.toMp4Tags(cover: ByteArray?, lyrics: String?) = Mp4Tags(-    title = title,-    artist = artist,-    album = album,-    albumArtist = albumArtist,-    date = date,-    lyrics = lyrics,-    trackNumber = trackNumber,-    trackTotal = trackTotal,-    discNumber = discNumber,-    coverArt = cover,-    coverIsPng = cover.isPng(),-    freeform = buildMap {-        recordingId?.let { put("MusicBrainz Track Id", it) }-        releaseId?.let { put("MusicBrainz Album Id", it) }-        releaseTrackId?.let { put("MusicBrainz Release Track Id", it) }-    },-)- private fun DownloadRequest.toVorbisTags(cover: ByteArray?, lyrics: String?) = VorbisTags(     title = title,     artist = artist,
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/ui/SettingsScreen.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/ui/SettingsScreen.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/ui/SettingsScreen.ktindex 55603a8a36..c824e0d534 100644--- a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/ui/SettingsScreen.kt+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/ui/SettingsScreen.kt@@ -19,13 +19,18 @@ import com.vayunmathur.library.ui.IconFolder import com.vayunmathur.library.ui.IconRefresh import com.vayunmathur.library.ui.SettingsRow import com.vayunmathur.library.ui.SettingsSection+import com.vayunmathur.library.ui.SettingsSelectRow import com.vayunmathur.library.ui.SettingsSwitchRow+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.musicbrainz.R import com.vayunmathur.musicbrainz.Route+import com.vayunmathur.musicbrainz.platform.DownloadSource import com.vayunmathur.musicbrainz.platform.MusicBrainzActions import com.vayunmathur.musicbrainz.platform.MusicBrainzViewModel import com.vayunmathur.musicbrainz.platform.SettingsUiState+import com.vayunmathur.musicbrainz.platform.TidalQuality  /**  * Binds the settings screen to the ViewModel.@@ -56,6 +61,9 @@ fun SettingsScreen(     onPickFolder: () -> Unit, ) {     AppScaffold(title = stringResource(R.string.settings), backStack = backStack) { padding ->+        // Resolved up front: SettingsSelectRow's label is a plain lambda, not composable.+        val sourceLabels = DownloadSource.entries.associateWith { stringResource(it.labelRes) }+        val qualityLabels = TidalQuality.entries.associateWith { stringResource(it.labelRes) }         Column(             Modifier                 .fillMaxSize()@@ -92,6 +100,13 @@ fun SettingsScreen(                 )             }             SettingsSection(title = stringResource(R.string.downloads)) {+                SettingsSelectRow(+                    title = stringResource(R.string.download_source),+                    selected = state.downloadSource,+                    options = DownloadSource.entries,+                    label = { sourceLabels.getValue(it) },+                    onSelect = actions::setDownloadSource,+                )                 SettingsSwitchRow(                     title = stringResource(R.string.embed_cover_art),                     checked = state.embedCoverArt,@@ -105,7 +120,36 @@ fun SettingsScreen(                     supportingText = stringResource(R.string.fetch_lyrics_description),                 )             }+            SettingsSection(title = stringResource(R.string.download_source_tidal)) {+                if (state.tidalUsername != null) {+                    SettingsRow(+                        title = stringResource(R.string.tidal_account),+                        supportingText = state.tidalUsername,+                        trailingContent = {+                            TextButton(onClick = actions::signOutOfTidal) {+                                Text(stringResource(R.string.tidal_sign_out))+                            }+                        },+                    )+                } else {+                    SettingsRow(+                        title = stringResource(R.string.tidal_sign_in),+                        supportingText = stringResource(R.string.tidal_signed_out),+                        onClick = { backStack.add(Route.TidalLogin) },+                    )+                }+                // Quality only means anything once Tidal is the source audio comes from.+                if (state.downloadSource == DownloadSource.Tidal) {+                    SettingsSelectRow(+                        title = stringResource(R.string.tidal_quality),+                        selected = state.tidalQuality,+                        options = TidalQuality.entries,+                        label = { qualityLabels.getValue(it) },+                        onSelect = actions::setTidalQuality,+                    )+                }+            }         }     } }-+
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/ui/TidalLoginScreen.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/ui/TidalLoginScreen.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/ui/TidalLoginScreen.ktnew file mode 100644index 0000000000..1278484fe7--- /dev/null+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/ui/TidalLoginScreen.kt@@ -0,0 +1,117 @@+package com.vayunmathur.musicbrainz.ui++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.runtime.DisposableEffect+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.dp+import androidx.lifecycle.compose.collectAsStateWithLifecycle+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.CircularProgressIndicator+import com.vayunmathur.library.ui.ExternalIntents+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedButton+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.musicbrainz.R+import com.vayunmathur.musicbrainz.Route+import com.vayunmathur.musicbrainz.platform.MusicBrainzViewModel+import com.vayunmathur.musicbrainz.platform.TidalLoginStatus+import com.vayunmathur.musicbrainz.platform.TidalLoginUiState++/**+ * The Tidal device-code sign-in.+ *+ * Kicks off the flow on entry, shows the code and where to enter it, and pops itself once+ * the ViewModel reports the poll succeeded. Leaving before that cancels the poll.+ */+@Composable+fun TidalLoginPage(backStack: NavBackStack<Route>, viewModel: MusicBrainzViewModel) {+    val state by viewModel.tidalLogin.collectAsStateWithLifecycle()++    LaunchedEffect(Unit) { viewModel.startTidalLogin() }++    DisposableEffect(Unit) {+        onDispose {+            // If the user backed out mid-flow, stop polling; a completed login already reset.+            if (viewModel.tidalLogin.value.status != TidalLoginStatus.Success) {+                viewModel.cancelTidalLogin()+            }+        }+    }++    LaunchedEffect(state.status) {+        if (state.status == TidalLoginStatus.Success) backStack.pop()+    }++    TidalLoginScreen(+        state = state,+        backStack = backStack,+        onRetry = viewModel::startTidalLogin,+    )+}++@Composable+fun TidalLoginScreen(+    state: TidalLoginUiState,+    backStack: NavBackStack<Route>,+    onRetry: () -> Unit,+) {+    val context = LocalContext.current+    AppScaffold(title = stringResource(R.string.tidal_sign_in), backStack = backStack) { padding ->+        Column(+            modifier = Modifier+                .fillMaxSize()+                .padding(padding)+                .padding(24.dp),+            horizontalAlignment = Alignment.CenterHorizontally,+            verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterVertically),+        ) {+            when (state.status) {+                TidalLoginStatus.Failed -> {+                    Text(+                        state.error ?: stringResource(R.string.tidal_login_failed),+                        textAlign = TextAlign.Center,+                    )+                    Button(onClick = onRetry) { Text(stringResource(R.string.retry)) }+                }+                TidalLoginStatus.AwaitingUser -> {+                    Text(+                        stringResource(R.string.tidal_login_instructions),+                        textAlign = TextAlign.Center,+                    )+                    val code = state.userCode.orEmpty()+                    Text(+                        code,+                        style = MaterialTheme.typography.displaySmall,+                        modifier = Modifier.fillMaxWidth(),+                        textAlign = TextAlign.Center,+                    )+                    OutlinedButton(+                        onClick = { ExternalIntents.copyToClipboard(context, code) },+                    ) { Text(stringResource(R.string.tidal_copy_code)) }+                    state.verificationUri?.let { uri ->+                        Button(onClick = { ExternalIntents.openUrl(context, uri) }) {+                            Text(stringResource(R.string.tidal_open_browser))+                        }+                    }+                }+                else -> {+                    CircularProgressIndicator()+                    Text(stringResource(R.string.tidal_login_starting))+                }+            }+        }+    }+}
musicbrainz/src/main/res/values/strings.xml
diff --git a/musicbrainz/src/main/res/values/strings.xml b/musicbrainz/src/main/res/values/strings.xmlindex 0e0b9f33ab..4a21054e7c 100644--- a/musicbrainz/src/main/res/values/strings.xml+++ b/musicbrainz/src/main/res/values/strings.xml@@ -93,4 +93,38 @@     <string name="fetch_lyrics">Lyrics</string>     <!-- Settings row: explanation of the lyrics setting. -->     <string name="fetch_lyrics_description">Look up synced lyrics and save them with the song.</string>+    <!-- Settings row: picks where downloaded audio is fetched from. Noun. -->+    <string name="download_source">Download from</string>+    <!-- Download source: YouTube. Brand name, do not translate. -->+    <string name="download_source_youtube" translatable="false">YouTube</string>+    <!-- Download source: Tidal. Brand name, do not translate. -->+    <string name="download_source_tidal" translatable="false">Tidal</string>+    <!-- Settings row: picks how good the audio Tidal is asked for should be. Noun. -->+    <string name="tidal_quality">Audio quality</string>+    <!-- Audio quality: smallest files. Adjective. -->+    <string name="tidal_quality_low">Low</string>+    <!-- Audio quality: everyday listening. Adjective. -->+    <string name="tidal_quality_normal">Normal</string>+    <!-- Audio quality: lossless CD quality. Adjective. -->+    <string name="tidal_quality_high">High</string>+    <!-- Audio quality: best Tidal offers. Adjective. -->+    <string name="tidal_quality_max">Max</string>+    <!-- Settings section: the user's Tidal subscription. -->+    <string name="tidal_account">Tidal account</string>+    <!-- Settings row: shown when no Tidal account is connected. -->+    <string name="tidal_signed_out">Not signed in. Downloads use YouTube.</string>+    <!-- Settings row: disconnects the Tidal account. Verb. -->+    <string name="tidal_sign_out">Sign out</string>+    <!-- Sign-in screen: title, and the row that opens it. Verb. -->+    <string name="tidal_sign_in">Sign in to Tidal</string>+    <!-- Sign-in screen: shown while the code is being requested. -->+    <string name="tidal_login_starting">Starting sign-in\u2026</string>+    <!-- Sign-in screen: tells the user what to do with the code below. -->+    <string name="tidal_login_instructions">Open the link below and enter this code to finish signing in.</string>+    <!-- Sign-in screen: copies the code to the clipboard. Verb. -->+    <string name="tidal_copy_code">Copy code</string>+    <!-- Sign-in screen: opens the Tidal page where the code is entered. Verb. -->+    <string name="tidal_open_browser">Open browser</string>+    <!-- Sign-in screen: shown when sign-in did not complete. -->+    <string name="tidal_login_failed">Could not sign in to Tidal.</string> </resources>
musicbrainz/src/test/java/com/vayunmathur/musicbrainz/data/download/Mp4TaggerTest.kt
diff --git a/musicbrainz/src/test/java/com/vayunmathur/musicbrainz/data/download/Mp4TaggerTest.kt b/musicbrainz/src/test/java/com/vayunmathur/musicbrainz/data/download/Mp4TaggerTest.ktdeleted file mode 100644index 9ac7c601e8..0000000000--- a/musicbrainz/src/test/java/com/vayunmathur/musicbrainz/data/download/Mp4TaggerTest.kt+++ /dev/null@@ -1,201 +0,0 @@-package com.vayunmathur.musicbrainz.data.download--import com.vayunmathur.musicbrainz.data.library.TagReader-import java.io.ByteArrayOutputStream-import java.io.File-import java.io.RandomAccessFile-import kotlin.test.Test-import kotlin.test.assertContentEquals-import kotlin.test.assertEquals-import kotlin.test.assertNotNull-import kotlin.test.assertNull-import kotlin.test.assertTrue--/**- * Round-trip tests for the MP4 tagger and the tag reader.- *- * These two have to agree exactly: the identifiers [Mp4Tagger] writes into a download are- * the same ones [TagReader] reads back during a library scan to decide the track is- * already owned. A mismatch would silently make every download look missing forever, and- * that is not something the UI would reveal.- */-class Mp4TaggerTest {--    private fun box(type: String, content: ByteArray): ByteArray {-        val out = ByteArrayOutputStream()-        out.write(intBytes(content.size + 8))-        out.write(type.toByteArray(Charsets.ISO_8859_1))-        out.write(content)-        return out.toByteArray()-    }--    private fun intBytes(value: Int) = byteArrayOf(-        (value ushr 24).toByte(),-        (value ushr 16).toByte(),-        (value ushr 8).toByte(),-        value.toByte(),-    )--    private fun readInt(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)--    /**-     * A minimal faststart MP4: `ftyp`, then `moov` holding one chunk offset table, then-     * `mdat`. This is the layout that makes tagging risky, because growing `moov` moves-     * the audio and invalidates the offsets.-     */-    private fun syntheticMp4(chunkOffsets: List<Int>): Pair<ByteArray, Int> {-        val stcoContent = ByteArrayOutputStream()-        stcoContent.write(intBytes(0)) // version and flags-        stcoContent.write(intBytes(chunkOffsets.size))-        chunkOffsets.forEach { stcoContent.write(intBytes(it)) }-        val stbl = box("stbl", box("stco", stcoContent.toByteArray()))-        val minf = box("minf", stbl)-        val mdia = box("mdia", minf)-        val trak = box("trak", mdia)-        val moov = box("moov", trak)-        val ftyp = box("ftyp", "isom".toByteArray(Charsets.ISO_8859_1) + ByteArray(8))-        val mdat = box("mdat", ByteArray(512) { (it % 251).toByte() })--        val file = ByteArrayOutputStream()-        file.write(ftyp)-        file.write(moov)-        file.write(mdat)-        return file.toByteArray() to moov.size-    }--    private fun readBack(bytes: ByteArray): com.vayunmathur.musicbrainz.data.library.AudioTags {-        val temp = File.createTempFile("tagger", ".m4a")-        try {-            temp.writeBytes(bytes)-            RandomAccessFile(temp, "r").use { return TagReader.readMp4(it.channel) }-        } finally {-            temp.delete()-        }-    }--    @Test-    fun `writes and reads back every tag it supports`() {-        val (source, _) = syntheticMp4(listOf(1000))-        val tagged = Mp4Tagger.tag(-            source,-            Mp4Tags(-                title = "Midnight Drive",-                artist = "The Neon Owls",-                album = "After Hours",-                albumArtist = "The Neon Owls",-                date = "2024-03-01",-                trackNumber = 3,-                trackTotal = 8,-                freeform = mapOf(-                    "MusicBrainz Track Id" to "11111111-2222-3333-4444-555555555555",-                    "MusicBrainz Album Id" to "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",-                    "MusicBrainz Release Track Id" to "99999999-8888-7777-6666-555555555555",-                ),-            ),-        )-        assertNotNull(tagged)--        val tags = readBack(tagged)-        assertEquals("Midnight Drive", tags.title)-        assertEquals("The Neon Owls", tags.artist)-        assertEquals("After Hours", tags.album)-        assertEquals("The Neon Owls", tags.albumArtist)-        assertEquals("11111111-2222-3333-4444-555555555555", tags.recordingId)-        assertEquals("aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee", tags.releaseId)-        assertEquals("99999999-8888-7777-6666-555555555555", tags.releaseTrackId)-    }--    /**-     * The whole point of the `stco` fixup: the audio has moved, so the offsets pointing at-     * it must move by exactly the same amount or the file plays silence.-     */-    @Test-    fun `shifts chunk offsets by the amount moov grew`() {-        val originalOffsets = listOf(1000, 2000, 3000)-        val (source, originalMoovSize) = syntheticMp4(originalOffsets)-        val tagged = assertNotNull(Mp4Tagger.tag(source, Mp4Tags(title = "Test")))--        val moovStart = readInt(source, 0) // ftyp size; moov begins right after-        val newMoovSize = readInt(tagged, moovStart)-        val delta = newMoovSize - originalMoovSize-        assertTrue(delta > 0, "tagging should have grown moov")--        val shifted = findChunkOffsets(tagged)-        assertContentEquals(originalOffsets.map { it + delta }, shifted)-    }--    /** Offsets must be left alone when `moov` already sits after the audio. */-    @Test-    fun `leaves chunk offsets alone when moov follows mdat`() {-        val originalOffsets = listOf(64, 128)-        val stcoContent = ByteArrayOutputStream()-        stcoContent.write(intBytes(0))-        stcoContent.write(intBytes(originalOffsets.size))-        originalOffsets.forEach { stcoContent.write(intBytes(it)) }-        val moov = box("moov", box("trak", box("mdia", box("minf", box("stbl", box("stco", stcoContent.toByteArray()))))))-        val file = ByteArrayOutputStream()-        file.write(box("ftyp", "isom".toByteArray(Charsets.ISO_8859_1) + ByteArray(8)))-        file.write(box("mdat", ByteArray(256)))-        file.write(moov)--        val tagged = assertNotNull(Mp4Tagger.tag(file.toByteArray(), Mp4Tags(title = "Test")))-        assertContentEquals(originalOffsets, findChunkOffsets(tagged))-    }--    @Test-    fun `returns null for input that is not an mp4`() {-        assertNull(Mp4Tagger.tag("not an mp4 at all, just bytes".toByteArray(), Mp4Tags(title = "x")))-    }--    @Test-    fun `omits tags that were not supplied`() {-        val (source, _) = syntheticMp4(listOf(1000))-        val tagged = assertNotNull(Mp4Tagger.tag(source, Mp4Tags(title = "Only A Title")))-        val tags = readBack(tagged)-        assertEquals("Only A Title", tags.title)-        assertNull(tags.artist)-        assertNull(tags.recordingId)-    }--    /** Re-tagging must replace the previous `udta`, not stack a second one alongside it. */-    @Test-    fun `retagging replaces the previous metadata`() {-        val (source, _) = syntheticMp4(listOf(1000))-        val once = assertNotNull(Mp4Tagger.tag(source, Mp4Tags(title = "First", artist = "A")))-        val twice = assertNotNull(Mp4Tagger.tag(once, Mp4Tags(title = "Second", artist = "B")))--        val tags = readBack(twice)-        assertEquals("Second", tags.title)-        assertEquals("B", tags.artist)-        assertEquals(1, countBoxes(twice, "udta"))-    }--    private fun findChunkOffsets(buf: ByteArray): List<Int> {-        var index = 0-        while (index + 8 <= buf.size) {-            if (String(buf, index + 4, 4, Charsets.ISO_8859_1) == "stco") {-                val count = readInt(buf, index + 12)-                return (0 until count).map { readInt(buf, index + 16 + it * 4) }-            }-            index++-        }-        return emptyList()-    }--    private fun countBoxes(buf: ByteArray, type: String): Int {-        var count = 0-        for (index in 0..buf.size - 8) {-            if (String(buf, index + 4, 4, Charsets.ISO_8859_1) == type &&-                readInt(buf, index) in 8..buf.size-            ) {-                count++-            }-        }-        return count-    }-}-
musicbrainz/src/test/java/com/vayunmathur/musicbrainz/data/download/TidalManifestTest.kt
diff --git a/musicbrainz/src/test/java/com/vayunmathur/musicbrainz/data/download/TidalManifestTest.kt b/musicbrainz/src/test/java/com/vayunmathur/musicbrainz/data/download/TidalManifestTest.ktnew file mode 100644index 0000000000..dc71398030--- /dev/null+++ b/musicbrainz/src/test/java/com/vayunmathur/musicbrainz/data/download/TidalManifestTest.kt@@ -0,0 +1,126 @@+package com.vayunmathur.musicbrainz.data.download++import java.util.Base64+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith++/**+ * Tests for the Tidal manifest decoder.+ *+ * The manifest is the one part of the Tidal path that is pure data transformation and so+ * can be pinned down off-device. A mistake here means either a download of the wrong number+ * of segments (a truncated or corrupt file) or the wrong extension (an untaggable file), so+ * both the BTS and DASH shapes and the codec-to-extension mapping are covered.+ */+class TidalManifestTest {++    private fun b64(s: String): String = Base64.getEncoder().encodeToString(s.toByteArray(Charsets.UTF_8))++    @Test+    fun `bts flac manifest yields the urls and a flac extension`() {+        val manifest = b64(+            """{"mimeType":"audio/flac","codecs":"flac","encryptionType":"NONE",""" ++                """"urls":["https://cdn.tidal.com/a","https://cdn.tidal.com/b"]}""",+        )+        val stream = TidalManifest.decode("application/vnd.tidal.bts", manifest, "LOSSLESS")+        assertEquals(listOf("https://cdn.tidal.com/a", "https://cdn.tidal.com/b"), stream.urls)+        assertEquals("flac", stream.suffix)+        assertEquals("audio/flac", stream.mimeType)+    }++    @Test+    fun `hi-res flac-codec manifest is filed as m4a`() {+        val manifest = b64(+            """{"mimeType":"audio/mp4","codecs":"flac","encryptionType":"NONE","urls":["https://cdn/1"]}""",+        )+        val stream = TidalManifest.decode("application/vnd.tidal.bts", manifest, "HI_RES_LOSSLESS")+        assertEquals("m4a", stream.suffix)+        assertEquals("audio/mp4", stream.mimeType)+    }++    @Test+    fun `bts aac manifest is filed as m4a`() {+        val manifest = b64(+            """{"mimeType":"audio/mp4","codecs":"mp4a.40.2","encryptionType":"NONE","urls":["https://cdn/1"]}""",+        )+        val stream = TidalManifest.decode("application/vnd.tidal.bts", manifest, "HIGH")+        assertEquals("m4a", stream.suffix)+    }++    @Test+    fun `dash manifest expands the segment timeline including repeats`() {+        val mpd = """+            <?xml version="1.0" encoding="UTF-8"?>+            <MPD xmlns="urn:mpeg:dash:schema:mpd:2011">+              <Period>+                <AdaptationSet>+                  <Representation codecs="mp4a.40.2">+                    <SegmentTemplate media="https://cdn.tidal.com/seg_${'$'}Number${'$'}.mp4">+                      <SegmentTimeline>+                        <S d="100" r="2"/>+                        <S d="100"/>+                      </SegmentTimeline>+                    </SegmentTemplate>+                  </Representation>+                </AdaptationSet>+              </Period>+            </MPD>+        """.trimIndent()+        val stream = TidalManifest.decode("application/dash+xml", b64(mpd), "HI_RES_LOSSLESS")+        // S with r=2 is 3 segments, plus 1 = 4; $Number$ runs 0..4 inclusive = 5 urls.+        assertEquals(5, stream.urls.size)+        assertEquals("https://cdn.tidal.com/seg_0.mp4", stream.urls.first())+        assertEquals("https://cdn.tidal.com/seg_4.mp4", stream.urls.last())+        assertEquals("m4a", stream.suffix)+    }++    @Test+    fun `a protected dash manifest is rejected`() {+        val mpd = """+            <?xml version="1.0" encoding="UTF-8"?>+            <MPD xmlns="urn:mpeg:dash:schema:mpd:2011">+              <Period>+                <AdaptationSet>+                  <ContentProtection schemeIdUri="urn:mpeg:dash:mp4protection:2011"/>+                  <Representation codecs="mp4a.40.2">+                    <SegmentTemplate media="https://cdn/seg_${'$'}Number${'$'}.mp4">+                      <SegmentTimeline><S d="100"/></SegmentTimeline>+                    </SegmentTemplate>+                  </Representation>+                </AdaptationSet>+              </Period>+            </MPD>+        """.trimIndent()+        assertFailsWith<IllegalArgumentException> {+            TidalManifest.decode("application/dash+xml", b64(mpd), "HI_RES_LOSSLESS")+        }+    }++    @Test+    fun `an encrypted manifest is rejected`() {+        val manifest = b64(+            """{"mimeType":"audio/flac","codecs":"flac","encryptionType":"OLD_AES","urls":["https://cdn/1"]}""",+        )+        assertFailsWith<IllegalArgumentException> {+            TidalManifest.decode("application/vnd.tidal.bts", manifest, "LOSSLESS")+        }+    }++    @Test+    fun `an unknown codec is rejected`() {+        val manifest = b64(+            """{"mimeType":"audio/x","codecs":"vorbis","encryptionType":"NONE","urls":["https://cdn/1"]}""",+        )+        assertFailsWith<IllegalArgumentException> {+            TidalManifest.decode("application/vnd.tidal.bts", manifest, "LOW")+        }+    }++    @Test+    fun `an unknown manifest type is rejected`() {+        assertFailsWith<IllegalArgumentException> {+            TidalManifest.decode("application/unknown", b64("{}"), "LOW")+        }+    }+}
musicbrainz/src/test/java/com/vayunmathur/musicbrainz/data/library/MatchingTest.kt
diff --git a/musicbrainz/src/test/java/com/vayunmathur/musicbrainz/data/library/MatchingTest.kt b/musicbrainz/src/test/java/com/vayunmathur/musicbrainz/data/library/MatchingTest.ktindex 44a75d8edf..f6e23d5ef5 100644--- a/musicbrainz/src/test/java/com/vayunmathur/musicbrainz/data/library/MatchingTest.kt+++ b/musicbrainz/src/test/java/com/vayunmathur/musicbrainz/data/library/MatchingTest.kt@@ -1,6 +1,7 @@ package com.vayunmathur.musicbrainz.data.library  import com.vayunmathur.musicbrainz.data.LocalTrack+import com.vayunmathur.musicbrainz.domain.library.MatchKeys import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse