Skip to content

Native Android client for Spotify, built with Jetpack Compose

Faster downloads, as SpotiFLAC Mobile does them

kota-zoe1bf29e2710f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d512862a..8b9fd44f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,7 +6,7 @@ Each release on GitHub shows its section below. The app shows it too when it off
A new engine, written from scratch, and a cleaner app on top of it.
-- **Lossless downloads**: the offline downloads are now FLAC. Myspoti finds the same recording on a lossless service (Tidal, Qobuz or Amazon) by the track's ISRC and takes it as it is served, never re-encoded — 16-bit CD quality, **24-bit hi-res when it exists**, or AAC re-encoded on the phone to keep them small (in Settings). Tidal and Qobuz come through the same signed servers as SpotiFLAC Mobile's extensions, three songs at a time; a one-off verification in Settings turns them on. A track with no lossless recording anywhere is marked unavailable.
+- **Lossless downloads**: the offline downloads are now FLAC. Myspoti finds the same recording on a lossless service (Tidal, Qobuz or Amazon) by the track's ISRC and takes it as it is served, never re-encoded — 16-bit CD quality, **24-bit hi-res when it exists**, or AAC re-encoded on the phone to keep them small (in Settings). Tidal (and Qobuz) come through the same signed servers as SpotiFLAC Mobile's extensions, three songs at a time and three segments per song; the smallest quality takes Tidal's own AAC as it is served. A one-off verification in Settings turns them on. A track with no lossless recording anywhere is marked unavailable.
- **Sound quality, chosen at the start**: a first step after sign-in picks the streaming quality (Automatic, Low 24 kbit/s, Normal 96, High 160) and the download quality (off, smallest AAC 96 kbit/s, FLAC CD, FLAC hi-res). Both stay in the new **Settings** page.
- **Connect shows your headphones**: with Bluetooth or wired headphones, their name replaces "This phone", a "This phone" row sends the sound back to the speaker, and a Bluetooth button opens the pairing settings. The quality badge opens a small page with what plays now (codec and bitrate) and the setting.
- **Downloads ask their quality** if you want ("Ask each time"): once for a whole playlist, kept for its new songs.
diff --git a/base/app/build.gradle.kts b/base/app/build.gradle.kts
index b5fb72cc..008dc94d 100644
--- a/base/app/build.gradle.kts
+++ b/base/app/build.gradle.kts
@@ -99,6 +99,8 @@ dependencies {
// The SpotiFLAC verification opens in a browser tab, as SpotiFLAC Mobile does.
implementation("androidx.browser:browser:1.8.0")
testImplementation("junit:junit:4.13.2")
+ // The real org.json in unit tests (android.jar only has stubs).
+ testImplementation("org.json:json:20240303")
androidTestImplementation("androidx.test:runner:1.6.2")
androidTestImplementation("androidx.test.ext:junit:1.2.1")
implementation(libs.androidx.core.ktx)
diff --git a/base/app/src/main/java/com/music/spotui/data/offline/AacTranscoder.kt b/base/app/src/main/java/com/music/spotui/data/offline/AacTranscoder.kt
index 4138edb9..dc8cfa37 100644
--- a/base/app/src/main/java/com/music/spotui/data/offline/AacTranscoder.kt
+++ b/base/app/src/main/java/com/music/spotui/data/offline/AacTranscoder.kt
@@ -160,6 +160,11 @@ object AacTranscoder {
*/
internal fun toPcm16(buf: ByteBuffer, encoding: Int, inChannels: Int, outChannels: Int, step: Int = 1): ByteArray {
val b = buf.slice().order(ByteOrder.nativeOrder())
+ // The usual case (CD FLAC, 16-bit stereo): the decoder's bytes are already what the encoder takes.
+ if (step == 1 && inChannels == outChannels &&
+ encoding != android.media.AudioFormat.ENCODING_PCM_FLOAT && encoding != android.media.AudioFormat.ENCODING_PCM_32BIT &&
+ encoding != android.media.AudioFormat.ENCODING_PCM_24BIT_PACKED
+ ) return ByteArray(b.remaining()).also { b.get(it) }
val bytesPerSample = when (encoding) {
android.media.AudioFormat.ENCODING_PCM_FLOAT, android.media.AudioFormat.ENCODING_PCM_32BIT -> 4
android.media.AudioFormat.ENCODING_PCM_24BIT_PACKED -> 3
diff --git a/base/app/src/main/java/com/music/spotui/data/offline/OfflineDownloader.kt b/base/app/src/main/java/com/music/spotui/data/offline/OfflineDownloader.kt
index 39762fae..856f5d6e 100644
--- a/base/app/src/main/java/com/music/spotui/data/offline/OfflineDownloader.kt
+++ b/base/app/src/main/java/com/music/spotui/data/offline/OfflineDownloader.kt
@@ -26,6 +26,7 @@ import kotlinx.coroutines.runInterruptible
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
+import kotlinx.coroutines.sync.withPermit
import okhttp3.HttpUrl.Companion.toHttpUrl
import org.json.JSONArray
import org.json.JSONObject
@@ -84,6 +85,9 @@ object OfflineDownloader {
private class Unavailable(message: String) : Exception(message)
+ /** Two AAC encodes at once at most: the CPU stays free for the rest of the app. */
+ private val encodeSlots = kotlinx.coroutines.sync.Semaphore(2)
+
@Volatile private var hinted = false
/**
@@ -255,7 +259,8 @@ object OfflineDownloader {
Log.i(TAG, "${meta.title}: isrc=${meta.isrc ?: "-"} preview=${if (previewFeatures != null) "ok" else if (previewLink != null) "unusable" else "none"}")
// ── Lossless resolve: gated SpotiFLAC first, then the community backends.
- val file = resolveAndFetch(r, meta, audioTmp, quality == com.music.spotui.data.preferences.DownloadQuality.HI_RES)
+ val file = resolveAndFetch(r, meta, audioTmp, quality == com.music.spotui.data.preferences.DownloadQuality.HI_RES,
+ small = quality == com.music.spotui.data.preferences.DownloadQuality.SMALL)
?: throw Unavailable("no lossless match")
currentCoroutineContext().ensureActive()
@@ -275,12 +280,17 @@ object OfflineDownloader {
}
val out: File
- if (quality == com.music.spotui.data.preferences.DownloadQuality.SMALL) {
+ if (file.aac) {
+ // Tidal's own AAC: already small, kept as it was served.
+ out = File(OfflineStore.audioDir, "${r.trackId}.m4a")
+ if (!audioTmp.renameTo(out)) throw IOException("could not move the file")
+ } else if (quality == com.music.spotui.data.preferences.DownloadQuality.SMALL) {
// "Smallest": the checked FLAC becomes AAC, encoded on the phone.
out = File(OfflineStore.audioDir, "${r.trackId}.m4a")
val aacTmp = File(OfflineStore.tmpDir, "${r.trackId}.m4apart")
try {
- checkLock.withLock { runInterruptible(Dispatchers.Default) { AacTranscoder.transcode(audioTmp, aacTmp) } }
+ // Not under checkLock: encoding is long, the other downloads must not queue behind it.
+ encodeSlots.withPermit { runInterruptible(Dispatchers.Default) { AacTranscoder.transcode(audioTmp, aacTmp) } }
if (aacTmp.length() < 10_000 || !aacTmp.renameTo(out)) throw IOException("could not encode the small file")
} finally {
aacTmp.delete()
@@ -304,22 +314,23 @@ object OfflineDownloader {
}
}
- private class Fetched(val provider: String, val isrcMatched: Boolean) {
+ private class Fetched(val provider: String, val isrcMatched: Boolean, val aac: Boolean = false) {
var verified = false
}
- /** Runs the lossless resolver and saves the audio into [out]; null when nothing matched. */
/** This download's quality: the one chosen when it started, else Settings (CD when Settings says "ask"). */
private fun qualityOf(r: Request): com.music.spotui.data.preferences.DownloadQuality =
com.music.spotui.data.preferences.DownloadQuality.saved(r.quality)
?: com.music.spotui.data.preferences.DownloadQuality.saved(com.music.spotui.data.preferences.getDownloadQuality(Graph.app).name)
?: com.music.spotui.data.preferences.DownloadQuality.CD
- private suspend fun resolveAndFetch(r: Request, meta: Meta, out: File, hiRes: Boolean): Fetched? {
+ /** Runs the resolver and saves the audio into [out]; null when nothing matched. */
+ private suspend fun resolveAndFetch(r: Request, meta: Meta, out: File, hiRes: Boolean, small: Boolean = false): Fetched? {
val resolved = LosslessSource.resolve(
Graph.app, r.trackId,
LosslessSource.TrackInfo(meta.title, meta.artist, (meta.durationMs / 1000).toInt(), meta.isrc.orEmpty()),
preferHiRes = hiRes,
+ small = small,
)
if (resolved !is LosslessSource.Success) return null
val track = resolved.track
@@ -332,6 +343,10 @@ object OfflineDownloader {
else -> fetchWithProgress(r.trackId, track.url, out)
}
if (!ok || out.length() < 10_000) return null
+ if (track.aac) {
+ Log.i(TAG, "${meta.title}: saved ${track.provider}")
+ return Fetched(track.provider, resolved.isrcMatched, aac = true)
+ }
checkFlacHeader(out, meta, track)
Log.i(TAG, "${meta.title}: saved lossless FLAC from ${track.provider} (${track.quality}-bit)")
return Fetched("${track.provider} ${track.quality}-bit", resolved.isrcMatched)
diff --git a/base/app/src/main/java/com/music/spotui/lossless/DashFlacRemux.kt b/base/app/src/main/java/com/music/spotui/lossless/DashFlacRemux.kt
index 95e389d3..7c29866e 100644
--- a/base/app/src/main/java/com/music/spotui/lossless/DashFlacRemux.kt
+++ b/base/app/src/main/java/com/music/spotui/lossless/DashFlacRemux.kt
@@ -18,6 +18,7 @@ import android.util.Log
internal object DashFlacRemux {
private const val TAG = "DashFlacRemux"
private const val UA = "SpotiFLAC"
+ private const val PARALLEL_SEGMENTS = 3
/** [trackUrl] is either a `data:application/dash+xml;base64,…` URI or the MPD text itself. */
fun download(streamUrl: String, outFile: java.io.File): Boolean = runCatching {
@@ -39,9 +40,16 @@ internal object DashFlacRemux {
out.write((streamInfo.size ushr 8) and 0xFF)
out.write(streamInfo.size and 0xFF)
out.write(streamInfo)
- for (n in startNumber until startNumber + segCount) {
- val seg = httpBytes(mediaTmpl.replace("\$Number$", n.toString())) ?: return false
- writeMdatPayloads(seg, out)
+ // Three segments in flight at once (SpotiFLAC's transfer policy), written in order.
+ val pool = java.util.concurrent.Executors.newFixedThreadPool(PARALLEL_SEGMENTS)
+ try {
+ val numbers = (startNumber until startNumber + segCount).toList()
+ for (batch in numbers.chunked(PARALLEL_SEGMENTS * 2)) {
+ val parts = batch.map { n -> pool.submit<ByteArray?> { httpBytes(mediaTmpl.replace("\$Number$", n.toString())) } }
+ for (p in parts) writeMdatPayloads(p.get() ?: return false, out)
+ }
+ } finally {
+ pool.shutdownNow()
}
}
Log.d(TAG, "tidal DASH remuxed to FLAC ($segCount segments)")
diff --git a/base/app/src/main/java/com/music/spotui/lossless/LosslessSource.kt b/base/app/src/main/java/com/music/spotui/lossless/LosslessSource.kt
index 37fd4bb7..963f72fc 100644
--- a/base/app/src/main/java/com/music/spotui/lossless/LosslessSource.kt
+++ b/base/app/src/main/java/com/music/spotui/lossless/LosslessSource.kt
@@ -46,6 +46,8 @@ object LosslessSource {
val provider: String,
/** Bit depth the source claims (the STREAMINFO after a remux tells the truth). */
val quality: Int,
+ /** An AAC file served as it is (Tidal's LOW / HIGH), not a FLAC. */
+ val aac: Boolean = false,
)
sealed interface Result
@@ -64,6 +66,8 @@ object LosslessSource {
spotifyId: String,
info: TrackInfo = TrackInfo(),
preferHiRes: Boolean = false,
+ /** The "smallest" quality: Tidal's own AAC first, as SpotiFLAC asks for LOW / HIGH. */
+ small: Boolean = false,
): Result = withContext(Dispatchers.IO) {
// Qobuz's own catalogue search finds the ISRC quickly and does not depend on the
// community backends; the Tidal id does (their search), and they are often down.
@@ -73,7 +77,10 @@ object LosslessSource {
// session, as SpotiFLAC Mobile's tidal-web extension does: the most reliable source.
// Tidal's own public API finds the exact ISRC.
if (verified(ZarzSession.Ext.TIDAL)) {
- tidalIdForIsrc(info.isrc)?.let { id -> zarzTidal(context, id, info, preferHiRes)?.let { return@withContext it } }
+ tidalIdForIsrc(info.isrc)?.let { id ->
+ if (small) zarzTidalAac(context, id)?.let { return@withContext it }
+ zarzTidal(context, id, info, preferHiRes)?.let { return@withContext it }
+ }
}
// 2. Qobuz the same way (qobuz-web), found by ISRC in Qobuz's own catalogue.
val qobuz = qobuzIdForIsrc(info.isrc)
@@ -153,6 +160,38 @@ object LosslessSource {
return null
}
+ /**
+ * Tidal's own AAC (LOW = 96 kbit/s, else HIGH = 320), one file as Tidal serves it:
+ * the small download, without a FLAC to fetch and re-encode on the phone.
+ */
+ private fun zarzTidalAac(context: Context, tidalId: String): Result? {
+ for (q in listOf("LOW", "HIGH")) {
+ try {
+ val ticket = ZarzSession.ticket(context, ZarzSession.Ext.TIDAL, "tid", "track", tidalId)
+ val o = ZarzSession.signedJson(context, ZarzSession.Ext.TIDAL, "POST", "/dl/tid",
+ JSONObject().put("id", tidalId).put("quality", q), mapOf("X-Zarz-Ticket" to ticket))
+ val data = o.optJSONObject("data") ?: continue
+ if (data.optString("assetPresentation").equals("PREVIEW", true)) continue
+ val url = aacManifestUrl(data.optString("manifest")) ?: continue
+ return Success(LosslessFile(url, "", "Tidal AAC ${if (q == "LOW") 96 else 320}", 16, aac = true), isrcMatched = true)
+ } catch (e: ZarzSession.VerifyRequired) {
+ com.music.spotui.data.preferences.clearSpotiflacSession(context, ZarzSession.Ext.TIDAL.appVersion)
+ return null
+ } catch (e: Exception) {
+ Log.w(TAG, "zarz tidal aac $q: ${e.message}")
+ }
+ }
+ return null
+ }
+
+ /** The one file of a Tidal AAC manifest (BTS JSON, mimeType audio/mp4); null for anything else. */
+ internal fun aacManifestUrl(manifestB64: String): String? = runCatching {
+ val m = JSONObject(String(java.util.Base64.getMimeDecoder().decode(manifestB64), Charsets.UTF_8))
+ val urls = m.optJSONArray("urls") ?: return null
+ if (urls.length() != 1 || !m.optString("mimeType").contains("mp4")) return null
+ urls.optString(0).takeIf { it.startsWith("http") }
+ }.getOrNull()
+
/** Tidal's public API: the track carrying this exact ISRC (the web player's own token). */
internal fun tidalIdForIsrc(isrc: String): String? {
if (isrc.isBlank()) return null
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/SpotiflacScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/SpotiflacScreen.kt
index d3e175ea..df750d8e 100644
--- a/base/app/src/main/java/com/music/spotui/ui/screens/SpotiflacScreen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/SpotiflacScreen.kt
@@ -60,7 +60,8 @@ fun SpotiflacScreen(onClose: () -> Unit) {
val scope = rememberCoroutineScope()
var attempt by remember { mutableStateOf(0) }
// One session per download server (Tidal, then Qobuz); verified once none is missing.
- fun missing() = com.music.spotui.lossless.ZarzSession.Ext.entries
+ // Tidal only: the best source, and a single page to solve (Qobuz would need its own).
+ fun missing() = listOf(com.music.spotui.lossless.ZarzSession.Ext.TIDAL)
.firstOrNull { com.music.spotui.data.preferences.getSpotiflacSession(context, it.appVersion) == null }
var ext by remember { mutableStateOf(missing()) }
var verified by remember { mutableStateOf(ext == null) }
diff --git a/base/app/src/test/java/com/music/spotui/lossless/LosslessMatchTest.kt b/base/app/src/test/java/com/music/spotui/lossless/LosslessMatchTest.kt
index b5687293..0a26003d 100644
--- a/base/app/src/test/java/com/music/spotui/lossless/LosslessMatchTest.kt
+++ b/base/app/src/test/java/com/music/spotui/lossless/LosslessMatchTest.kt
@@ -84,4 +84,13 @@ class FlacDurationTest {
// Spotify gave no ISRC: nothing can match it.
assertFalse(LosslessSource.isrcMatches("USUM71703861", ""))
}
+
+ @Test
+ fun readsTheOneFileOfAnAacManifest() {
+ fun b64(s: String) = java.util.Base64.getEncoder().encodeToString(s.toByteArray())
+ assertEquals("https://cdn/x.mp4", LosslessSource.aacManifestUrl(b64("""{"mimeType":"audio/mp4","codecs":"mp4a.40.5","urls":["https://cdn/x.mp4"]}""")))
+ // A FLAC or a DASH manifest is not the small AAC file.
+ assertNull(LosslessSource.aacManifestUrl(b64("""{"mimeType":"audio/flac","urls":["https://cdn/x.flac"]}""")))
+ assertNull(LosslessSource.aacManifestUrl(b64("<MPD></MPD>")))
+ }
}