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.

Radio keys, quieter recents and one network stack, from #19

Lelonio6624940e99ad
diff --git a/app/src/main/java/dev/lelonio/square/SquareApplication.kt b/app/src/main/java/dev/lelonio/square/SquareApplication.kt
index baa560a..45cf052 100644
--- a/app/src/main/java/dev/lelonio/square/SquareApplication.kt
+++ b/app/src/main/java/dev/lelonio/square/SquareApplication.kt
@@ -1,6 +1,11 @@
package dev.lelonio.square
import android.app.Application
+import coil.ImageLoader
+import coil.ImageLoaderFactory
+import coil.disk.DiskCache
+import coil.memory.MemoryCache
+import com.metrolist.innertube.YouTube
import dev.lelonio.square.auth.TokenStore
import dev.lelonio.square.auth.WebApiAccount
import dev.lelonio.square.data.ContextCacheStore
@@ -12,6 +17,9 @@ import dev.lelonio.square.data.RecentStore
import dev.lelonio.square.playback.EffectPresetStore
import dev.lelonio.square.data.ApiFactory
import dev.lelonio.square.data.SpotifyApi
+import okhttp3.ConnectionPool
+import okhttp3.OkHttpClient
+import java.util.concurrent.TimeUnit
/**
* Manual dependency container.
@@ -20,7 +28,7 @@ import dev.lelonio.square.data.SpotifyApi
* one thing that matters obvious: a single [TokenStore] instance, so token
* refreshes really are serialised across the whole process.
*/
-class SquareApplication : Application() {
+class SquareApplication : Application(), ImageLoaderFactory {
override fun onCreate() {
super.onCreate()
@@ -32,6 +40,10 @@ class SquareApplication : Application() {
if (BuildConfig.DEBUG || BuildConfig.VERBOSE_LOG) {
timber.log.Timber.plant(timber.log.Timber.DebugTree())
}
+
+ // Persistent HTTP cache for InnerTube requests in Android cache directory
+ YouTube.cacheDir = cacheDir
+
// Before anything can read or write them. The service used to do this on
// creation, which is late: the player screen and the media session both
// exist by then and either can announce a default that would be saved
@@ -41,7 +53,7 @@ class SquareApplication : Application() {
// Where the extras live, and which tracks are worth keeping them for.
// Attached here rather than in the service: Catalog reaches for it on
// any thread and long before anything has started playing.
- dev.lelonio.square.download.DownloadExtras.attach(downloads.root) {
+ dev.lelonio.square.download.DownloadExtras.attach(downloads.root, sharedHttpClient) {
downloads.isDownloaded(it)
}
@@ -181,7 +193,49 @@ class SquareApplication : Application() {
*/
val webApi: WebApiAccount by lazy { WebApiAccount(this) }
- val api: SpotifyApi by lazy { ApiFactory.create(webApi.tokens, debug = BuildConfig.DEBUG) }
+ /**
+ * Shared [OkHttpClient] providing a common connection pool, DNS cache, and dispatcher
+ * across Spotify API, DownloadExtras, and Coil image loading.
+ */
+ val sharedHttpClient: OkHttpClient by lazy {
+ OkHttpClient.Builder()
+ .connectionPool(ConnectionPool(5, 5, TimeUnit.MINUTES))
+ .connectTimeout(15, TimeUnit.SECONDS)
+ .readTimeout(30, TimeUnit.SECONDS)
+ .build()
+ }
+
+ override fun newImageLoader(): ImageLoader {
+ val am = getSystemService(android.app.ActivityManager::class.java)
+ val isLowRam = am?.isLowRamDevice ?: false
+ val memoryCachePercent = if (isLowRam) 0.12 else 0.20
+
+ return ImageLoader.Builder(this)
+ .okHttpClient { sharedHttpClient }
+ .memoryCache {
+ MemoryCache.Builder(this)
+ .maxSizePercent(memoryCachePercent)
+ .build()
+ }
+ .diskCache {
+ DiskCache.Builder()
+ .directory(cacheDir.resolve("image_cache"))
+ .maxSizePercent(0.02)
+ .build()
+ }
+ .allowRgb565(isLowRam)
+ .allowHardware(true)
+ .respectCacheHeaders(false)
+ .build()
+ }
+
+ val api: SpotifyApi by lazy {
+ ApiFactory.create(
+ tokens = webApi.tokens,
+ baseClient = sharedHttpClient,
+ debug = BuildConfig.DEBUG,
+ )
+ }
/** Checks the project's own releases; there is no store to do it. */
val updater: dev.lelonio.square.update.Updater by lazy {
diff --git a/app/src/main/java/dev/lelonio/square/data/ApiFactory.kt b/app/src/main/java/dev/lelonio/square/data/ApiFactory.kt
index 297af5d..5238ba8 100644
--- a/app/src/main/java/dev/lelonio/square/data/ApiFactory.kt
+++ b/app/src/main/java/dev/lelonio/square/data/ApiFactory.kt
@@ -30,8 +30,19 @@ object ApiFactory {
coerceInputValues = true
}
- fun create(tokens: TokenStore, debug: Boolean = false): SpotifyApi {
- val client = OkHttpClient.Builder()
+ /**
+ * @param baseClient the process-wide client whose connection pool, DNS cache
+ * and dispatcher this one should share. Null builds a stack of its own,
+ * which is what a test wants and what nothing else does: two independent
+ * pools to the same handful of hosts is two sets of sockets and two DNS
+ * caches for no gain. See SquareApplication's `sharedHttpClient`.
+ */
+ fun create(
+ tokens: TokenStore,
+ baseClient: OkHttpClient? = null,
+ debug: Boolean = false,
+ ): SpotifyApi {
+ val client = (baseClient?.newBuilder() ?: OkHttpClient.Builder())
.addInterceptor(AuthInterceptor(tokens))
.addInterceptor(RateLimitInterceptor())
.connectTimeout(15, TimeUnit.SECONDS)
diff --git a/app/src/main/java/dev/lelonio/square/data/DownloadStore.kt b/app/src/main/java/dev/lelonio/square/data/DownloadStore.kt
index f13dbfa..8297196 100644
--- a/app/src/main/java/dev/lelonio/square/data/DownloadStore.kt
+++ b/app/src/main/java/dev/lelonio/square/data/DownloadStore.kt
@@ -16,6 +16,7 @@ import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
+import org.json.JSONObject
import java.io.File
/**
@@ -122,6 +123,7 @@ class DownloadStore(context: Context) {
private val json = Json { ignoreUnknownKeys = true }
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
private val writeLock = Mutex()
+ private val loadLock = Mutex()
private val _index = MutableStateFlow(Index())
private val _progress = MutableStateFlow<Map<String, Float>>(emptyMap())
@@ -158,6 +160,20 @@ class DownloadStore(context: Context) {
owners.keys.associateWith(::ownerState)
}.stateIn(scope, SharingStarted.Eagerly, emptyMap())
+ init {
+ scope.launch {
+ ensureLoaded()
+ reconcile()
+ }
+ }
+
+ suspend fun ensureLoaded() = withContext(Dispatchers.IO) {
+ if (loaded) return@withContext
+ loadLock.withLock {
+ if (!loaded) loadLocked()
+ }
+ }
+
// ------------------------------------------------------------- lifecycle
/**
@@ -167,17 +183,22 @@ class DownloadStore(context: Context) {
* files on disk are still there and [reconcile] will find them, which is a
* better answer than refusing to start because a JSON file got truncated.
*/
- suspend fun load() = withContext(Dispatchers.IO) {
- if (loaded) return@withContext
- loaded = true
+ suspend fun load() = ensureLoaded()
+
+ private fun loadLocked() {
root.mkdirs()
val stored = runCatching {
if (indexFile.exists()) json.decodeFromString(Index.serializer(), indexFile.readText())
else Index()
}.getOrElse { Index() }
+ // Published before the flag goes up: [ensureLoaded] reads the flag
+ // without the lock, and a caller that sees it set must find the index
+ // already there rather than the empty one it started with.
publish(stored)
+ loaded = true
}
+ @Volatile
private var loaded = false
/**
@@ -190,14 +211,17 @@ class DownloadStore(context: Context) {
* index write leaves a file nothing claims. Cheap enough to run at startup.
*/
suspend fun reconcile() = withContext(Dispatchers.IO) {
- val current = _index.value
- val surviving = current.files.filterKeys { uri ->
- val record = current.files[uri] ?: return@filterKeys false
- audioFile(record.trackId).exists()
- }
- if (surviving.size != current.files.size) {
- publish(current.copy(files = surviving))
- save()
+ writeLock.withLock {
+ ensureLoaded()
+ val current = _index.value
+ val surviving = current.files.filterKeys { uri ->
+ val record = current.files[uri] ?: return@filterKeys false
+ audioFile(record.trackId).exists()
+ }
+ if (surviving.size != current.files.size) {
+ publish(current.copy(files = surviving))
+ save()
+ }
}
}
@@ -345,9 +369,34 @@ class DownloadStore(context: Context) {
tracks: List<CatalogTrack>,
label: OwnerLabel?,
) = writeLock.withLock {
+ ensureLoaded()
val current = _index.value
+ val existingFiles = current.files.toMutableMap()
+ for (track in tracks) {
+ if (!existingFiles.containsKey(track.uri)) {
+ val sidecar = runCatching {
+ dev.lelonio.square.nativecore.NativeBridge.downloadState(track.uri)
+ }.getOrNull()
+ if (!sidecar.isNullOrBlank()) {
+ val rootObj = runCatching { JSONObject(sidecar) }.getOrNull()
+ if (rootObj != null) {
+ val trackId = rootObj.optString("id").takeIf { it.isNotBlank() } ?: track.uri.substringAfterLast(':')
+ if (audioFile(trackId).exists()) {
+ existingFiles[track.uri] = FileRecord(
+ trackId = trackId,
+ format = rootObj.optString("format").ifEmpty { "OGG_VORBIS_320" },
+ bytes = rootObj.optLong("bytes"),
+ kbps = rootObj.optInt("kbps").takeIf { it > 0 } ?: 320,
+ downloadedAt = rootObj.optLong("downloadedAt").takeIf { it > 0 } ?: System.currentTimeMillis(),
+ )
+ }
+ }
+ }
+ }
+ }
publish(
current.copy(
+ files = existingFiles,
owners = current.owners + (ownerUri to tracks.map { it.uri }),
tracks = current.tracks + tracks.associateBy { it.uri },
labels = label?.let { current.labels + (ownerUri to it) } ?: current.labels,
@@ -364,6 +413,7 @@ class DownloadStore(context: Context) {
val existing = _owners.value[SINGLES].orEmpty()
if (existing.contains(track.uri)) return
writeLock.withLock {
+ ensureLoaded()
val current = _index.value
publish(
current.copy(
@@ -380,6 +430,7 @@ class DownloadStore(context: Context) {
val existing = _owners.value[SINGLES].orEmpty()
if (!existing.contains(trackUri)) return
writeLock.withLock {
+ ensureLoaded()
val current = _index.value
publish(current.copy(owners = current.owners + (SINGLES to existing - trackUri)))
save()
@@ -395,6 +446,7 @@ class DownloadStore(context: Context) {
* could ever see again, let alone remove.
*/
suspend fun removeOwner(ownerUri: String) = writeLock.withLock {
+ ensureLoaded()
val current = _index.value
publish(
current.copy(
@@ -423,6 +475,7 @@ class DownloadStore(context: Context) {
suspend fun onCompleted(trackUri: String, record: FileRecord) {
writeLock.withLock {
+ ensureLoaded()
val current = _index.value
publish(
current.copy(
@@ -437,6 +490,7 @@ class DownloadStore(context: Context) {
suspend fun onFailed(trackUri: String, reason: String) {
writeLock.withLock {
+ ensureLoaded()
val current = _index.value
val before = current.failures[trackUri]
publish(
@@ -457,12 +511,11 @@ class DownloadStore(context: Context) {
/** Forgets past failures so [pending] offers those tracks again. */
suspend fun retryFailed() = writeLock.withLock {
+ ensureLoaded()
publish(_index.value.copy(failures = emptyMap()))
save()
}
- // ------------------------------------------------------------ tidying up
-
/**
* Deletes files, metadata and labels nothing claims any more.
*
@@ -475,6 +528,7 @@ class DownloadStore(context: Context) {
* engine to drop them.
*/
suspend fun pruneOrphans(): List<String> = writeLock.withLock {
+ ensureLoaded()
val current = _index.value
val claimed = current.owners.values.flatten().toSet()
@@ -496,6 +550,7 @@ class DownloadStore(context: Context) {
/** Everything goes: the index, and the whole store the engine writes into. */
suspend fun clearAll() = withContext(Dispatchers.IO) {
writeLock.withLock {
+ ensureLoaded()
publish(Index())
_progress.value = emptyMap()
runCatching { root.deleteRecursively() }
@@ -530,13 +585,15 @@ class DownloadStore(context: Context) {
private fun save() {
val snapshot = _index.value
scope.launch {
- runCatching {
- root.mkdirs()
- val tmp = File(root, "$INDEX_NAME.tmp")
- tmp.writeText(json.encodeToString(Index.serializer(), snapshot))
- if (!tmp.renameTo(indexFile)) {
- indexFile.delete()
- tmp.renameTo(indexFile)
+ loadLock.withLock {
+ runCatching {
+ root.mkdirs()
+ val tmp = File(root, "$INDEX_NAME.tmp")
+ tmp.writeText(json.encodeToString(Index.serializer(), snapshot))
+ if (!tmp.renameTo(indexFile)) {
+ indexFile.delete()
+ tmp.renameTo(indexFile)
+ }
}
}
}
diff --git a/app/src/main/java/dev/lelonio/square/data/GlassStore.kt b/app/src/main/java/dev/lelonio/square/data/GlassStore.kt
index 5a4fed4..2a15f0b 100644
--- a/app/src/main/java/dev/lelonio/square/data/GlassStore.kt
+++ b/app/src/main/java/dev/lelonio/square/data/GlassStore.kt
@@ -1,6 +1,8 @@
package dev.lelonio.square.data
+import android.app.ActivityManager
import android.content.Context
+import android.os.Build
import androidx.annotation.StringRes
import dev.lelonio.square.R
import dev.lelonio.square.ui.glass.GlassEffectConfig
@@ -82,7 +84,7 @@ class GlassStore(context: Context) {
private val _profile = MutableStateFlow(
GlassProfile.entries.firstOrNull { it.key == prefs.getString(KEY_PROFILE, null) }
- ?: GlassProfile.Balanced,
+ ?: defaultProfile(context),
)
val profile: StateFlow<GlassProfile> = _profile.asStateFlow()
@@ -200,6 +202,17 @@ class GlassStore(context: Context) {
)
}
+ private fun defaultProfile(context: Context): GlassProfile {
+ val am = context.getSystemService(Context.ACTIVITY_SERVICE) as? ActivityManager
+ val isLowRam = am?.isLowRamDevice == true
+ val isOldAndroid = Build.VERSION.SDK_INT < Build.VERSION_CODES.S
+ return if (isLowRam || isOldAndroid) {
+ GlassProfile.Performance
+ } else {
+ GlassProfile.Balanced
+ }
+ }
+
private companion object {
const val FILE_NAME = "square_glass"
const val KEY_PROFILE = "profile"
diff --git a/app/src/main/java/dev/lelonio/square/download/DownloadExtras.kt b/app/src/main/java/dev/lelonio/square/download/DownloadExtras.kt
index c304251..a3083dc 100644
--- a/app/src/main/java/dev/lelonio/square/download/DownloadExtras.kt
+++ b/app/src/main/java/dev/lelonio/square/download/DownloadExtras.kt
@@ -5,6 +5,8 @@ import org.json.JSONObject
import kotlinx.coroutines.withContext
import java.io.File
import java.net.URL
+import android.graphics.Bitmap
+import android.graphics.BitmapFactory
/**
* Everything about a downloaded song that is not the song.
@@ -56,9 +58,18 @@ object DownloadExtras {
/** Whether a track is downloaded, and therefore worth keeping extras for. */
private var kept: (String) -> Boolean = { false }
- fun attach(downloadsRoot: File, isKept: (String) -> Boolean) {
+ fun attach(
+ downloadsRoot: File,
+ baseClient: okhttp3.OkHttpClient? = null,
+ isKept: (String) -> Boolean,
+ ) {
root = File(downloadsRoot, "extras")
kept = isKept
+ customHttpClient = baseClient?.newBuilder()
+ ?.connectTimeout(15, java.util.concurrent.TimeUnit.SECONDS)
+ ?.readTimeout(30, java.util.concurrent.TimeUnit.SECONDS)
+ ?.followRedirects(true)
+ ?.build()
forgetArtAnswers()
// Answers filed by a matching this build no longer trusts; see ART.
root?.let { here ->
@@ -68,6 +79,9 @@ object DownloadExtras {
}
}
+ fun attach(downloadsRoot: File, isKept: (String) -> Boolean) =
+ attach(downloadsRoot, null, isKept)
+
// ------------------------------------------------------------ the answers
fun rememberLyrics(trackUri: String, raw: String) = remember("lyrics", trackUri, raw)
@@ -197,13 +211,35 @@ object DownloadExtras {
/** Called whenever a cover appears or goes, so the answers stay true. */
private fun forgetArtAnswers() = artCache.clear()
+ private var customHttpClient: okhttp3.OkHttpClient? = null
+
+ private val httpClient: okhttp3.OkHttpClient
+ get() = customHttpClient ?: defaultHttpClient
+
+ private val defaultHttpClient by lazy {
+ okhttp3.OkHttpClient.Builder()
+ .connectTimeout(15, java.util.concurrent.TimeUnit.SECONDS)
+ .readTimeout(30, java.util.concurrent.TimeUnit.SECONDS)
+ .followRedirects(true)
+ .build()
+ }
+
/**
* Fetches and keeps one file. Answers with what is already there.
*
- * Deliberately plain: a CDN GET with no headers, no client to configure and
- * no cache of its own. Everything this fetches is immutable and addressed
- * by content — Spotify's image and Canvas URLs name the file — so there is
- * nothing for a smarter client to be smarter about.
+ * Uses OkHttp for HTTP/2 connection reuse and pooled connections.
+ *
+ * For artwork ([kind] == "art") the image is decoded, scaled down to at most
+ * [MAX_ART_PX] on each side, and re-encoded as WEBP_LOSSY quality
+ * [ART_WEBP_QUALITY] before being written. This typically reduces each cover
+ * from ~150 KB (640 px JPEG from Spotify/Apple CDN) to ~30–40 KB with no
+ * visible difference at any size the app uses, saving bandwidth every time a
+ * cover is downloaded and disk space for the lifetime of the library.
+ *
+ * The file is still named .jpg: Android BitmapFactory and Coil both detect
+ * the format from the file's magic bytes, not from the extension, so the
+ * rename is not needed and avoiding it means existing cached files remain
+ * valid without a version bump.
*/
suspend fun keep(url: String, kind: String): File? = withContext(Dispatchers.IO) {
if (url.isBlank()) return@withContext null
@@ -215,8 +251,46 @@ object DownloadExtras {
// Through a part file, so an interrupted fetch never leaves
// something half-written where a reader would take it for whole.
val part = File(file.parentFile, "${file.name}.part")
- URL(url).openStream().use { input ->
- part.outputStream().use(input::copyTo)
+ val request = okhttp3.Request.Builder().url(url).build()
+ httpClient.newCall(request).execute().use { response ->
+ if (!response.isSuccessful) return@runCatching null
+ val body = response.body ?: return@runCatching null
+
+ if (kind == "art") {
+ // Decode → scale → WebP-compress in memory, then write once.
+ //
+ // Reading the full body into a ByteArray costs one allocation
+ // of ~150 KB; the alternative (streaming into BitmapFactory)
+ // requires two passes over the stream, which OkHttp does not
+ // support without buffering it anyway.
+ val bytes = body.bytes()
+ val opts = BitmapFactory.Options().apply { inJustDecodeBounds = false }
+ val raw = BitmapFactory.decodeByteArray(bytes, 0, bytes.size, opts)
+ ?: return@runCatching null // unreadable image
+
+ val scaled = scaleBitmapDown(raw, MAX_ART_PX)
+ // raw and scaled may be the same object when no scaling was needed.
+ if (scaled !== raw) raw.recycle()
+
+ part.outputStream().use { out ->
+ @Suppress("DEPRECATION") // WEBP is fine on API 26+; WEBP_LOSSY needs API 30
+ val format = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) {
+ Bitmap.CompressFormat.WEBP_LOSSY
+ } else {
+ Bitmap.CompressFormat.WEBP
+ }
+ scaled.compress(format, ART_WEBP_QUALITY, out)
+ }
+ scaled.recycle()
+ } else {
+ // Videos and other binary files: stream directly with a
+ // 32 KB buffer so large Canvas clips don't sit in memory.
+ part.outputStream().buffered(32 * 1024).use { output ->
+ body.byteStream().buffered(32 * 1024).use { input ->
+ input.copyTo(output)
+ }
+ }
+ }
}
if (!part.renameTo(file)) {
part.delete()
@@ -227,6 +301,49 @@ object DownloadExtras {
}.getOrNull()
}
+ /**
+ * Scales a bitmap down so neither dimension exceeds [maxPx].
+ *
+ * Returns the original bitmap unchanged when it is already within the limit,
+ * so the caller can tell whether a recycle is needed.
+ */
+ private fun scaleBitmapDown(src: Bitmap, maxPx: Int): Bitmap {
+ val w = src.width
+ val h = src.height
+ if (w <= maxPx && h <= maxPx) return src
+ val scale = maxPx.toFloat() / maxOf(w, h)
+ val dstW = (w * scale).toInt().coerceAtLeast(1)
+ val dstH = (h * scale).toInt().coerceAtLeast(1)
+ return Bitmap.createScaledBitmap(src, dstW, dstH, /* filter= */ true)
+ }
+
+ /**
+ * Maximum side length for a stored cover, in pixels.
+ *
+ * High enough never to touch the prints this app asks for, and here only to
+ * bound what a pathological image could take.
+ *
+ * It arrived as 512, on the reasoning that a cover is never drawn wider
+ * than the screen. Two of the pictures kept here are not covers in that
+ * sense: the catalogue's tall artwork is fetched at 1600x2134 and the
+ * player draws it full-bleed, so on a 1080-wide phone 512 is a picture
+ * stretched to twice its size. The point of keeping it at all is that a
+ * downloaded song looks the same offline as it does online.
+ *
+ * The re-encode below is the part worth having: WebP at 80 saves most of
+ * what the scaling saved and loses nothing anybody can see.
+ */
+ private const val MAX_ART_PX = 2400
+
+ /**
+ * WEBP quality for stored covers.
+ *
+ * 80 is indistinguishable from lossless at any size the app renders
+ * covers at, and reduces file size by roughly 60–70 % compared to the
+ * JPEG that arrives from Spotify's CDN.
+ */
+ private const val ART_WEBP_QUALITY = 80
+
/**
* What a cover URL is really about, so every size of it lands on one file.
*
diff --git a/app/src/main/java/dev/lelonio/square/playback/AudioOutput.kt b/app/src/main/java/dev/lelonio/square/playback/AudioOutput.kt
index 3a6bfe5..1c055f0 100644
--- a/app/src/main/java/dev/lelonio/square/playback/AudioOutput.kt
+++ b/app/src/main/java/dev/lelonio/square/playback/AudioOutput.kt
@@ -334,7 +334,17 @@ class AudioOutput {
*/
fun setPlaybackActive(active: Boolean) {
synchronized(this) {
- if (active) applyReverb() else suspendReverb()
+ if (active) {
+ applyReverb()
+ track?.takeIf { it.state == AudioTrack.STATE_INITIALIZED }?.runCatching {
+ if (playState != AudioTrack.PLAYSTATE_PLAYING) play()
+ }
+ } else {
+ suspendReverb()
+ track?.takeIf { it.state == AudioTrack.STATE_INITIALIZED }?.runCatching {
+ if (playState == AudioTrack.PLAYSTATE_PLAYING) pause()
+ }
+ }
}
}
@@ -654,11 +664,14 @@ class AudioOutput {
return null
}
- // Four times the reported minimum. The minimum is the point at which the
- // track underruns if anything at all is late, and decoding competes with
- // the UI and the network on a phone; the extra latency is irrelevant for
- // music playback and buys enough slack to stop the dropouts.
- val bufferSize = minBuffer * BUFFER_MULTIPLIER
+ // Four times the reported minimum, with a floor of at least 500 ms of audio.
+ // The minimum is the point at which the track underruns if anything at all is late,
+ // and decoding competes with the UI and the network on a phone. Sizing for at least
+ // 500 ms ensures that UI garbage collection (GC) or Compose frame animation bursts
+ // will never cause audible dropouts or buffer starvation.
+ val bytesPerMs = sampleRate * channels * 2 / 1000
+ val minBuffer500ms = bytesPerMs * 500
+ val bufferSize = maxOf(minBuffer * BUFFER_MULTIPLIER, minBuffer500ms)
val created = AudioTrack.Builder()
.setAudioAttributes(
diff --git a/app/src/main/java/dev/lelonio/square/playback/LibrespotPlayer.kt b/app/src/main/java/dev/lelonio/square/playback/LibrespotPlayer.kt
index 9baa101..2aaeadc 100644
--- a/app/src/main/java/dev/lelonio/square/playback/LibrespotPlayer.kt
+++ b/app/src/main/java/dev/lelonio/square/playback/LibrespotPlayer.kt
@@ -463,16 +463,26 @@ class LibrespotPlayer(
.distinctUntilChanged()
.collect { offline ->
if (offline) return@collect
+ // On returning online, guarantee native session reconnection
+ kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
+ runCatching { NativeBridge.reconnect() }
+ .onFailure { android.util.Log.w("SquarePlayer", "auto-reconnect failed: ${it.message}") }
+ }
handler.post {
if (released || queue.items.isEmpty()) return@post
+ val shouldPlay = playWhenReady || wantPlay
android.util.Log.i(
"SquarePlayer",
- "back online: handing the queue over at ${positionMs}ms",
+ "back online: reconnected, restoring playback at ${positionMs}ms (shouldPlay=$shouldPlay)",
)
+ if (shouldPlay) {
+ playbackState = Player.STATE_BUFFERING
+ invalidateState()
+ }
// From where it is, playing if it was: this is a
// handover, not a restart, and the listener should hear
// the same second of the same song either side of it.
- pushQueue(startPlaying = playWhenReady, positionMs = positionMs.toInt())
+ pushQueue(startPlaying = shouldPlay, positionMs = positionMs.toInt())
}
}
}
diff --git a/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt b/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt
index a3e5f64..103974a 100644
--- a/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt
@@ -1549,7 +1549,10 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
val recent: StateFlow<List<CatalogTrack>> =
combine(container.recentStore.tracks, container.preferences.backend) { tracks, _ ->
- tracks.filter { container.activeBackend.owns(it.uri) }
+ // A nameless row is one that was recorded before the session had
+ // finished describing the track; see the history effect in
+ // SquareApp. (From HectorZL's #19.)
+ tracks.filter { it.name.isNotBlank() && container.activeBackend.owns(it.uri) }
}.stateIn(viewModelScope, SharingStarted.Eagerly, emptyList())
/** Called when a track starts, to keep the home page's history current. */
diff --git a/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt b/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt
index de246c4..a6a8d6e 100644
--- a/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt
@@ -577,7 +577,11 @@ fun SquareApp(
val radioSeeds = remember(recent, searchHistory, newPage.songs, feed.topTracks, feed.allTimeTracks) {
(recent + feed.topTracks + searchHistory + newPage.songs + feed.allTimeTracks)
.filter { it.uri.startsWith("spotify:track:") && it.artist.isNotBlank() }
- .distinctBy { it.artist.lowercase() }
+ // By address as well as by artist: the same track can arrive from
+ // two of these lists at once, and a lazy list crashes on a repeated
+ // key rather than drawing it twice. (From HectorZL's #19.)
+ .distinctBy { it.artist.lowercase().trim() }
+ .distinctBy { it.uri }
// Turned over daily rather than shuffled: a page that rearranges
// itself every time it is opened is not richer, it is unreadable.
// The same list, started at a different name each day.
@@ -866,8 +870,17 @@ fun SquareApp(
// Recorded here rather than at the tap: this fires for auto-advance and for
// controls outside the app too, so the history matches what was actually
// heard instead of only what was tapped.
- LaunchedEffect(playback.mediaId) {
+ // Keyed on the metadata as well as the address, and refusing a nameless
+ // track.
+ //
+ // A session arrives in pieces: the uri first, the title and the cover a
+ // moment later. Recorded on the uri alone, what landed in the history was a
+ // row with no name and no picture, which is the ghost you could not tap
+ // away. Waiting for a title costs nothing, because the same effect runs
+ // again when it arrives. (From HectorZL's #19.)
+ LaunchedEffect(playback.mediaId, playback.title, playback.artworkUrl) {
val uri = playback.mediaId ?: return@LaunchedEffect
+ if (playback.title.isBlank()) return@LaunchedEffect
viewModel.recordPlayed(
CatalogTrack(
uri = uri,
@@ -1487,6 +1500,13 @@ fun SquareApp(
},
onOpen = { seed ->
scope.launch {
+ // Held, because everything in here can
+ // fail: the station is fetched from a
+ // private gateway and the page is
+ // opened from a coroutine, and a throw
+ // in either took the app down with it.
+ // (From HectorZL's #19.)
+ runCatching {
val tracks = viewModel.radioFor(seed.uri)
if (tracks.isEmpty()) return@launch
val station = "spotify:station:track:" +
@@ -1505,6 +1525,13 @@ fun SquareApp(
)
navController.navigate(Routes.PLAYLIST)
onPlay(tracks, 0, station, true, name, 0L)
+ }.onFailure {
+ android.util.Log.w(
+ "SquareRadio",
+ "station for ${seed.uri} failed: ${it.message}",
+ it,
+ )
+ }
}
},
)
diff --git a/app/src/main/java/dev/lelonio/square/ui/browse/RadioScreen.kt b/app/src/main/java/dev/lelonio/square/ui/browse/RadioScreen.kt
index 409a067..7283dc2 100644
--- a/app/src/main/java/dev/lelonio/square/ui/browse/RadioScreen.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/browse/RadioScreen.kt
@@ -24,6 +24,7 @@ import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
+import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
@@ -105,7 +106,7 @@ fun RadioScreen(
horizontalArrangement = Arrangement.spacedBy(14.dp),
verticalArrangement = Arrangement.spacedBy(18.dp),
) {
- item(span = { GridItemSpan(maxLineSpan) }) {
+ item(key = "tab_radio_title", span = { GridItemSpan(maxLineSpan) }) {
Text(
stringResource(R.string.tab_radio),
style = MaterialTheme.typography.headlineMedium,
@@ -129,8 +130,12 @@ fun RadioScreen(
// Spotify's own first, under its own headings: they are titled for
// this listener, and they are the half of the page that is new every
// day rather than as old as the listening behind it.
- shelves.forEach { shelf ->
- item(span = { GridItemSpan(maxLineSpan) }, key = "shelf ${shelf.title}") {
+ val uniqueShelves = shelves
+ .filter { it.title.isNotBlank() }
+ .distinctBy { it.title.lowercase() }
+
+ uniqueShelves.forEachIndexed { shelfIndex, shelf ->
+ item(key = "shelf_${shelfIndex}_${shelf.title}", span = { GridItemSpan(maxLineSpan) }) {
Text(
shelf.title,
style = MaterialTheme.typography.titleLarge,
@@ -138,17 +143,24 @@ fun RadioScreen(
modifier = Modifier.padding(bottom = 2.dp),
)
}
- item(span = { GridItemSpan(maxLineSpan) }, key = "row ${shelf.title}") {
+ item(key = "row_${shelfIndex}_${shelf.title}", span = { GridItemSpan(maxLineSpan) }) {
+ val uniqueMixes = shelf.items
+ .filter { it.uri.isNotBlank() }
+ .distinctBy { it.uri }
LazyRow(horizontalArrangement = Arrangement.spacedBy(14.dp)) {
- rowItems(shelf.items, key = { it.uri }) { mix ->
+ rowItems(uniqueMixes, key = { it.uri }) { mix ->
MixTile(mix) { onOpenMix(mix) }
}
}
}
}
- if (seeds.isNotEmpty()) {
- item(span = { GridItemSpan(maxLineSpan) }) {
+ val uniqueSeeds = seeds
+ .filter { it.uri.isNotBlank() }
+ .distinctBy { it.uri }
+
+ if (uniqueSeeds.isNotEmpty()) {
+ item(key = "stations_title", span = { GridItemSpan(maxLineSpan) }) {
Text(
stringResource(R.string.stations_for_you),
style = MaterialTheme.typography.titleLarge,
@@ -157,7 +169,7 @@ fun RadioScreen(
)
}
- items(seeds, key = { it.uri }) { seed ->
+ items(uniqueSeeds, key = { it.uri }) { seed ->
StationTile(seed) { onOpen(seed) }
}
}
diff --git a/app/src/main/java/dev/lelonio/square/ui/components/BlurTransformation.kt b/app/src/main/java/dev/lelonio/square/ui/components/BlurTransformation.kt
index eaff621..246b1bb 100644
--- a/app/src/main/java/dev/lelonio/square/ui/components/BlurTransformation.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/components/BlurTransformation.kt
@@ -55,26 +55,41 @@ class BlurTransformation(private val radius: Int = 12, private val passes: Int =
height: Int,
radius: Int,
) {
+ val windowSize = 2 * radius + 1
for (y in 0 until height) {
val row = y * width
+ val first = source[row]
+ val firstA = (first ushr 24) and 0xFF
+ val firstR = (first ushr 16) and 0xFF
+ val firstG = (first ushr 8) and 0xFF
+ val firstB = first and 0xFF
+
+ var a = firstA * (radius + 1)
+ var r = firstR * (radius + 1)
+ var g = firstG * (radius + 1)
+ var b = firstB * (radius + 1)
+
+ for (i in 1..radius) {
+ val sample = source[row + i.coerceAtMost(width - 1)]
+ a += (sample ushr 24) and 0xFF
+ r += (sample ushr 16) and 0xFF
+ g += (sample ushr 8) and 0xFF
+ b += sample and 0xFF
+ }
+
for (x in 0 until width) {
- var a = 0
- var r = 0
- var g = 0
- var b = 0
- var count = 0
- // Clamped at the edges, which repeats the border pixel. On an
- // image this blurred, the alternative — wrapping — would drag
- // one side's colour onto the other.
- for (offset in -radius..radius) {
- val sample = source[row + (x + offset).coerceIn(0, width - 1)]
- a += (sample ushr 24) and 0xFF
- r += (sample ushr 16) and 0xFF
- g += (sample ushr 8) and 0xFF
- b += sample and 0xFF
- count++
- }
- target[row + x] = pack(a / count, r / count, g / count, b / count)
+ target[row + x] = pack(a / windowSize, r / windowSize, g / windowSize, b / windowSize)
+
+ val outIdx = (x - radius).coerceAtLeast(0)
+ val inIdx = (x + radius + 1).coerceAtMost(width - 1)
+
+ val outSample = source[row + outIdx]
+ val inSample = source[row + inIdx]
+
+ a += ((inSample ushr 24) and 0xFF) - ((outSample ushr 24) and 0xFF)
+ r += ((inSample ushr 16) and 0xFF) - ((outSample ushr 16) and 0xFF)
+ g += ((inSample ushr 8) and 0xFF) - ((outSample ushr 8) and 0xFF)
+ b += (inSample and 0xFF) - (outSample and 0xFF)
}
}
}
@@ -86,22 +101,40 @@ class BlurTransformation(private val radius: Int = 12, private val passes: Int =
height: Int,
radius: Int,
) {
+ val windowSize = 2 * radius + 1
for (x in 0 until width) {
+ val first = source[x]
+ val firstA = (first ushr 24) and 0xFF
+ val firstR = (first ushr 16) and 0xFF
+ val firstG = (first ushr 8) and 0xFF
+ val firstB = first and 0xFF
+
+ var a = firstA * (radius + 1)
+ var r = firstR * (radius + 1)
+ var g = firstG * (radius + 1)
+ var b = firstB * (radius + 1)
+
+ for (i in 1..radius) {
+ val sample = source[i.coerceAtMost(height - 1) * width + x]
+ a += (sample ushr 24) and 0xFF
+ r += (sample ushr 16) and 0xFF
+ g += (sample ushr 8) and 0xFF
+ b += sample and 0xFF
+ }
+
for (y in 0 until height) {
- var a = 0
- var r = 0
- var g = 0
- var b = 0
- var count = 0
- for (offset in -radius..radius) {
- val sample = source[(y + offset).coerceIn(0, height - 1) * width + x]
- a += (sample ushr 24) and 0xFF
- r += (sample ushr 16) and 0xFF
- g += (sample ushr 8) and 0xFF
- b += sample and 0xFF
- count++
- }
- target[y * width + x] = pack(a / count, r / count, g / count, b / count)
+ target[y * width + x] = pack(a / windowSize, r / windowSize, g / windowSize, b / windowSize)
+
+ val outIdx = (y - radius).coerceAtLeast(0)
+ val inIdx = (y + radius + 1).coerceAtMost(height - 1)
+
+ val outSample = source[outIdx * width + x]
+ val inSample = source[inIdx * width + x]
+
+ a += ((inSample ushr 24) and 0xFF) - ((outSample ushr 24) and 0xFF)
+ r += ((inSample ushr 16) and 0xFF) - ((outSample ushr 16) and 0xFF)
+ g += ((inSample ushr 8) and 0xFF) - ((outSample ushr 8) and 0xFF)
+ b += (inSample and 0xFF) - (outSample and 0xFF)
}
}
}
diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/InnerTube.kt b/innertube/src/main/kotlin/com/metrolist/innertube/InnerTube.kt
index 7586f85..a9b9ad0 100644
--- a/innertube/src/main/kotlin/com/metrolist/innertube/InnerTube.kt
+++ b/innertube/src/main/kotlin/com/metrolist/innertube/InnerTube.kt
@@ -75,6 +75,20 @@ class InnerTube {
var useLoginForBrowse: Boolean = false
+ /**
+ * Persistent HTTP cache directory.
+ *
+ * Set this to [android.content.Context.getCacheDir] (or a subdirectory of
+ * it) before the first request is made. The default — [java.io.tmpdir] —
+ * maps to the system's temporary directory, which Android is free to clear
+ * under memory pressure. Pointing it at the app's own cache directory keeps
+ * the cached responses between runs without risking a memory leak.
+ *
+ * Changing this after the client has been built has no effect until the
+ * client is next recreated (e.g. on a proxy change).
+ */
+ var cacheDir: java.io.File? = null
+
@OptIn(ExperimentalSerializationApi::class)
private fun createClient() = HttpClient(OkHttp) {
expectSuccess = true
@@ -118,7 +132,13 @@ class InnerTube {
// Cache configuration for better performance
cache(
okhttp3.Cache(
- directory = java.io.File(System.getProperty("java.io.tmpdir"), "http_cache"),
+ // Use the injected Android cache directory when available;
+ // fall back to java.io.tmpdir only as a last resort so the
+ // module still compiles and runs in unit-test environments
+ // that have no Android context.
+ directory = [email protected]
+ ?.let { java.io.File(it, "innertube_http_cache") }
+ ?: java.io.File(System.getProperty("java.io.tmpdir"), "http_cache"),
maxSize = 50L * 1024L * 1024L // 50 MB
)
)
@@ -148,10 +168,12 @@ class InnerTube {
defaultRequest {
url(YouTubeClient.API_URL_YOUTUBE_MUSIC)
- // Add common headers for better compatibility
header("Accept", "application/json")
header("Accept-Language", "en-US,en;q=0.9")
- header("Cache-Control", "no-cache")
+ // Cache-Control is intentionally omitted: OkHttp and the server
+ // negotiate caching through ETag / Cache-Control response headers.
+ // Sending "no-cache" here would bypass the 50 MB disk cache on
+ // every single request, which is exactly what was happening before.
}
}
diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/YouTube.kt b/innertube/src/main/kotlin/com/metrolist/innertube/YouTube.kt
index eb05509..bbbe7a8 100644
--- a/innertube/src/main/kotlin/com/metrolist/innertube/YouTube.kt
+++ b/innertube/src/main/kotlin/com/metrolist/innertube/YouTube.kt
@@ -135,6 +135,21 @@ object YouTube {
innerTube.useLoginForBrowse = value
}
+ /**
+ * Persistent HTTP cache directory for the underlying OkHttp client.
+ *
+ * Assign [android.content.Context.getCacheDir] (or a subdirectory of it)
+ * before the first request is made. The default is java.io.tmpdir, which
+ * Android may clear at any time. This must be set from the Application
+ * class before the YouTube backend is first used.
+ */
+ var cacheDir: java.io.File?
+ get() = innerTube.cacheDir
+ set(value) {
+ innerTube.cacheDir = value
+ }
+
+
suspend fun searchSuggestions(query: String): Result<SearchSuggestions> =
runCatching {
val response = innerTube.getSearchSuggestions(WEB_REMIX, query).body<GetSearchSuggestionsResponse>()