Skip to content

Native Android client for Spotify, built with Jetpack Compose

Next songs kept: an extension's songs go through the media cache, the next one read whole ahead

kota-zo70cbcb4565e6
diff --git a/base/app/src/main/java/com/music/spotui/automix/TrackDecoder.kt b/base/app/src/main/java/com/music/spotui/automix/TrackDecoder.kt
index 852896c7..ab42905f 100644
--- a/base/app/src/main/java/com/music/spotui/automix/TrackDecoder.kt
+++ b/base/app/src/main/java/com/music/spotui/automix/TrackDecoder.kt
@@ -176,7 +176,9 @@ object TrackDecoder {
* plus 7.8 s decoding). A read elsewhere (a seek) starts again from there.
*/
private class ByteSource(private val uri: Uri, private val cancelled: () -> Boolean) : MediaDataSource() {
- private val data = OfflineCrypto.Factory(Graph.app).createDataSource()
+ // Through the media cache for an extension's song: the bytes read for the analysis are the
+ // ones the song then plays from, not asked a second time (see ExtStreamCache).
+ private val data = com.music.spotui.data.offline.ExtStreamCache.Factory(Graph.app).createDataSource()
private var size = -1L
private var sizeKnown = false
/** [data] is open at 0 from [getSize], not read yet: the first read from 0 goes on from it. */
diff --git a/base/app/src/main/java/com/music/spotui/data/AppStorage.kt b/base/app/src/main/java/com/music/spotui/data/AppStorage.kt
index 69d48387..0d95e1fd 100644
--- a/base/app/src/main/java/com/music/spotui/data/AppStorage.kt
+++ b/base/app/src/main/java/com/music/spotui/data/AppStorage.kt
@@ -18,9 +18,12 @@ import java.io.File
object AppStorage {
private const val PREFS = "myspoti_prefs"
private const val KEY_MEDIA_MB = "media_cache_mb"
- private const val MEDIA_DEFAULT_MB = 64
+ private const val MEDIA_DEFAULT_MB = 256
- /** The sizes offered for the media cache, in MB (64 MB, the old fixed size, by default). */
+ /**
+ * The sizes offered for the media cache, in MB. 256 MB unless chosen: it holds the songs the
+ * extensions stream (the next one read whole ahead), and a lossless song is 30 to 40 MB.
+ */
val MEDIA_CACHE_CHOICES = listOf(64, 256, 512, 1024)
/** The media cache's size as chosen, in MB (Compose state). */
diff --git a/base/app/src/main/java/com/music/spotui/data/offline/ExtStreamCache.kt b/base/app/src/main/java/com/music/spotui/data/offline/ExtStreamCache.kt
new file mode 100644
index 00000000..1151836f
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/data/offline/ExtStreamCache.kt
@@ -0,0 +1,81 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+package com.music.spotui.data.offline
+
+import android.content.Context
+import android.net.Uri
+import androidx.annotation.OptIn
+import androidx.media3.common.util.UnstableApi
+import androidx.media3.datasource.DataSource
+import androidx.media3.datasource.DataSpec
+import androidx.media3.datasource.TransferListener
+import androidx.media3.datasource.cache.CacheDataSource
+import androidx.media3.datasource.cache.CacheWriter
+import com.music.spotui.di.SongPlayer
+import com.music.spotui.extensions.ExtensionAudio
+
+/**
+ * The songs an audio-source extension streams, kept in the media cache as they are read, and the
+ * next one read whole ahead ([cacheAhead]): a song then plays on through a network that drops
+ * (airplane mode, a tunnel) and a skip back plays from the phone. Keyed by the song (the
+ * extension's address changes at each ask); downloads and files of the device are read as before.
+ */
+@OptIn(UnstableApi::class)
+object ExtStreamCache {
+ private fun key(uri: Uri) = "ext:" + uri.lastPathSegment.orEmpty()
+
+ private fun cached(context: Context): CacheDataSource.Factory = CacheDataSource.Factory()
+ .setCache(SongPlayer.mediaCache(context.applicationContext))
+ .setUpstreamDataSourceFactory(OfflineCrypto.Factory(context))
+ .setCacheKeyFactory { spec -> key(spec.uri) }
+ // A cache that fails (full storage) never stops the song: it is read from the network.
+ .setFlags(CacheDataSource.FLAG_IGNORE_CACHE_ON_ERROR)
+
+ /** The player's sources: an extension's song through the cache, anything else as before. */
+ class Factory(private val context: Context) : DataSource.Factory {
+ private val plain = OfflineCrypto.Factory(context)
+ private val viaCache by lazy { cached(context) }
+ override fun createDataSource(): DataSource = Routing(plain.createDataSource()) { viaCache.createDataSource() }
+ }
+
+ /** Opens [cachedSource] for an extension's song, [plain] for the rest. */
+ private class Routing(private val plain: DataSource, private val cachedSource: () -> DataSource) : DataSource {
+ private var cache: DataSource? = null
+ private var active: DataSource = plain
+ private val listeners = mutableListOf<TransferListener>()
+
+ override fun addTransferListener(transferListener: TransferListener) {
+ listeners += transferListener
+ plain.addTransferListener(transferListener)
+ cache?.addTransferListener(transferListener)
+ }
+
+ override fun open(dataSpec: DataSpec): Long {
+ active = if (dataSpec.uri.scheme == ExtensionAudio.SCHEME)
+ (cache ?: cachedSource().also { c -> listeners.forEach(c::addTransferListener); cache = c })
+ else plain
+ return active.open(dataSpec)
+ }
+
+ override fun read(buffer: ByteArray, offset: Int, length: Int): Int = active.read(buffer, offset, length)
+ override fun getUri(): Uri? = active.uri
+ override fun getResponseHeaders(): Map<String, List<String>> = active.responseHeaders
+ override fun close() = active.close()
+ }
+
+ /**
+ * Reads the song at [uri] into the cache, up to half the media cache (a long FLAC is kept in
+ * part: its start, which is what a drop or a skip needs first). Blocking; [keepGoing] false
+ * stops it. Off a metered network only (the caller checks).
+ */
+ fun cacheAhead(context: Context, uri: Uri, keepGoing: () -> Boolean) {
+ if (uri.scheme != ExtensionAudio.SCHEME) return
+ val cap = com.music.spotui.data.AppStorage.mediaCacheLimit() / 2
+ val spec = DataSpec.Builder().setUri(uri).setLength(cap).build()
+ val writer = CacheWriter(cached(context).createDataSource(), spec, null) { _, _, _ -> }
+ val watch = Thread {
+ while (keepGoing()) runCatching { Thread.sleep(250) }.onFailure { return@Thread }
+ writer.cancel()
+ }.apply { isDaemon = true; name = "ext-cache-watch"; start() }
+ try { writer.cache() } finally { watch.interrupt() }
+ }
+}
diff --git a/base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt b/base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt
index 79c4b86d..d599a91c 100644
--- a/base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt
+++ b/base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt
@@ -67,8 +67,9 @@ object LocalPlayer {
.setAudioAttributes(audioAttributes, main && !mirrorActive)
.setHandleAudioBecomingNoisy(main)
// Downloaded songs are encrypted files: the player reads them through the decrypting source.
+ // An extension's songs go through the media cache (see ExtStreamCache).
.setMediaSourceFactory(androidx.media3.exoplayer.source.DefaultMediaSourceFactory(
- com.music.spotui.data.offline.OfflineCrypto.Factory(Graph.app)).setLoadErrorHandlingPolicy(NoAudioNotRetried))
+ com.music.spotui.data.offline.ExtStreamCache.Factory(Graph.app)).setLoadErrorHandlingPolicy(NoAudioNotRetried))
.build()
// The speed and the silence skipping of the settings (the fading-out copy too: both are heard).
.also(::tune)
@@ -249,8 +250,9 @@ object LocalPlayer {
/**
* Resolves the next item's audio ahead (ExtensionAudio keeps the answer for its data source),
* and reads its start: the first bytes of a url (StreamHead), the index and first segment of a
- * DASH answer, so a skip starts at once. Off a metered network only, apart from the answer
- * and the DASH index; the next song changing abandons it.
+ * DASH answer, so a skip starts at once, then the song itself into the cache (ExtStreamCache).
+ * Off a metered network only, apart from the answer and the DASH index; the next song
+ * changing abandons it.
*/
private fun prefetchNext(p: ExoPlayer) {
ahead?.cancel()
@@ -273,6 +275,11 @@ object LocalPlayer {
com.music.spotui.data.offline.StreamHead.fetch(uri.lastPathSegment.orEmpty(), s.url, s.headers,
System.currentTimeMillis() + s.keepMs(HEAD_KEEP_MS)) { isActive }
}
+ // The whole next song (or its start, a long one) into the cache: it plays on if
+ // the network drops meanwhile, airplane mode included (reported: the song after
+ // skipped a few seconds into a flight).
+ if (cheap && isActive && !com.music.spotui.data.DataSaver.active)
+ com.music.spotui.data.offline.ExtStreamCache.cacheAhead(Graph.app, uri) { isActive }
}
}
}