Skip to content

Native Android client for Spotify, built with Jetpack Compose

Spotify lossless for Premium: a Lossless streaming quality, through the Web Player's own SDK

kota-zo74bedcdac4b9
diff --git a/base/app/src/main/java/com/music/spotui/data/preferences/QualityPref.kt b/base/app/src/main/java/com/music/spotui/data/preferences/QualityPref.kt
index b782f4de..9c65da00 100644
--- a/base/app/src/main/java/com/music/spotui/data/preferences/QualityPref.kt
+++ b/base/app/src/main/java/com/music/spotui/data/preferences/QualityPref.kt
@@ -20,7 +20,9 @@ private const val KEY_CANVAS_WIFI = "canvas_wifi_only"
enum class StreamingQuality(val level: String) {
AUTO("auto"), LOW("low"), NORMAL("normal"), HIGH("high"),
/** 256 kbit/s: the Web Player gives it to Premium accounts only (offered then, see StreamingQualityPicker). */
- VERY_HIGH("very_high");
+ VERY_HIGH("very_high"),
+ /** Spotify lossless (FLAC), Premium: declared to the Web Player when chosen (see applyStreamingQuality). */
+ LOSSLESS("lossless");
companion object {
fun of(level: String?): StreamingQuality = entries.firstOrNull { it.level == level } ?: AUTO
@@ -62,6 +64,9 @@ fun applyStreamingQuality(c: Context) {
val runtime = app.myspoti.host.android.MyspotiRuntime
if (!runtime.isStarted) return
val q = getStreamingQuality(c, cellular = com.music.spotui.data.DataSaver.metered)
+ // Lossless chosen for either network: the Web Player is told it may play it (a page reload
+ // when that changes); the level of the network in use then picks FLAC or not.
+ runtime.setLossless(getStreamingQuality(c, false) == StreamingQuality.LOSSLESS || getStreamingQuality(c, true) == StreamingQuality.LOSSLESS)
runtime.scope.launch { runtime.spotify.player.setAudioQuality(q.level) }
}
diff --git a/base/app/src/main/java/com/music/spotui/ui/components/PlayerSheets.kt b/base/app/src/main/java/com/music/spotui/ui/components/PlayerSheets.kt
index effc3e5f..a9638d4b 100644
--- a/base/app/src/main/java/com/music/spotui/ui/components/PlayerSheets.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/components/PlayerSheets.kt
@@ -316,6 +316,7 @@ internal fun streamingLabel(q: com.music.spotui.data.preferences.StreamingQualit
com.music.spotui.data.preferences.StreamingQuality.NORMAL -> R.string.quality_streaming_normal
com.music.spotui.data.preferences.StreamingQuality.HIGH -> R.string.quality_streaming_high
com.music.spotui.data.preferences.StreamingQuality.VERY_HIGH -> R.string.quality_streaming_very_high
+ com.music.spotui.data.preferences.StreamingQuality.LOSSLESS -> R.string.quality_streaming_lossless
}
/** The sound quality page: what plays now (codec and bitrate, the downloaded file, or what an extension announced), and the setting. */
diff --git a/base/app/src/main/java/com/music/spotui/ui/components/QualityPickers.kt b/base/app/src/main/java/com/music/spotui/ui/components/QualityPickers.kt
index 6ec65119..23d91124 100644
--- a/base/app/src/main/java/com/music/spotui/ui/components/QualityPickers.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/components/QualityPickers.kt
@@ -64,6 +64,8 @@ fun StreamingQualityPicker(modifier: Modifier = Modifier, cellular: Boolean = fa
Option(StreamingQuality.HIGH, R.string.quality_streaming_high, R.string.quality_streaming_high_detail),
Option(StreamingQuality.VERY_HIGH, R.string.quality_streaming_very_high, R.string.quality_streaming_very_high_detail)
.takeIf { premium == true || current == StreamingQuality.VERY_HIGH },
+ Option(StreamingQuality.LOSSLESS, R.string.quality_streaming_lossless, R.string.quality_streaming_lossless_detail)
+ .takeIf { premium == true || current == StreamingQuality.LOSSLESS },
),
selected = current,
onSelect = { current = it; setStreamingQuality(ctx, it, cellular) },
diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveSettingsScreen.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveSettingsScreen.kt
index 6af725fe..bc0036b6 100644
--- a/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveSettingsScreen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveSettingsScreen.kt
@@ -82,6 +82,7 @@ private val StreamingChoices = listOf(
Triple(StreamingQuality.HIGH, R.string.quality_streaming_high, R.string.quality_streaming_high_detail),
// Offered with a Premium account only (see the page below).
Triple(StreamingQuality.VERY_HIGH, R.string.quality_streaming_very_high, R.string.quality_streaming_very_high_detail),
+ Triple(StreamingQuality.LOSSLESS, R.string.quality_streaming_lossless, R.string.quality_streaming_lossless_detail),
)
private val DownloadChoices = listOf(
@@ -419,7 +420,8 @@ private fun StreamingPage(cellular: Boolean, back: () -> Unit) {
var current by remember(cellular) { mutableStateOf(getStreamingQuality(ctx, cellular)) }
// Very high is the Web Player's Premium level: offered with a Premium account, kept while chosen.
val premium by app.myspoti.spotify.AccountPlan.premium.collectAsState()
- val choices = StreamingChoices.filter { it.first != StreamingQuality.VERY_HIGH || premium == true || current == StreamingQuality.VERY_HIGH }
+ val premiumOnly = setOf(StreamingQuality.VERY_HIGH, StreamingQuality.LOSSLESS)
+ val choices = StreamingChoices.filter { it.first !in premiumOnly || premium == true || current == it.first }
ImmersivePage(
title = stringResource(if (cellular) R.string.quality_streaming_cell_title else R.string.quality_streaming_wifi_title),
onBack = back,
diff --git a/base/app/src/main/res/values-de/myspoti_strings.xml b/base/app/src/main/res/values-de/myspoti_strings.xml
index cc562099..2bb0b51d 100644
--- a/base/app/src/main/res/values-de/myspoti_strings.xml
+++ b/base/app/src/main/res/values-de/myspoti_strings.xml
@@ -771,4 +771,6 @@
<string name="settings_release_notify_detail">Eine Benachrichtigung, wenn ein Künstler, dem du folgst, etwas veröffentlicht; alle paar Stunden geprüft, solange Myspoti läuft</string>
<string name="quality_streaming_very_high">Sehr hoch</string>
<string name="quality_streaming_very_high_detail">256 kbit/s, nur für Premium-Konten</string>
+ <string name="quality_streaming_lossless">Verlustfrei</string>
+ <string name="quality_streaming_lossless_detail">FLAC bis 24 Bit/44,1 kHz, Premium; Spotify liefert es nur an Handys mit Hardware-DRM, sonst wird Sehr hoch gespielt</string>
</resources>
diff --git a/base/app/src/main/res/values-el/myspoti_strings.xml b/base/app/src/main/res/values-el/myspoti_strings.xml
index a5173a7e..7fdf8acf 100644
--- a/base/app/src/main/res/values-el/myspoti_strings.xml
+++ b/base/app/src/main/res/values-el/myspoti_strings.xml
@@ -771,4 +771,6 @@
<string name="settings_release_notify_detail">Μια ειδοποίηση όταν ένας καλλιτέχνης που ακολουθείς κυκλοφορεί κάτι, με έλεγχο κάθε λίγες ώρες όσο τρέχει το Myspoti</string>
<string name="quality_streaming_very_high">Πολύ υψηλή</string>
<string name="quality_streaming_very_high_detail">256 kbit/s, μόνο για λογαριασμούς Premium</string>
+ <string name="quality_streaming_lossless">Χωρίς απώλειες</string>
+ <string name="quality_streaming_lossless_detail">FLAC έως 24 bit/44,1 kHz, Premium· το Spotify το δίνει μόνο σε τηλέφωνα με DRM υλικού, αλλιώς παίζει Πολύ υψηλή</string>
</resources>
diff --git a/base/app/src/main/res/values-es/myspoti_strings.xml b/base/app/src/main/res/values-es/myspoti_strings.xml
index df470f56..0bf8e00c 100644
--- a/base/app/src/main/res/values-es/myspoti_strings.xml
+++ b/base/app/src/main/res/values-es/myspoti_strings.xml
@@ -771,4 +771,6 @@
<string name="settings_release_notify_detail">Una notificación cuando un artista que sigues publica algo, comprobado cada pocas horas mientras Myspoti está abierto</string>
<string name="quality_streaming_very_high">Muy alta</string>
<string name="quality_streaming_very_high_detail">256 kbit/s, solo cuentas Premium</string>
+ <string name="quality_streaming_lossless">Sin pérdida</string>
+ <string name="quality_streaming_lossless_detail">FLAC hasta 24 bits/44,1 kHz, Premium; Spotify solo lo da a móviles con DRM por hardware, si no suena Muy alta</string>
</resources>
diff --git a/base/app/src/main/res/values-fr/myspoti_strings.xml b/base/app/src/main/res/values-fr/myspoti_strings.xml
index 7f91efc4..8e462169 100644
--- a/base/app/src/main/res/values-fr/myspoti_strings.xml
+++ b/base/app/src/main/res/values-fr/myspoti_strings.xml
@@ -776,4 +776,6 @@
<string name="settings_release_notify_detail">Une notification quand un artiste que tu suis sort quelque chose, vérifié toutes les quelques heures pendant que Myspoti tourne</string>
<string name="quality_streaming_very_high">Très élevée</string>
<string name="quality_streaming_very_high_detail">256 kbit/s, comptes Premium uniquement</string>
+ <string name="quality_streaming_lossless">Sans perte</string>
+ <string name="quality_streaming_lossless_detail">FLAC jusqu’à 24 bits/44,1 kHz, Premium ; Spotify ne le donne qu’aux téléphones avec un DRM matériel, sinon Très élevée est jouée</string>
</resources>
diff --git a/base/app/src/main/res/values-it/myspoti_strings.xml b/base/app/src/main/res/values-it/myspoti_strings.xml
index 29484f1f..b1944bb7 100644
--- a/base/app/src/main/res/values-it/myspoti_strings.xml
+++ b/base/app/src/main/res/values-it/myspoti_strings.xml
@@ -771,4 +771,6 @@
<string name="settings_release_notify_detail">Una notifica quando un artista che segui pubblica qualcosa, controllato ogni poche ore mentre Myspoti è attivo</string>
<string name="quality_streaming_very_high">Molto alta</string>
<string name="quality_streaming_very_high_detail">256 kbit/s, solo account Premium</string>
+ <string name="quality_streaming_lossless">Lossless</string>
+ <string name="quality_streaming_lossless_detail">FLAC fino a 24 bit/44,1 kHz, Premium; Spotify lo dà solo ai telefoni con DRM hardware, altrimenti suona Molto alta</string>
</resources>
diff --git a/base/app/src/main/res/values-pl/myspoti_strings.xml b/base/app/src/main/res/values-pl/myspoti_strings.xml
index f75130c0..c9e194cd 100644
--- a/base/app/src/main/res/values-pl/myspoti_strings.xml
+++ b/base/app/src/main/res/values-pl/myspoti_strings.xml
@@ -786,4 +786,6 @@
<string name="settings_release_notify_detail">Powiadomienie, gdy obserwowany artysta coś wyda; sprawdzane co kilka godzin, gdy Myspoti działa</string>
<string name="quality_streaming_very_high">Bardzo wysoka</string>
<string name="quality_streaming_very_high_detail">256 kbit/s, tylko konta Premium</string>
+ <string name="quality_streaming_lossless">Bezstratna</string>
+ <string name="quality_streaming_lossless_detail">FLAC do 24 bitów/44,1 kHz, Premium; Spotify daje ją tylko telefonom ze sprzętowym DRM, inaczej gra Bardzo wysoka</string>
</resources>
diff --git a/base/app/src/main/res/values-pt-rBR/myspoti_strings.xml b/base/app/src/main/res/values-pt-rBR/myspoti_strings.xml
index 069ca300..b68e3a53 100644
--- a/base/app/src/main/res/values-pt-rBR/myspoti_strings.xml
+++ b/base/app/src/main/res/values-pt-rBR/myspoti_strings.xml
@@ -750,4 +750,6 @@
<string name="settings_release_notify_detail">Uma notificação quando um artista que você segue lança algo, verificado a cada poucas horas enquanto o Myspoti está aberto</string>
<string name="quality_streaming_very_high">Muito alta</string>
<string name="quality_streaming_very_high_detail">256 kbit/s, apenas contas Premium</string>
+ <string name="quality_streaming_lossless">Sem perdas</string>
+ <string name="quality_streaming_lossless_detail">FLAC até 24 bits/44,1 kHz, Premium; o Spotify só libera para celulares com DRM por hardware, senão toca Muito alta</string>
</resources>
diff --git a/base/app/src/main/res/values-pt-rPT/myspoti_strings.xml b/base/app/src/main/res/values-pt-rPT/myspoti_strings.xml
index ead45bb7..ef9a916e 100644
--- a/base/app/src/main/res/values-pt-rPT/myspoti_strings.xml
+++ b/base/app/src/main/res/values-pt-rPT/myspoti_strings.xml
@@ -717,4 +717,6 @@
<string name="settings_release_notify_detail">Uma notificação quando um artista que segues lança algo, verificado a cada poucas horas enquanto o Myspoti está aberto</string>
<string name="quality_streaming_very_high">Muito alta</string>
<string name="quality_streaming_very_high_detail">256 kbit/s, só contas Premium</string>
+ <string name="quality_streaming_lossless">Sem perdas</string>
+ <string name="quality_streaming_lossless_detail">FLAC até 24 bits/44,1 kHz, Premium; o Spotify só o dá a telemóveis com DRM por hardware, senão toca Muito alta</string>
</resources>
diff --git a/base/app/src/main/res/values-pt/myspoti_strings.xml b/base/app/src/main/res/values-pt/myspoti_strings.xml
index 7beb5a30..59fd6adf 100644
--- a/base/app/src/main/res/values-pt/myspoti_strings.xml
+++ b/base/app/src/main/res/values-pt/myspoti_strings.xml
@@ -771,4 +771,6 @@
<string name="settings_release_notify_detail">Uma notificação quando um artista que segues lança algo, verificado a cada poucas horas enquanto o Myspoti está aberto</string>
<string name="quality_streaming_very_high">Muito alta</string>
<string name="quality_streaming_very_high_detail">256 kbit/s, só contas Premium</string>
+ <string name="quality_streaming_lossless">Sem perdas</string>
+ <string name="quality_streaming_lossless_detail">FLAC até 24 bits/44,1 kHz, Premium; o Spotify só o dá a telemóveis com DRM por hardware, senão toca Muito alta</string>
</resources>
diff --git a/base/app/src/main/res/values-ru/myspoti_strings.xml b/base/app/src/main/res/values-ru/myspoti_strings.xml
index bc3f1001..f61b3a76 100644
--- a/base/app/src/main/res/values-ru/myspoti_strings.xml
+++ b/base/app/src/main/res/values-ru/myspoti_strings.xml
@@ -786,4 +786,6 @@
<string name="settings_release_notify_detail">Уведомление, когда артист, на которого вы подписаны, что-то выпускает; проверка каждые несколько часов, пока Myspoti работает</string>
<string name="quality_streaming_very_high">Очень высокое</string>
<string name="quality_streaming_very_high_detail">256 кбит/с, только для Premium</string>
+ <string name="quality_streaming_lossless">Без потерь</string>
+ <string name="quality_streaming_lossless_detail">FLAC до 24 бит/44,1 кГц, Premium; Spotify даёт его только телефонам с аппаратным DRM, иначе играет «Очень высокое»</string>
</resources>
diff --git a/base/app/src/main/res/values-zh/myspoti_strings.xml b/base/app/src/main/res/values-zh/myspoti_strings.xml
index aadbcadc..785575ba 100644
--- a/base/app/src/main/res/values-zh/myspoti_strings.xml
+++ b/base/app/src/main/res/values-zh/myspoti_strings.xml
@@ -771,4 +771,6 @@
<string name="settings_release_notify_detail">你关注的艺人发布新作品时发送通知,Myspoti 运行时每隔几小时检查一次</string>
<string name="quality_streaming_very_high">极高</string>
<string name="quality_streaming_very_high_detail">256 kbit/s,仅限 Premium 账户</string>
+ <string name="quality_streaming_lossless">无损</string>
+ <string name="quality_streaming_lossless_detail">FLAC 最高 24 位/44.1 kHz,Premium;Spotify 只向具备硬件 DRM 的手机提供,否则播放“极高”</string>
</resources>
diff --git a/base/app/src/main/res/values/myspoti_strings.xml b/base/app/src/main/res/values/myspoti_strings.xml
index 188156b8..33ab7397 100644
--- a/base/app/src/main/res/values/myspoti_strings.xml
+++ b/base/app/src/main/res/values/myspoti_strings.xml
@@ -778,4 +778,6 @@
<string name="settings_release_notify_detail">A notification when an artist you follow releases something, checked every few hours while Myspoti runs</string>
<string name="quality_streaming_very_high">Very high</string>
<string name="quality_streaming_very_high_detail">256 kbit/s, Premium accounts only</string>
+ <string name="quality_streaming_lossless">Lossless</string>
+ <string name="quality_streaming_lossless_detail">FLAC up to 24-bit/44.1 kHz, Premium; Spotify gives it only to phones with hardware DRM, otherwise Very high plays</string>
</resources>
diff --git a/base/host-android/src/main/kotlin/app/myspoti/host/android/MyspotiRuntime.kt b/base/host-android/src/main/kotlin/app/myspoti/host/android/MyspotiRuntime.kt
index d4e6f2c3..1341ecae 100644
--- a/base/host-android/src/main/kotlin/app/myspoti/host/android/MyspotiRuntime.kt
+++ b/base/host-android/src/main/kotlin/app/myspoti/host/android/MyspotiRuntime.kt
@@ -48,6 +48,9 @@ object MyspotiRuntime {
.build()
}
+ /** Spotify lossless declared to the Web Player or not (see [WebPlayerHost.setLossless]). */
+ fun setLossless(on: Boolean) { if (::host.isInitialized) host.setLossless(on) }
+
/** The phone moved to another network: the API's idle connections belong to the old one. Not on the main thread. */
fun resetApiConnections() { if (::host.isInitialized) apiHttp.connectionPool.evictAll() }
diff --git a/base/host-android/src/main/kotlin/app/myspoti/host/android/WebPlayerHost.kt b/base/host-android/src/main/kotlin/app/myspoti/host/android/WebPlayerHost.kt
index 4ff185a7..9c18193b 100644
--- a/base/host-android/src/main/kotlin/app/myspoti/host/android/WebPlayerHost.kt
+++ b/base/host-android/src/main/kotlin/app/myspoti/host/android/WebPlayerHost.kt
@@ -276,6 +276,8 @@ class WebPlayerHost(private val context: Context) : BridgeHost {
it.onDeviceRegistered = { drmAsked = true; main.removeCallbacks(drmWatch) }
it.install()
}
+ // Spotify lossless, when chosen: declared before the page's first script (see setLossless).
+ losslessScript = if (roots.getBoolean(LOSSLESS_KEY, false)) declareLossless(this) else null
val webView = this
cookies().apply {
setAcceptCookie(true)
@@ -554,6 +556,36 @@ class WebPlayerHost(private val context: Context) : BridgeHost {
*/
private fun playerRoot(): String = roots.getString(ROOT_KEY, null)?.takeIf { PLAYER_ROOT.matches(it) } ?: PLAYER_URL
+ /**
+ * Spotify lossless (FLAC, up to 24-bit/44.1 kHz) for a Premium account. The Web Player's own
+ * playback SDK plays it (format MP4_FLAC, Widevine-protected, decrypted by the phone's DRM with
+ * Spotify's licence) when its client says `lossless_playback`, which open.spotify.com never
+ * does (it passes only video_playback). The script below says it before the page's first
+ * script: the property is read from objects that do not set it, so a getter on Object's
+ * prototype answers true, whatever names Spotify's next build minifies to. Spotify still
+ * decides: it sends FLAC files only to an eligible account and a device whose Widevine is
+ * hardware-backed (the SDK's own rule), and the page plays AAC otherwise. A change reloads
+ * the page, as the device registers its capabilities when it loads.
+ */
+ fun setLossless(on: Boolean) = main.post {
+ if (roots.getBoolean(LOSSLESS_KEY, false) == on) return@post
+ roots.edit().putBoolean(LOSSLESS_KEY, on).apply()
+ losslessScript?.remove(); losslessScript = null
+ if (on) losslessScript = declareLossless(view)
+ Logbook.log("lossless ${if (on) "declared" else "withdrawn"}: the page reloads to register the device again")
+ if (pageStarts > 0) view.loadUrl(playerRoot())
+ }
+
+ private var losslessScript: androidx.webkit.ScriptHandler? = null
+
+ private fun declareLossless(v: WebView): androidx.webkit.ScriptHandler? {
+ if (!androidx.webkit.WebViewFeature.isFeatureSupported(androidx.webkit.WebViewFeature.DOCUMENT_START_SCRIPT)) {
+ Logbook.log("lossless: this WebView runs no document-start script, not declared")
+ return null
+ }
+ return androidx.webkit.WebViewCompat.addDocumentStartJavaScript(v, LOSSLESS_SCRIPT, setOf("https://open.spotify.com"))
+ }
+
/** The player's own URL, not the page's current one: the bridge parks the page on an empty route. */
fun reload() = main.post {
// A page whose player never started is not helped by loading it again in the same renderer.
@@ -992,3 +1024,23 @@ private class AwakeWebView(context: Context) : WebView(context) {
super.onDetachedFromWindow()
}
}
+
+private const val LOSSLESS_KEY = "lossless"
+
+/**
+ * Says `lossless_playback` to the Web Player's playback SDK (see [WebPlayerHost.setLossless]): a
+ * getter on Object's prototype, not enumerable (no `for in`, no JSON), that an object setting the
+ * property itself replaces with its own value.
+ */
+private const val LOSSLESS_SCRIPT = """
+(function () {
+ try {
+ if (Object.prototype.hasOwnProperty('lossless_playback')) return;
+ Object.defineProperty(Object.prototype, 'lossless_playback', {
+ configurable: true,
+ get: function () { return true; },
+ set: function (v) { Object.defineProperty(this, 'lossless_playback', { value: v, writable: true, enumerable: true, configurable: true }); }
+ });
+ } catch (e) {}
+})();
+"""