Skip to content

Native Android client for Spotify, built with Jetpack Compose

Resume after a relaunch goes back to the extensions when the last session was theirs (still starting: waited for), the last answers are kept on disk for an instant resume, and an extension answering after Spotify started the song takes it back from where it is

kota-zo8b1ce590e1f0
diff --git a/base/app/src/main/java/com/music/spotui/di/SongPlayer.kt b/base/app/src/main/java/com/music/spotui/di/SongPlayer.kt
index 4fdc547f..03c7bfed 100644
--- a/base/app/src/main/java/com/music/spotui/di/SongPlayer.kt
+++ b/base/app/src/main/java/com/music/spotui/di/SongPlayer.kt
@@ -1542,11 +1542,26 @@ object SongPlayer {
* mini player, the notification, headphones) is asked there first, from where it was, with
* the engine's queue after it; Spotify resumes when they have nothing. False: Spotify resumes.
*/
- private fun resumeThroughExtensions(): Boolean {
+ private fun resumeThroughExtensions(restoredLocal: Boolean = false): Boolean {
val np = _nowPlaying.value
- if (!np.uri.startsWith(SPOTIFY_TRACK_PREFIX) || _activeDevice.value != null || routing) return false
val id = trackIdOf(np.uri)
- if (id.isBlank() || id in spotifyPlayed || !com.music.spotui.extensions.Extensions.hasAudioSource()) return false
+ val ext = com.music.spotui.extensions.Extensions
+ // The session put back at launch was the extensions' (this phone's local player): it goes
+ // back to them, the extensions still starting are waited for ([Extensions.audio]), and a
+ // device Spotify still lists as active (the page has not caught up yet) does not send it to Spotify.
+ // Reported: a play right after a relaunch resumed on Spotify, and the source had to be picked again.
+ val why = when {
+ !np.uri.startsWith(SPOTIFY_TRACK_PREFIX) || id.isBlank() -> "not a song"
+ routing -> "a song is being asked"
+ _activeDevice.value != null && !restoredLocal -> "another device plays"
+ id in spotifyPlayed -> "no extension had it this session"
+ !ext.hasAudioSource() && !(restoredLocal && ext.audioSourceOn()) -> ext.audioSkipped() ?: "no audio source on"
+ else -> null
+ }
+ if (why != null) {
+ if (np.uri.startsWith(SPOTIFY_TRACK_PREFIX)) app.myspoti.host.android.Logbook.log("audio: resume of $id on Spotify: $why")
+ return false
+ }
val q = _queue.value
val songs = (listOfNotNull(q.current) + (q.queued + q.nextUp).map { it.song }).takeIf { l -> l.any { it.spotifyTrackId == id } }
app.myspoti.host.android.Logbook.log("audio: resume of $id asked to the extensions")
@@ -1554,6 +1569,28 @@ object SongPlayer {
return true
}
+ /**
+ * The extension answered for [trackId] after Spotify had started it for want of an answer in
+ * time ([com.music.spotui.extensions.ExtensionAudio.playList]): still that song on Spotify here,
+ * it goes to the extension from where it is, its queue after it, as picking the extension in the
+ * player does. On the main thread.
+ */
+ fun extensionAnsweredLate(trackId: String) {
+ val np = _nowPlaying.value
+ if (LocalPlayer.active.value || routing || _activeDevice.value != null || trackIdOf(np.uri) != trackId) return
+ if (com.music.spotui.data.DataSaver.active || com.music.spotui.cast.CastPlayback.active) return
+ spotifyPlayed.remove(trackId)
+ val q = _queue.value
+ val songs = (listOfNotNull(q.current) + (q.queued + q.nextUp).map { it.song }).takeIf { l -> l.any { it.spotifyTrackId == trackId } }
+ app.myspoti.host.android.Logbook.log("audio: the extension answered late for $trackId: it plays it from ${getCurrentPosition()} ms")
+ if (!isPlaying()) {
+ val song = songs?.firstOrNull { it.spotifyTrackId == trackId } ?: q.current?.takeIf { it.spotifyTrackId == trackId } ?: return
+ putPausedOnExtension(trackId, songs ?: listOf(song)) { }
+ return
+ }
+ playSong(np.uri, contextUri = np.contextUri.ifBlank { null }, positionMs = getCurrentPosition(), songs = songs)
+ }
+
/**
* A song picked on another device while the Connect mirror played: asked to the extensions as a
* pick here is, from where the page is, with the page's queue after it; Spotify plays it when they
@@ -1608,8 +1645,9 @@ object SongPlayer {
app.myspoti.host.android.Logbook.log("play asked by $by")
if (routing) return // the song asked for starts by itself
if (LocalPlayer.active.value) { Haptics.click(); if (!playDueOnSpotify()) LocalPlayer.resume(); return }
+ val wasLocal = restoredLocal
if (resumeRestoredLocal()) { Haptics.click(); return }
- if (resumeThroughExtensions()) { Haptics.click(); return }
+ if (resumeThroughExtensions(wasLocal)) { Haptics.click(); return }
// Smart shuffle was turned off while paused: the list's order comes back as it plays on.
plainOrderDue?.let { if (restorePlainOrder(it)) return }
// Myspoti's shuffle turned on or off while paused: the song goes on in the list's new order.
diff --git a/base/app/src/main/java/com/music/spotui/extensions/ExtensionAudio.kt b/base/app/src/main/java/com/music/spotui/extensions/ExtensionAudio.kt
index a364f0a7..82c4ac58 100644
--- a/base/app/src/main/java/com/music/spotui/extensions/ExtensionAudio.kt
+++ b/base/app/src/main/java/com/music/spotui/extensions/ExtensionAudio.kt
@@ -8,6 +8,8 @@ import com.music.spotui.data.local.LocalTrack
import com.music.spotui.data.offline.OfflineStore
import com.music.spotui.di.LocalPlayer
import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.async
+import kotlinx.coroutines.launch
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeoutOrNull
@@ -78,6 +80,67 @@ object ExtensionAudio {
private fun keep(trackId: String, stream: AudioStream) {
known[trackId] = Known(stream)
answers.intValue++
+ Saved.put(trackId, stream)
+ }
+
+ /**
+ * The last few answers, kept on disk with when they came: an app relaunched within their life
+ * ([AudioStream.keepMs]) plays the song where it was at once, without waiting for the extension
+ * to start and answer again (reported: the resume after a relaunch fell back to Spotify). An
+ * address refused by then is asked again ([AudioRoute.openStream]), as any expired one.
+ */
+ private object Saved {
+ private const val PREFS = "extension_answers"
+ private const val MAX = 4
+ private val prefs get() = com.music.spotui.di.Graph.app.getSharedPreferences(PREFS, 0)
+ @Volatile private var loaded = false
+
+ fun put(trackId: String, s: AudioStream) {
+ // A transformed file (decrypted, remuxed) is not replayed from a bare address.
+ if (s.transform != null || trackId.isBlank()) return
+ val json = kotlinx.serialization.json.buildJsonObject {
+ put("at", kotlinx.serialization.json.JsonPrimitive(System.currentTimeMillis()))
+ put("url", kotlinx.serialization.json.JsonPrimitive(s.url))
+ put("headers", kotlinx.serialization.json.JsonObject(s.headers.mapValues { kotlinx.serialization.json.JsonPrimitive(it.value) }))
+ s.mimeType?.let { put("mime", kotlinx.serialization.json.JsonPrimitive(it)) }
+ s.durationMs?.let { put("duration", kotlinx.serialization.json.JsonPrimitive(it)) }
+ s.providerId?.let { put("provider", kotlinx.serialization.json.JsonPrimitive(it)) }
+ s.manifest?.let { put("manifest", kotlinx.serialization.json.JsonPrimitive(it)) }
+ s.expiresInMs?.let { put("expires", kotlinx.serialization.json.JsonPrimitive(it)) }
+ s.bitDepth?.let { put("bits", kotlinx.serialization.json.JsonPrimitive(it)) }
+ s.sampleRate?.let { put("rate", kotlinx.serialization.json.JsonPrimitive(it)) }
+ s.codec?.let { put("codec", kotlinx.serialization.json.JsonPrimitive(it)) }
+ s.source?.let { put("source", kotlinx.serialization.json.JsonPrimitive(it)) }
+ }.toString()
+ runCatching {
+ val p = prefs
+ val order = p.getString("order", "").orEmpty().split(',').filter { it.isNotBlank() && it != trackId } + trackId
+ val keep = order.takeLast(MAX)
+ p.edit().apply {
+ order.dropLast(MAX).forEach { remove("a:$it") }
+ putString("a:$trackId", json); putString("order", keep.joinToString(","))
+ }.apply()
+ }
+ }
+
+ /** Puts the answers still good back in [known], once, before the first use of an answer. */
+ fun load() {
+ if (loaded) return
+ loaded = true
+ runCatching {
+ val p = prefs
+ for (id in p.getString("order", "").orEmpty().split(',').filter { it.isNotBlank() }) {
+ val o = runCatching { kotlinx.serialization.json.Json.parseToJsonElement(p.getString("a:$id", null) ?: continue) as kotlinx.serialization.json.JsonObject }.getOrNull() ?: continue
+ fun str(k: String) = (o[k] as? kotlinx.serialization.json.JsonPrimitive)?.takeIf { it.isString }?.content
+ fun num(k: String) = (o[k] as? kotlinx.serialization.json.JsonPrimitive)?.content?.toLongOrNull()
+ val headers = (o["headers"] as? kotlinx.serialization.json.JsonObject)?.mapValues { (it.value as kotlinx.serialization.json.JsonPrimitive).content }.orEmpty()
+ val s = AudioStream(str("url").orEmpty(), headers, str("mime"), num("duration"), str("provider"), str("manifest"),
+ num("expires"), num("bits")?.toInt(), num("rate")?.toInt(), str("codec"), str("source"))
+ val k = Known(s, num("at") ?: 0L)
+ if (k.fresh && known[id] == null) known[id] = k
+ }
+ }
+ }
}
/** [stream], from the source picked for it in the player (SongPlayer.switchSource), is the song [trackId]'s audio from now on. */
@@ -85,6 +148,9 @@ object ExtensionAudio {
private val warming = ConcurrentHashMap.newKeySet<String>()
+ /** Asks that outlive a tap's wait (see [playList]). */
+ private val late = kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.SupervisorJob() + Dispatchers.IO)
+
/** Taps being answered ([playList]): asking ahead waits, the extension's one thread is theirs. */
private val picking = java.util.concurrent.atomic.AtomicInteger()
@@ -144,6 +210,7 @@ object ExtensionAudio {
* [ahead]: asked before the song plays (the extension is told so).
*/
fun resolve(u: Uri, again: Boolean = false, ahead: Boolean = false): AudioStream? {
+ Saved.load()
val key = u.lastPathSegment.orEmpty()
if (again) {
known.remove(key)
@@ -191,18 +258,28 @@ object ExtensionAudio {
// take a second ask for a refused address and resolve it anew.
// A downloaded song plays from its file whatever the extensions have: asked first, a miss (after
// up to 13 s) sent a song marked downloaded to Spotify's stream.
+ Saved.load()
if (!OfflineStore.isDownloaded(picked.spotifyTrackId)) {
// A tap waits [Extensions.PICK_AUDIO_MS] for the extensions, then Spotify plays the song.
// The outer bound also covers a wait in the extension's queue or for extensions still loading.
+ // The ask itself goes on longer: an answer that comes after Spotify started the song
+ // takes it back to the extension where it is ([late]), rather than the user doing so by hand.
picking.incrementAndGet()
+ val cached = known[picked.spotifyTrackId]?.takeIf { it.fresh }?.stream
+ val ask = if (cached != null) null else late.async {
+ Extensions.audio(Extensions.trackInfo(picked.spotifyTrackId, picked.title, picked.singer, picked.album, picked.durationMs.toLong(), picked.coverUri), timeoutMs = Extensions.AUDIO_MS)
+ }
val first = try {
- known[picked.spotifyTrackId]?.takeIf { it.fresh }?.stream ?: withTimeoutOrNull(Extensions.PICK_AUDIO_MS + 1_000) {
- withContext(Dispatchers.IO) {
- Extensions.audio(Extensions.trackInfo(picked.spotifyTrackId, picked.title, picked.singer, picked.album, picked.durationMs.toLong(), picked.coverUri), timeoutMs = Extensions.PICK_AUDIO_MS)
- }
- }
+ cached ?: withTimeoutOrNull(Extensions.PICK_AUDIO_MS + 1_000) { ask!!.await() }
} finally { picking.decrementAndGet() } ?: run {
- app.myspoti.host.android.Logbook.log("audio: no extension audio for ${picked.title} within ${Extensions.PICK_AUDIO_MS / 1000} s: Spotify plays it")
+ if (ask != null && !ask.isCompleted) {
+ app.myspoti.host.android.Logbook.log("audio: no extension audio for ${picked.title} within ${(Extensions.PICK_AUDIO_MS + 1_000) / 1000} s: Spotify plays it, the extension's answer is still awaited")
+ late.launch {
+ val s = runCatching { ask.await() }.getOrNull() ?: return@launch
+ keep(picked.spotifyTrackId, s)
+ withContext(Dispatchers.Main) { com.music.spotui.di.SongPlayer.extensionAnsweredLate(picked.spotifyTrackId) }
+ }
+ } else app.myspoti.host.android.Logbook.log("audio: no extension had ${picked.title}: Spotify plays it")
return false
}
keep(picked.spotifyTrackId, first)
diff --git a/base/app/src/main/java/com/music/spotui/extensions/Extensions.kt b/base/app/src/main/java/com/music/spotui/extensions/Extensions.kt
index 1b36639f..92636c66 100644
--- a/base/app/src/main/java/com/music/spotui/extensions/Extensions.kt
+++ b/base/app/src/main/java/com/music/spotui/extensions/Extensions.kt
@@ -745,6 +745,9 @@ object Extensions {
return isReady && (providing(Hook.AUDIO_SOURCE).isNotEmpty() || startingAudioSource())
}
+ /** An audio-source extension is turned on (running or not yet): a session of theirs goes back to them. */
+ fun audioSourceOn(): Boolean = isReady && _registry.value.extensions.any { it.enabled && Action.AUDIO_SOURCE.key in it.granted }
+
/** The app is still starting the extensions on at launch, an audio source among them. */
private fun startingAudioSource(): Boolean =
!started.isCompleted && _registry.value.extensions.any { it.enabled && Action.AUDIO_SOURCE.key in it.granted }