Skip to content

Unofficial YouTube Music / Spotify Premium client for Android, built in Liquid Glass. Audio effects, Spotify Connect, listening history, 8 languages. Rust core on librespot.

Choose the audio quality in settings

Lelonioaa314d50527c
diff --git a/app/src/main/java/dev/lelonio/square/SquareApplication.kt b/app/src/main/java/dev/lelonio/square/SquareApplication.kt
index c2a2c27..5d134e1 100644
--- a/app/src/main/java/dev/lelonio/square/SquareApplication.kt
+++ b/app/src/main/java/dev/lelonio/square/SquareApplication.kt
@@ -28,6 +28,11 @@ class SquareApplication : Application() {
val playlistOrder: PlaylistOrderStore by lazy { PlaylistOrderStore(this) }
val preferences: PreferencesStore by lazy { PreferencesStore(this) }
+ /** Which file the engine asks Spotify for. */
+ val quality: dev.lelonio.square.data.QualityStore by lazy {
+ dev.lelonio.square.data.QualityStore(this)
+ }
+
/** What language the app is read in, and what the engine asks Spotify for. */
val language: LanguageStore by lazy { LanguageStore(this) }
diff --git a/app/src/main/java/dev/lelonio/square/data/QualityStore.kt b/app/src/main/java/dev/lelonio/square/data/QualityStore.kt
new file mode 100644
index 0000000..6ef6938
--- /dev/null
+++ b/app/src/main/java/dev/lelonio/square/data/QualityStore.kt
@@ -0,0 +1,74 @@
+package dev.lelonio.square.data
+
+import android.content.Context
+import android.net.ConnectivityManager
+import android.net.NetworkCapabilities
+import androidx.annotation.StringRes
+import dev.lelonio.square.R
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+
+/**
+ * Which file the engine asks Spotify for.
+ *
+ * The three fixed steps are the ones the account is actually offered: Ogg
+ * Vorbis at 320, 160 and 96 kbps. Nothing higher exists for this client, so
+ * there is no "lossless" here to choose.
+ */
+enum class Quality(val key: String, @StringRes val label: Int, val kbps: Int) {
+ /** Full quality on wi-fi, the middle step on a metered connection. */
+ Auto("auto", R.string.quality_auto, 0),
+ High("high", R.string.quality_high, 320),
+ Medium("medium", R.string.quality_medium, 160),
+ Low("low", R.string.quality_low, 96),
+}
+
+class QualityStore(context: Context) {
+
+ private val app = context.applicationContext
+ private val prefs = app.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE)
+
+ private val _quality = MutableStateFlow(
+ Quality.entries.firstOrNull { it.key == prefs.getString(KEY_QUALITY, null) }
+ ?: Quality.Auto,
+ )
+ val quality: StateFlow<Quality> = _quality.asStateFlow()
+
+ fun set(quality: Quality) {
+ _quality.value = quality
+ prefs.edit().putString(KEY_QUALITY, quality.key).apply()
+ }
+
+ /**
+ * The bitrate to start the engine with, resolving [Quality.Auto].
+ *
+ * Read when an engine is built rather than watched: the player owns its
+ * configuration for its whole life, so a connection that changes from wi-fi
+ * to mobile mid-track keeps the bitrate it started on until the next time
+ * the engine is built.
+ */
+ fun bitrateKbps(): Int {
+ val chosen = _quality.value
+ if (chosen != Quality.Auto) return chosen.kbps
+ return if (isMetered()) Quality.Medium.kbps else Quality.High.kbps
+ }
+
+ /**
+ * Whether the connection is one the user pays by the megabyte.
+ *
+ * The system's own answer, not a guess from the transport: a phone tethering
+ * over wi-fi is metered, and an unlimited mobile plan the user has marked as
+ * such is not.
+ */
+ private fun isMetered(): Boolean {
+ val manager = app.getSystemService(ConnectivityManager::class.java) ?: return false
+ val capabilities = manager.getNetworkCapabilities(manager.activeNetwork) ?: return false
+ return !capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)
+ }
+
+ private companion object {
+ const val FILE_NAME = "square_quality"
+ const val KEY_QUALITY = "quality"
+ }
+}
diff --git a/app/src/main/java/dev/lelonio/square/nativecore/NativeBridge.kt b/app/src/main/java/dev/lelonio/square/nativecore/NativeBridge.kt
index 50fcf13..72ba2db 100644
--- a/app/src/main/java/dev/lelonio/square/nativecore/NativeBridge.kt
+++ b/app/src/main/java/dev/lelonio/square/nativecore/NativeBridge.kt
@@ -66,6 +66,14 @@ object NativeBridge {
cacheDir: String,
/** What language Spotify should answer in, as a bare tag: `it`, `en`. */
language: String,
+ /**
+ * Which file to ask for: 96, 160 or 320 kbps.
+ *
+ * Fixed for the life of the engine. The player reads it when a track
+ * loads but owns its configuration until it is dropped, so changing the
+ * setting means starting a new engine.
+ */
+ bitrateKbps: Int,
listener: NativeEvents,
) = nativeStart(
clientId,
@@ -74,6 +82,7 @@ object NativeBridge {
credentialsDir,
cacheDir,
language,
+ bitrateKbps,
listener,
)
@@ -172,6 +181,7 @@ object NativeBridge {
credentialsDir: String,
cacheDir: String,
language: String,
+ bitrateKbps: Int,
listener: NativeEvents,
)
diff --git a/app/src/main/java/dev/lelonio/square/playback/PlaybackService.kt b/app/src/main/java/dev/lelonio/square/playback/PlaybackService.kt
index 909f05c..df87730 100644
--- a/app/src/main/java/dev/lelonio/square/playback/PlaybackService.kt
+++ b/app/src/main/java/dev/lelonio/square/playback/PlaybackService.kt
@@ -13,6 +13,7 @@ import dev.lelonio.square.nativecore.NativeBridge
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
+import kotlinx.coroutines.flow.drop
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
@@ -47,12 +48,14 @@ class PlaybackService : MediaLibraryService() {
private val audioOutput = AudioOutput()
private lateinit var playbackStore: PlaybackStore
+ private lateinit var quality: dev.lelonio.square.data.QualityStore
private var saveJob: Job? = null
override fun onCreate() {
super.onCreate()
tokens = TokenStore(this)
playbackStore = PlaybackStore(this)
+ quality = (application as dev.lelonio.square.SquareApplication).quality
queue = PlayQueue()
player = LibrespotPlayer(
this,
@@ -113,9 +116,41 @@ class PlaybackService : MediaLibraryService() {
AudioEffects.reverb.collect(audioOutput::setReverbAmount)
}
+ // The bitrate is fixed when the player is built, so a change means a new
+ // engine. Watched here rather than acted on from the settings screen:
+ // the service owns the engine's lifetime, and it is the only place that
+ // can put playback back afterwards.
+ scope.launch {
+ quality.quality.drop(1).collect { restartForQuality() }
+ }
+
connectEngine()
}
+ /**
+ * Rebuilds the engine so a new bitrate takes effect.
+ *
+ * librespot reads the bitrate when a track loads but the player owns its
+ * configuration until it is dropped, so there is nothing to set: the
+ * session is torn down and started again. The queue and position are saved
+ * first and put back after, which is the same path a cold start takes.
+ */
+ private fun restartForQuality() {
+ val wasPlaying = player.playWhenReady
+ runCatching { savePlayback() }
+
+ runCatching { NativeBridge.shutdown() }
+ engineStarted = false
+ player.clearForRestart()
+
+ scope.launch {
+ connectEngine().join()
+ // restoreQueue, run by connectEngine, puts the queue back at the
+ // position that was just saved, paused.
+ if (wasPlaying && player.mediaItemCount > 0) player.play()
+ }
+ }
+
/**
* Re-runs [connectEngine] on demand.
*
@@ -162,6 +197,7 @@ class PlaybackService : MediaLibraryService() {
// generated playlists carry the language in the cover's
// URL, so the tiles came back in English.
language = appLanguage(),
+ bitrateKbps = quality.bitrateKbps(),
listener = player,
)
}
diff --git a/app/src/main/java/dev/lelonio/square/ui/settings/SettingsScreen.kt b/app/src/main/java/dev/lelonio/square/ui/settings/SettingsScreen.kt
index 26f28da..fb8d5f8 100644
--- a/app/src/main/java/dev/lelonio/square/ui/settings/SettingsScreen.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/settings/SettingsScreen.kt
@@ -50,6 +50,7 @@ import com.kyant.backdrop.Backdrop
import dev.lelonio.square.BuildConfig
import dev.lelonio.square.R
import dev.lelonio.square.data.AppLanguages
+import dev.lelonio.square.data.Quality
import dev.lelonio.square.ui.MainViewModel
import dev.lelonio.square.ui.components.Artwork
import dev.lelonio.square.ui.glass.LiquidButton
@@ -188,6 +189,10 @@ fun SettingsScreen(
}
}
+ item("quality") {
+ QualitySection()
+ }
+
item("language") {
Section(stringResource(R.string.language)) {
AppLanguages.forEachIndexed { index, (tag, name) ->
@@ -279,6 +284,40 @@ fun SettingsScreen(
}
}
+/**
+ * Which file the engine asks Spotify for.
+ *
+ * The three fixed steps are the ones the account is offered, and there is no
+ * fourth: this client is served Ogg Vorbis at 320 kbps and below, never a
+ * lossless file, so a "lossless" row would be a promise nothing can keep.
+ */
+@Composable
+private fun QualitySection() {
+ val context = LocalContext.current
+ val store = remember(context) {
+ (context.applicationContext as dev.lelonio.square.SquareApplication).quality
+ }
+ val chosen by store.quality.collectAsStateWithLifecycle()
+
+ Section(stringResource(R.string.quality)) {
+ Quality.entries.forEachIndexed { index, quality ->
+ if (index > 0) RowDivider()
+ ChoiceRow(
+ label = stringResource(quality.label),
+ selected = quality == chosen,
+ ) { store.set(quality) }
+ }
+ RowDivider()
+ Text(
+ stringResource(R.string.quality_auto_note) + " " +
+ stringResource(R.string.quality_restarts),
+ style = MaterialTheme.typography.bodySmall,
+ color = InkDim,
+ modifier = Modifier.padding(horizontal = 18.dp, vertical = 14.dp),
+ )
+ }
+}
+
/**
* Checking for, and installing, a new version.
*
diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml
index 4597d5d..f702424 100644
--- a/app/src/main/res/values-de/strings.xml
+++ b/app/src/main/res/values-de/strings.xml
@@ -176,4 +176,11 @@
<string name="update_installing">Warte auf deine Bestätigung</string>
<string name="update_needs_permission">Installation erlauben — tippen</string>
<string name="update_failed">Gerade nicht — zum Wiederholen tippen</string>
+ <string name="quality">Audioqualität</string>
+ <string name="quality_auto">Automatisch</string>
+ <string name="quality_high">Hoch</string>
+ <string name="quality_medium">Mittel</string>
+ <string name="quality_low">Niedrig</string>
+ <string name="quality_auto_note">Volle Qualität im WLAN, eine Stufe darunter bei getakteten Verbindungen.</string>
+ <string name="quality_restarts">Beim Ändern wird der laufende Titel neu geladen.</string>
</resources>
diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml
index 66f36f8..1811c83 100644
--- a/app/src/main/res/values-es/strings.xml
+++ b/app/src/main/res/values-es/strings.xml
@@ -176,4 +176,11 @@
<string name="update_installing">Esperando tu confirmación</string>
<string name="update_needs_permission">Permite la instalación — toca</string>
<string name="update_failed">Ahora no — toca para reintentar</string>
+ <string name="quality">Calidad de audio</string>
+ <string name="quality_auto">Automática</string>
+ <string name="quality_high">Alta</string>
+ <string name="quality_medium">Media</string>
+ <string name="quality_low">Baja</string>
+ <string name="quality_auto_note">Calidad plena con wi-fi, un paso menos con datos medidos.</string>
+ <string name="quality_restarts">Al cambiarla, la canción en curso se vuelve a cargar.</string>
</resources>
diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml
index cdab14e..a9a5316 100644
--- a/app/src/main/res/values-fr/strings.xml
+++ b/app/src/main/res/values-fr/strings.xml
@@ -176,4 +176,11 @@
<string name="update_installing">En attente de votre confirmation</string>
<string name="update_needs_permission">Autorisez l\'installation — touchez</string>
<string name="update_failed">Pas maintenant — touchez pour réessayer</string>
+ <string name="quality">Qualité audio</string>
+ <string name="quality_auto">Automatique</string>
+ <string name="quality_high">Haute</string>
+ <string name="quality_medium">Moyenne</string>
+ <string name="quality_low">Basse</string>
+ <string name="quality_auto_note">Qualité maximale en wi-fi, un cran en dessous sur une connexion facturée.</string>
+ <string name="quality_restarts">La changer recharge le titre en cours.</string>
</resources>
diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml
index 87e340b..cd371d9 100644
--- a/app/src/main/res/values-it/strings.xml
+++ b/app/src/main/res/values-it/strings.xml
@@ -177,4 +177,11 @@
<string name="update_installing">Aspetto la tua conferma</string>
<string name="update_needs_permission">Consenti l\'installazione — tocca</string>
<string name="update_failed">Non adesso — tocca per riprovare</string>
+ <string name="quality">Qualità audio</string>
+ <string name="quality_auto">Automatica</string>
+ <string name="quality_high">Alta</string>
+ <string name="quality_medium">Media</string>
+ <string name="quality_low">Bassa</string>
+ <string name="quality_auto_note">Qualità piena sul wi-fi, un gradino sotto con la rete a consumo.</string>
+ <string name="quality_restarts">Cambiandola, la canzone in corso viene ricaricata.</string>
</resources>
diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml
index 086cf26..0a3a9e6 100644
--- a/app/src/main/res/values-pt/strings.xml
+++ b/app/src/main/res/values-pt/strings.xml
@@ -176,4 +176,11 @@
<string name="update_installing">À espera da tua confirmação</string>
<string name="update_needs_permission">Permite a instalação — toca</string>
<string name="update_failed">Agora não — toca para tentar de novo</string>
+ <string name="quality">Qualidade de áudio</string>
+ <string name="quality_auto">Automática</string>
+ <string name="quality_high">Alta</string>
+ <string name="quality_medium">Média</string>
+ <string name="quality_low">Baixa</string>
+ <string name="quality_auto_note">Qualidade máxima no wi-fi, um degrau abaixo em ligação tarifada.</string>
+ <string name="quality_restarts">Ao mudá-la, a faixa em curso é recarregada.</string>
</resources>
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index a5531e9..246e5e1 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -197,4 +197,11 @@
<string name="update_installing">Waiting for you to confirm</string>
<string name="update_needs_permission">Allow installing — tap</string>
<string name="update_failed">Not now — tap to retry</string>
+ <string name="quality">Audio quality</string>
+ <string name="quality_auto">Automatic</string>
+ <string name="quality_high">High</string>
+ <string name="quality_medium">Medium</string>
+ <string name="quality_low">Low</string>
+ <string name="quality_auto_note">Full quality on wi-fi, one step down on a metered connection.</string>
+ <string name="quality_restarts">Changing this reloads what is playing.</string>
</resources>
diff --git a/native/src/engine.rs b/native/src/engine.rs
index 41a3d73..66c4299 100644
--- a/native/src/engine.rs
+++ b/native/src/engine.rs
@@ -111,6 +111,7 @@ pub fn start(
credentials_dir: &str,
cache_dir: &str,
language: &str,
+ bitrate_kbps: i32,
listener: GlobalRef,
) -> EngineResult<()> {
let mut guard = ENGINE.lock().map_err(|_| "engine mutex poisoned")?;
@@ -155,7 +156,14 @@ pub fn start(
mixer.set_volume(u16::MAX);
let player_config = PlayerConfig {
- bitrate: Bitrate::Bitrate320,
+ // Chosen by the caller. The bitrate is read when a track is loaded but
+ // the player owns its config for its whole life, so changing this means
+ // building a new engine: see PlaybackService.
+ bitrate: match bitrate_kbps {
+ 96 => Bitrate::Bitrate96,
+ 160 => Bitrate::Bitrate160,
+ _ => Bitrate::Bitrate320,
+ },
// Loudness normalisation, which is what keeps one track from being
// twice as loud as the next.
//
diff --git a/native/src/ffi.rs b/native/src/ffi.rs
index 4f80ec4..9d39e34 100644
--- a/native/src/ffi.rs
+++ b/native/src/ffi.rs
@@ -124,6 +124,7 @@ pub extern "system" fn Java_dev_lelonio_square_nativecore_NativeBridge_nativeSta
credentials_dir: JString,
cache_dir: JString,
language: JString,
+ bitrate_kbps: jni::sys::jint,
listener: JObject,
) {
// Every argument is read before the guard: reading borrows `env`, and so
@@ -159,6 +160,7 @@ pub extern "system" fn Java_dev_lelonio_square_nativecore_NativeBridge_nativeSta
&credentials_dir,
&cache_dir,
&language,
+ bitrate_kbps,
listener,
)
});