Skip to content

Native Android client for Spotify, built with Jetpack Compose

The queue follows on Spotify while an extension song plays: songs queued here (single or lists) are queued on Spotify in the same order, removals and moves follow, device files stay local; a local player that starts takes Spotify's queued songs first; the mirror skips to a song's queued copy instead of playing it twice; the mirror pulls playback here before its first play and a remote move is only followed while this phone is active, so two installs no longer pass playback back and forth

kota-zo2c50d3bc63d4
diff --git a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyPlayer.kt b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyPlayer.kt
index daf76f29..d6828526 100644
--- a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyPlayer.kt
+++ b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyPlayer.kt
@@ -1764,9 +1764,13 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
override suspend fun playNext(uris: List<Uri>) {
val first = _queue.value?.queued?.firstOrNull()
if (first == null) { addToQueue(uris); return }
+ insertInQueue(uris, first)
+ }
+
+ override suspend fun insertInQueue(uris: List<Uri>, before: NowPlaying) {
bridge.call("queue.insert", buildJsonObject {
putJsonArray("uris") { uris.forEach { add(kotlinx.serialization.json.JsonPrimitive(it)) } }
- put("before", ref(first))
+ put("before", ref(before))
})
}
diff --git a/base/api/src/main/kotlin/app/myspoti/api/Api.kt b/base/api/src/main/kotlin/app/myspoti/api/Api.kt
index 22ef3faf..cc1f24ed 100644
--- a/base/api/src/main/kotlin/app/myspoti/api/Api.kt
+++ b/base/api/src/main/kotlin/app/myspoti/api/Api.kt
@@ -50,6 +50,8 @@ interface Player {
suspend fun skipTo(item: NowPlaying)
/** "Play next": before everything already queued. */
suspend fun playNext(uris: List<Uri>)
+ /** Queues [uris] just before [before], a queued item of [Queue.queued]. */
+ suspend fun insertInQueue(uris: List<Uri>, before: NowPlaying)
/** Moves [item] just before or after [target], in the same part of the queue. */
suspend fun moveInQueue(item: NowPlaying, target: NowPlaying, after: Boolean)
diff --git a/base/app/src/main/java/com/music/spotui/di/ConnectMirror.kt b/base/app/src/main/java/com/music/spotui/di/ConnectMirror.kt
index 5bae4432..086f7f92 100644
--- a/base/app/src/main/java/com/music/spotui/di/ConnectMirror.kt
+++ b/base/app/src/main/java/com/music/spotui/di/ConnectMirror.kt
@@ -64,6 +64,10 @@ object ConnectMirror {
private val main = Handler(Looper.getMainLooper())
private val echo = MirrorRules.Echo(SystemClock::elapsedRealtime)
private val lock = Mutex()
+ /** The device list's read before a play or a followed move is not waited for longer. */
+ private const val DEVICES_WAIT_MS = 1_500L
+ /** A pull of playback here is not waited for longer (a device that went away can leave it pending). */
+ private const val PULL_WAIT_MS = 5_000L
/** Bumped when the mirror ends: commands still waiting for the lock are dropped. */
private var generation = 0
@@ -106,6 +110,10 @@ object ConnectMirror {
private var recoverUntil = 0L
/** Playback went to another device while mirrored: it comes back through the extensions. */
private var handedAway = false
+ /** The mirror's first play of this run is still to be sent: playback is pulled here first when elsewhere. */
+ private var firstPlay = false
+ /** The play waiting in [sendPlay] is for a new song of the local player (not a play sent again). */
+ private var newSong = false
private var driftJob: Job? = null
/** The end of the last mirror (page heard again, quality back): the next command waits for it. */
private var ending: Job? = null
@@ -224,6 +232,8 @@ object ConnectMirror {
if (item.uri == w.uri) lastWeb = s
if (item.uri == w.uri && !s.isPaused) {
if (failedUri == w.uri) log("the page plays ${w.uri} again")
+ // On the song now: Spotify's queue is checked against the local one.
+ if (!landed) QueueSync.mirrorLanded()
landed = true; failedUri = null; backoffStep = 0
}
val t = LocalPlayer.current() ?: return
@@ -254,13 +264,13 @@ object ConnectMirror {
Follow.Pause -> { log("paused on another device"); want = w.copy(paused = true); LocalPlayer.pause() }
Follow.Resume -> { log("resumed on another device"); want = w.copy(paused = false); LocalPlayer.resume() }
is Follow.Seek -> { log("moved to ${f.ms} ms on another device"); LocalPlayer.seekTo(f.ms) }
- Follow.Next -> { log("next on another device"); moved(web, s); LocalPlayer.next() }
- Follow.Previous -> { log("previous on another device"); moved(web, s); LocalPlayer.previousItem() }
+ Follow.Next -> { moved(web, s); followIfHere(web.uri, "next on another device") { LocalPlayer.next() } }
+ Follow.Previous -> { moved(web, s); followIfHere(web.uri, "previous on another device") { LocalPlayer.previousItem() } }
Follow.Resend -> if (pendingContext != null) Unit else if (resends++ < MAX_RESENDS) {
log("the page is still on ${web.uri}, played earlier by the mirror: ${w.uri} sent again")
playNow(w.uri, w.uri)
} else backOff(w)
- is Follow.Play -> { log("${f.uri} picked on another device"); moved(web, s); SongPlayer.followRemotePlay(item, s.contextUri, f.positionMs) }
+ is Follow.Play -> { moved(web, s); followIfHere(f.uri, "${f.uri} picked on another device") { SongPlayer.followRemotePlay(item, s.contextUri, f.positionMs) } }
is Follow.Align -> command(ECHO_MS) { api.player.seek(f.ms) }
Follow.Back -> if (pendingContext != null) Unit else {
log("the page went on to ${web.uri} by itself while ${t.title} is to play again here: put back on ${w.uri}, not followed")
@@ -279,6 +289,38 @@ object ConnectMirror {
}
}
+ /**
+ * Another song on the page, by a remote command: followed only while this phone is still Spotify
+ * Connect's active device. The page shows the active device's playback, and the watcher reports
+ * a takeover a few seconds late: a song another device (or another install of the app) took
+ * playback with is not followed, the local player stops (followed, the mirror's play would be a
+ * remote command to that device, which takes it as its own, and the two fight over it).
+ */
+ private fun followIfHere(uri: String, line: String, follow: () -> Unit) {
+ val gen = generation
+ MyspotiRuntime.scope.launch {
+ val device = activeElsewhere()
+ main.post {
+ if (gen != generation || !running) return@post
+ if (!MirrorRules.followsRemote(device != null)) {
+ log("$uri plays on $device, which took playback: the local player stops, not followed")
+ handedAway = true
+ LocalPlayer.stop()
+ return@post
+ }
+ log(line)
+ follow()
+ }
+ }
+ }
+
+ /** The name of the device of the account that is Spotify Connect's active one when it is not this page, or null. */
+ private suspend fun activeElsewhere(): String? {
+ if (page.playsElsewhere.value) return api.devices.devices.value.firstOrNull { it.active && !it.local }?.name ?: "another device"
+ kotlinx.coroutines.withTimeoutOrNull(DEVICES_WAIT_MS) { runCatching { api.devices.refresh() } }
+ return api.devices.devices.value.firstOrNull { it.active && !it.local }?.name
+ }
+
/**
* The page would not take [w]'s song (twice): never given up for good. It is paused meanwhile
* (unheard, at its lowest quality, nothing else plays on the account) and the song is played there
@@ -292,7 +334,7 @@ object ConnectMirror {
// One try each time from now on: a miss goes to the next, longer wait.
retries = MAX_RETRIES; resends = MAX_RESENDS
command(ECHO_MS) { api.player.pause() }
- pendingContext = w.uri
+ pendingContext = w.uri; newSong = false
main.removeCallbacks(sendPlay); main.postDelayed(sendPlay, delayMs)
}
@@ -303,7 +345,7 @@ object ConnectMirror {
landed = false; retries = 0; resends = 0; lastWeb = null; gapFrom = null
recoverUntil = SystemClock.elapsedRealtime() + RECOVER_MS
// The track alone: the list the page had went with the ad's or the reload's own plays.
- pendingContext = w.uri
+ pendingContext = w.uri; newSong = false
echo.sent(PLAY_ECHO_MS)
main.removeCallbacks(sendPlay); main.postDelayed(sendPlay, START_COALESCE_MS)
}
@@ -320,6 +362,7 @@ object ConnectMirror {
private fun start(uri: String, at: Long) {
if (!running) {
running = true
+ firstPlay = true
// An extension's own mirror (playback.mirror) gives way: two would fight over the page.
com.music.spotui.extensions.Extensions.mirrorReset("Myspoti plays the song on Spotify itself")
// The page asks Android for the audio focus as it plays: the local player must not yield it.
@@ -333,6 +376,7 @@ object ConnectMirror {
failedUri = null; backoffStep = 0
// In the list the local queue came from, as the phone would play it: other devices see that queue after it.
pendingContext = MirrorRules.playContext(LocalPlayer.contextUri, uri, missedContexts)
+ newSong = true
log("$uri plays unheard on Spotify from $at ms")
// A skip right after this one replaces it: one play for a burst of skips (they landed out of order).
echo.sent(PLAY_ECHO_MS)
@@ -346,12 +390,19 @@ object ConnectMirror {
// The local player paused or stalled meanwhile: played when it plays (Lead.Resume).
if (w.paused) return@Runnable
pendingContext = null
- playNow(w.uri, context)
+ playNow(w.uri, context, newSong)
+ newSong = false
}
- /** Plays [uri] (in [context]) on the page from the local position, unheard, noted as the mirror's own play. */
- private fun playNow(uri: String, context: String) {
+ /**
+ * Plays [uri] (in [context]) on the page from the local position, unheard, noted as the mirror's own play.
+ * [newSong]: the local player's new song, which may be queued on Spotify (see [QueueSyncRules.way]).
+ * The run's first play pulls playback here first when another device has it ([QueueSyncRules.pullsHere]).
+ */
+ private fun playNow(uri: String, context: String, newSong: Boolean = false) {
val at = LocalPlayer.position()
+ val first = firstPlay
+ firstPlay = false
val now = SystemClock.elapsedRealtime()
recentPlays.addLast(uri to now)
while (recentPlays.size > MAX_RECENT) recentPlays.removeFirst()
@@ -363,8 +414,31 @@ object ConnectMirror {
// Before the play: the page picks the song's file with the quality it has then.
page.setMirroring(true)
if (!api.player.localMute) api.player.setLocalMute(true)
+ val device = if (first) activeElsewhere() else null
+ if (QueueSyncRules.pullsHere(first, elsewhere = device != null)) {
+ log("$device has playback: pulled here before the page plays")
+ val pulled = kotlinx.coroutines.withTimeoutOrNull(PULL_WAIT_MS) { runCatching { api.devices.pullHere() } }
+ if (pulled?.isSuccess != true) log("pull here failed: ${pulled?.exceptionOrNull()?.message ?: "no answer"}")
+ }
// Ended meanwhile: no play that would be heard next to the local player.
- if (live()) api.player.play(context, trackUri = uri.takeIf { it != context }, positionMs = at)
+ if (!live()) return@command
+ val s = page.state.value
+ val queued = api.player.queue.value?.queued.orEmpty()
+ val way = if (newSong) QueueSyncRules.way(uri, s?.item?.uri, s?.isPaused == false, queued.map { it.uri }) else QueueSyncRules.Way.Play
+ when (way) {
+ QueueSyncRules.Way.Already -> {
+ log("the page plays $uri already (gone on to its queued copy): kept in step")
+ val web = s?.positionAt(System.currentTimeMillis()) ?: at
+ if (kotlin.math.abs(web - at) > MirrorRules.DRIFT_MS) api.player.seek(at)
+ }
+ is QueueSyncRules.Way.Skip -> {
+ log("$uri played from Spotify's queue")
+ api.player.skipTo(queued[way.index])
+ QueueSync.consumed(uri)
+ if (at > MirrorRules.DRIFT_MS) api.player.seek(at)
+ }
+ QueueSyncRules.Way.Play -> api.player.play(context, trackUri = uri.takeIf { it != context }, positionMs = at)
+ }
}
}
@@ -408,6 +482,9 @@ object ConnectMirror {
/** Waits until the last mirror's end reached the page (see [stop]). */
suspend fun awaitEnded() { ending?.join() }
+ /** The page plays [uri] for the mirror (it landed there). */
+ fun landedOn(uri: String): Boolean = running && landed && want?.uri == uri
+
/** Playback was handed to another device and has not come back to play here yet (see [onEngine]). */
val waitsBack: Boolean get() = handedAway
@@ -451,7 +528,20 @@ object ConnectMirror {
if (!playingHere) return
val back = MirrorRules.backHere(playingHere, handedAway, moved, intended, ConnectMirrorPref.on)
handedAway = false
- if (back) SongPlayer.backThroughExtensions()
+ if (!back) return
+ // Checked against the device list: the page shows the active device's song as playing, and
+ // the watcher reports another device's takeover a few seconds late.
+ MyspotiRuntime.scope.launch {
+ val device = activeElsewhere()
+ main.post {
+ if (MirrorRules.backHere(playingHere, true, moved, intended, ConnectMirrorPref.on, activeElsewhere = device != null)) SongPlayer.backThroughExtensions()
+ else if (device != null) {
+ // Still away: its next state here (a real transfer back) is judged again.
+ handedAway = true
+ log("playback plays on $device, not on this phone: not taken back")
+ }
+ }
+ }
}
/** The local player as it is now, judged as a state of it. */
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 4e456519..d571062c 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
@@ -243,8 +243,11 @@ object LocalPlayer {
}
SongPlayer.pauseEngineForLocal()
forgetRadio(); this.continues = continues
- tracks.clear(); tracks.addAll(list); unshuffled = null
+ // Spotify's queued songs (the account's: maybe queued on another device or install) play first.
+ val (all, fromSpotify) = QueueSync.withSpotifyQueue(list, index.coerceIn(0, list.lastIndex))
+ tracks.clear(); tracks.addAll(all); unshuffled = null
queued.clear(); playingQueued = null; radioSongs.clear()
+ queued += fromSpotify
listName = context ?: Graph.app.getString(app.myspoti.engine.R.string.local_files_title)
listUri = contextUri
active.value = true
@@ -255,7 +258,7 @@ object LocalPlayer {
replaying = null
repeat = SongPlayer.repeatMode.value
applyRepeat(p)
- p.setMediaItems(list.map(::item), index.coerceIn(0, list.lastIndex), startMs.coerceAtLeast(0L))
+ p.setMediaItems(all.map(::item), index.coerceIn(0, list.lastIndex), startMs.coerceAtLeast(0L))
p.prepare()
if (shuffle) setShuffle(true)
p.play()
@@ -477,6 +480,13 @@ object LocalPlayer {
/** How many of [upcoming] the user queued (they come first). */
fun queuedCount(): Int = exo?.let { LocalQueueOrder.queuedAfter(tracks, it.currentMediaItemIndex, isQueued) } ?: 0
+ /** The Spotify uris of the queued songs after the current one, in order (a device file has none: left out). */
+ fun queuedUris(): List<String> {
+ val i = exo?.currentMediaItemIndex ?: return emptyList()
+ val from = (i + 1).coerceAtMost(tracks.size)
+ return tracks.subList(from, (from + queuedCount()).coerceAtMost(tracks.size)).map(::spotifyId).filter { it.isNotBlank() }.map { "spotify:track:$it" }
+ }
+
/** The current song is one the user queued ("Playing from the queue"). */
fun fromQueue(): Boolean = playingQueued?.let { it === current() } == true
@@ -893,5 +903,6 @@ object LocalPlayer {
if (CastPlayback.active) CastPlayback.follow(t, exo?.currentPosition ?: 0L)
SongPlayer.onLocalState(t, playWhenReady(), position(), duration())
SongPlayer.onLocalQueue(t, upcoming(), queuedCount())
+ QueueSync.localChanged(queuedUris())
}
}
diff --git a/base/app/src/main/java/com/music/spotui/di/MirrorRules.kt b/base/app/src/main/java/com/music/spotui/di/MirrorRules.kt
index 656afddf..9bd4ee5e 100644
--- a/base/app/src/main/java/com/music/spotui/di/MirrorRules.kt
+++ b/base/app/src/main/java/com/music/spotui/di/MirrorRules.kt
@@ -173,10 +173,16 @@ object MirrorRules {
* Whether a song the engine plays heard on this phone goes back to the extensions (and so to the
* mirror): Connect playback came back here after the mirror had handed it away ([handedAway]), or
* another device moved the engine here (a resume, a skip, a pick: [moved]) without Myspoti having
- * asked for it ([intended]). Only while it plays here ([playingHere]) with the setting [on].
+ * asked for it ([intended]). Only while it plays here ([playingHere]) with the setting [on], and
+ * never while the device list says another device is the active one ([activeElsewhere]): the
+ * page then shows that device's song as playing (another install of the app that resumed it),
+ * and taking it back would start a fight between the two.
*/
- fun backHere(playingHere: Boolean, handedAway: Boolean, moved: Boolean, intended: Boolean, on: Boolean): Boolean =
- on && playingHere && !intended && (handedAway || moved)
+ fun backHere(playingHere: Boolean, handedAway: Boolean, moved: Boolean, intended: Boolean, on: Boolean, activeElsewhere: Boolean = false): Boolean =
+ on && playingHere && !intended && (handedAway || moved) && !activeElsewhere
+
+ /** A remote move of the page (next, previous, a pick) is followed only while no other device is the active one. */
+ fun followsRemote(activeElsewhere: Boolean): Boolean = !activeElsewhere
/** How long a page ready again is given for its device to join Spotify Connect before it is commanded anyway. */
const val JOIN_WAIT_MS = 8_000L
diff --git a/base/app/src/main/java/com/music/spotui/di/QueueSync.kt b/base/app/src/main/java/com/music/spotui/di/QueueSync.kt
new file mode 100644
index 00000000..9d637115
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/di/QueueSync.kt
@@ -0,0 +1,132 @@
+package com.music.spotui.di
+
+import android.os.Handler
+import android.os.Looper
+import app.myspoti.api.ItemKind
+import app.myspoti.host.android.MyspotiRuntime
+import com.music.spotui.data.local.LocalTrack
+import com.music.spotui.data.preferences.ConnectMirrorPref
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.sync.Mutex
+import kotlinx.coroutines.sync.withLock
+import kotlinx.coroutines.withTimeoutOrNull
+
+/**
+ * The local player's queue is Spotify's too, while the Connect mirror holds the page: the songs the
+ * user queues here ("Play next", "Add to queue", single songs and lists) are queued on Spotify, in
+ * the same order, and their removal or move there follows. Spotify's queue is the account's: another
+ * device, or another install of the app, that takes playback finds them. A local player that starts
+ * takes Spotify's queued songs first ([withSpotifyQueue]), as Spotify plays its queue before a list.
+ *
+ * Spotify's queue is brought to the local one ([QueueSyncRules.plan]) after a local queue edit and
+ * once the page is on each new song. Edits made on another device while the local player plays are
+ * not taken here: a song removed there comes back at the next song. Device files (no Spotify id) stay
+ * in the local queue only. The decisions are in [QueueSyncRules]; this runs them (main thread, page
+ * calls in the background).
+ */
+object QueueSync {
+ private const val TRACK_PREFIX = "spotify:track:"
+ /** A burst of edits (a list queued song by song, a drag) is synced once it settles. */
+ private const val SETTLE_MS = 1_000L
+ /** Waited (at most) for Spotify's queue to show the edits before the next sync reads it. */
+ private const val QUEUE_ECHO_MS = 2_500L
+ /** Songs per call: a whole playlist in one call is a long wait for the page. */
+ private const val BATCH = 100
+
+ private val api get() = MyspotiRuntime.api
+ private val page get() = MyspotiRuntime.spotify.player
+ private val main = Handler(Looper.getMainLooper())
+ private val lock = Mutex()
+ /** How many of each uri the sync queued on Spotify (or took from there): the ones it may take out again. */
+ private val owned = HashMap<String, Int>()
+ /** The local queue's songs at the last edit seen (see [localChanged]). */
+ private var lastLocal: List<String> = emptyList()
+
+ /** The local player's queue as published (main thread): synced when it changed. */
+ fun localChanged(queued: List<String>) {
+ if (queued == lastLocal) return
+ lastLocal = queued
+ schedule()
+ }
+
+ /** The mirror's page is on the local player's song (main thread): Spotify's queue is checked again. */
+ fun mirrorLanded() = schedule()
+
+ /** The mirror played [uri] from Spotify's queue, which consumed that copy. */
+ fun consumed(uri: String) = synchronized(owned) { take(uri, 1) }
+
+ private fun schedule() {
+ main.removeCallbacks(sync)
+ main.postDelayed(sync, SETTLE_MS)
+ }
+
+ private fun usable(): Boolean =
+ ConnectMirrorPref.on && LocalPlayer.active.value && ConnectMirror.running && !SongPlayer.routing &&
+ api.ready.value && !page.playsElsewhere.value && !page.adPlaying.value
+
+ private val sync = Runnable {
+ if (!usable()) return@Runnable
+ val local = LocalPlayer.queuedUris()
+ // The song about to be played from Spotify's queue by the mirror keeps its copy there until then.
+ val current = LocalPlayer.current()?.let(LocalPlayer::spotifyIdOf)?.takeIf { it.isNotBlank() }?.let { TRACK_PREFIX + it }
+ val spare = current?.takeIf { !ConnectMirror.landedOn(it) }
+ MyspotiRuntime.scope.launch { lock.withLock { runCatching { reconcile(local, spare) }.onFailure { log("not synced: ${it.message}") } } }
+ }
+
+ private suspend fun reconcile(local: List<String>, spare: String?) {
+ val q = api.player.queue.value ?: return
+ val items = q.queued.filter { it.kind == ItemKind.TRACK && it.uri.startsWith(TRACK_PREFIX) }
+ val plan = synchronized(owned) { QueueSyncRules.plan(local, items.map { it.uri }, HashMap(owned), spare) }
+ if (plan.empty) return
+ if (plan.remove.isNotEmpty()) {
+ val gone = plan.remove.map(items::get)
+ api.player.removeFromQueue(gone)
+ synchronized(owned) { gone.forEach { take(it.uri, 1) } }
+ }
+ for (insert in plan.inserts) for (batch in insert.uris.chunked(BATCH)) {
+ val before = insert.beforeIndex?.let(items::get)
+ if (before == null) api.player.addToQueue(batch) else api.player.insertInQueue(batch, before)
+ synchronized(owned) { batch.forEach { owned[it] = (owned[it] ?: 0) + 1 } }
+ }
+ log("Spotify's queue follows the local one: ${plan.inserts.sumOf { it.uris.size }} added, ${plan.remove.size} removed")
+ // The next sync reads the queue with these edits in it.
+ withTimeoutOrNull(QUEUE_ECHO_MS) { api.player.queue.first { it !== q } }
+ }
+
+ private fun take(uri: String, n: Int) {
+ val left = (owned[uri] ?: 0) - n
+ if (left > 0) owned[uri] = left else owned.remove(uri)
+ }
+
+ /**
+ * A local player starts on [list] at [at] (main thread): Spotify's queued songs (the account's,
+ * maybe queued on another device or by another install of the app) play right after the picked
+ * song, as queued songs, then the list goes on. Those [list] has there already (the takeover
+ * lists put Spotify's queue after the song) are taken as they are; the others are added (each
+ * asked to the extensions when it plays, as any queued song). Returns the list to play and the
+ * songs to mark queued. Unchanged with the mirror's setting off or nothing queued on Spotify.
+ */
+ fun withSpotifyQueue(list: List<LocalTrack>, at: Int): Pair<List<LocalTrack>, List<LocalTrack>> {
+ lastLocal = emptyList()
+ if (!ConnectMirrorPref.on) return list to emptyList()
+ // The new local queue is made of what Spotify's holds now: the sync owns those, nothing else.
+ synchronized(owned) { owned.clear() }
+ val queued = api.player.queue.value?.queued.orEmpty().filter { it.kind == ItemKind.TRACK && it.uri.startsWith(TRACK_PREFIX) }
+ if (queued.isEmpty()) return list to emptyList()
+ val next = list.drop(at + 1)
+ val ways = QueueSyncRules.adopt(next.map { t -> LocalPlayer.spotifyIdOf(t).let { if (it.isBlank()) "" else TRACK_PREFIX + it } }, queued.map { it.uri })
+ val taken = ways.mapIndexedNotNull { i, k ->
+ k?.let(next::get) ?: com.music.spotui.extensions.ExtensionAudio.queueTrack(SongPlayer.songOf(queued[i]))
+ }
+ if (taken.isEmpty()) return list to emptyList()
+ val matched = ways.count { it != null }
+ synchronized(owned) {
+ taken.forEach { t -> LocalPlayer.spotifyIdOf(t).takeIf { it.isNotBlank() }?.let { owned[TRACK_PREFIX + it] = (owned[TRACK_PREFIX + it] ?: 0) + 1 } }
+ }
+ log("${taken.size} queued songs taken from Spotify")
+ return (list.take(at + 1) + taken + next.drop(matched)) to taken
+ }
+
+ private fun log(line: String) = app.myspoti.host.android.Logbook.log("queue: $line")
+}
diff --git a/base/app/src/main/java/com/music/spotui/di/QueueSyncRules.kt b/base/app/src/main/java/com/music/spotui/di/QueueSyncRules.kt
new file mode 100644
index 00000000..f9ac42d0
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/di/QueueSyncRules.kt
@@ -0,0 +1,92 @@
+package com.music.spotui.di
+
+/**
+ * The queue sync's decisions (see [QueueSync]), without Android: the songs the user queued while
+ * the local player plays are Spotify's queue too (the account's, seen by every device and every
+ * install of the app), and a local player that starts takes Spotify's queued songs back.
+ * Songs are Spotify uris; a device file without one stays in the local queue only.
+ */
+object QueueSyncRules {
+ /** [uris] go into Spotify's queue before its queued item at [beforeIndex] (null: at its end). */
+ data class Insert(val uris: List<String>, val beforeIndex: Int?)
+
+ /** What Spotify's queue needs: its queued items at [remove] go (indexes), then [inserts], in order. */
+ data class Plan(val remove: List<Int>, val inserts: List<Insert>) {
+ val empty: Boolean get() = remove.isEmpty() && inserts.isEmpty()
+ }
+
+ /**
+ * Brings Spotify's queued songs ([page], in order) to the local queue's ([local], in order).
+ * Page items are matched to the local ones in order (each at the first place after the last
+ * match); a local song with no match is inserted before the next matched item (at the end when
+ * none), so "Play next" lands first and "Add to queue" last. A page item with no match goes only
+ * if the sync put it there ([owned]: how many of each uri it did): another device's queued song
+ * stays. A reorder is a removal and an insertion. [current]: the song the local player is on, whose
+ * first queued copy the mirror is about to play from the queue (it consumes it): never removed
+ * meanwhile (null once the mirror is on it: a copy left then is a duplicate).
+ */
+ fun plan(local: List<String>, page: List<String>, owned: Map<String, Int>, current: String? = null): Plan {
+ val matched = BooleanArray(page.size)
+ val spare = page.indexOfFirst { it == current }
+ val inserts = ArrayList<Insert>()
+ val pending = ArrayList<String>()
+ var from = 0
+ for (uri in local) {
+ val at = (from until page.size).firstOrNull { it != spare && page[it] == uri }
+ if (at == null) { pending += uri; continue }
+ matched[at] = true
+ if (pending.isNotEmpty()) { inserts += Insert(pending.toList(), at); pending.clear() }
+ from = at + 1
+ }
+ if (pending.isNotEmpty()) inserts += Insert(pending.toList(), null)
+ val left = HashMap(owned)
+ val remove = page.indices.filter { i ->
+ if (matched[i] || i == spare) return@filter false
+ val n = left[page[i]] ?: 0
+ if (n <= 0) return@filter false
+ left[page[i]] = n - 1
+ true
+ }
+ return Plan(remove, inserts)
+ }
+
+ /**
+ * A local player starts on a list ([localNext]: the songs after the picked one, in order) while
+ * Spotify's queue holds [pageQueued]: those play first, as Spotify plays its queue before the list.
+ * For each queued song in order, the index in [localNext] of the song that is it (the list
+ * already has it right there: the takeover lists put Spotify's queue after the picked song), or
+ * null when it must be added. The matched ones are always the first of [localNext], in order.
+ */
+ fun adopt(localNext: List<String>, pageQueued: List<String>): List<Int?> {
+ var k = 0
+ return pageQueued.map { uri -> if (localNext.getOrNull(k) == uri) k++ else null }
+ }
+
+ /** How the mirror puts the page on the local player's new song. */
+ sealed interface Way {
+ /** The page plays it already (it went on to its queued copy by itself): only kept in step. */
+ data object Already : Way
+ /** Its copy in Spotify's queue, at [index] of the queued items: a skip to it, which consumes it. */
+ data class Skip(val index: Int) : Way
+ /** A play (in the local list's Spotify list): Spotify keeps its user queue across a new play. */
+ data object Play : Way
+ }
+
+ /**
+ * [uri] is the local player's new song; the page is on [pageUri] ([pagePlaying]: not paused)
+ * with [pageQueued] queued. A queued copy is skipped to rather than played anew: a play would
+ * leave the copy queued, and Spotify would play the song a second time after it.
+ */
+ fun way(uri: String, pageUri: String?, pagePlaying: Boolean, pageQueued: List<String>): Way = when {
+ pageUri == uri && pagePlaying -> Way.Already
+ else -> pageQueued.indexOf(uri).takeIf { it >= 0 }?.let { Way.Skip(it) } ?: Way.Play
+ }
+
+ /**
+ * Before the mirror's first play of a run ([firstPlay]), another device being Spotify Connect's
+ * active one ([elsewhere]): playback is pulled here first. Sent as is, the page's play would be
+ * a remote command to that device (another install of the app there takes it as playback "back
+ * on this phone" and the two fight over it).
+ */
+ fun pullsHere(firstPlay: Boolean, elsewhere: Boolean): Boolean = firstPlay && elsewhere
+}
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 bf3b2763..dd0dc262 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
@@ -455,7 +455,7 @@ object SongPlayer {
private fun songIdFor(trackId: String, fallback: String) =
(if (trackId.isNotBlank()) "track:$trackId" else "uri:$fallback").hashCode() and 0x7fffffff
- private fun songOf(n: app.myspoti.api.NowPlaying): SongsModel {
+ internal fun songOf(n: app.myspoti.api.NowPlaying): SongsModel {
val id = trackIdOf(n.uri)
val artists = n.artists.joinToString(", ") { it.name }
return SongsModel(
diff --git a/base/app/src/test/java/com/music/spotui/di/MirrorRulesTest.kt b/base/app/src/test/java/com/music/spotui/di/MirrorRulesTest.kt
index ea35db39..871ca513 100644
--- a/base/app/src/test/java/com/music/spotui/di/MirrorRulesTest.kt
+++ b/base/app/src/test/java/com/music/spotui/di/MirrorRulesTest.kt
@@ -278,4 +278,14 @@ class MirrorRulesTest {
assertFalse(MirrorRules.pageUsable(ready = true, ad = true, joined = true, joinReported = true, waitedOut = true))
assertFalse(MirrorRules.pageUsable(ready = false, ad = false, joined = true, joinReported = true, waitedOut = true))
}
+
+ @Test fun `another install of the app that resumed playback is not fought over`() {
+ // The page shows the other device's song as playing: the device list says it is not this phone.
+ assertFalse(MirrorRules.backHere(playingHere = true, handedAway = false, moved = true, intended = false, on = true, activeElsewhere = true))
+ assertFalse(MirrorRules.backHere(playingHere = true, handedAway = true, moved = false, intended = false, on = true, activeElsewhere = true))
+ assertTrue(MirrorRules.backHere(playingHere = true, handedAway = true, moved = false, intended = false, on = true, activeElsewhere = false))
+ // A remote next, previous or pick is followed only while this phone has playback.
+ assertTrue(MirrorRules.followsRemote(activeElsewhere = false))
+ assertFalse(MirrorRules.followsRemote(activeElsewhere = true))
+ }
}
diff --git a/base/app/src/test/java/com/music/spotui/di/QueueSyncRulesTest.kt b/base/app/src/test/java/com/music/spotui/di/QueueSyncRulesTest.kt
new file mode 100644
index 00000000..9b4fe376
--- /dev/null
+++ b/base/app/src/test/java/com/music/spotui/di/QueueSyncRulesTest.kt
@@ -0,0 +1,105 @@
+package com.music.spotui.di
+
+import com.music.spotui.di.QueueSyncRules.Insert
+import com.music.spotui.di.QueueSyncRules.Plan
+import com.music.spotui.di.QueueSyncRules.Way
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class QueueSyncRulesTest {
+ private val a = "spotify:track:a"
+ private val b = "spotify:track:b"
+ private val c = "spotify:track:c"
+ private val d = "spotify:track:d"
+ private val f = "spotify:track:foreign"
+
+ private fun owns(vararg uris: String) = uris.groupingBy { it }.eachCount()
+
+ // ── Spotify's queue brought to the local one ──
+
+ @Test fun `in step nothing to do`() {
+ assertTrue(QueueSyncRules.plan(listOf(a, b), listOf(a, b), owns(a, b)).empty)
+ assertTrue(QueueSyncRules.plan(emptyList(), emptyList(), emptyMap()).empty)
+ }
+
+ @Test fun `add to queue goes at the end`() {
+ assertEquals(Plan(emptyList(), listOf(Insert(listOf(c), null))), QueueSyncRules.plan(listOf(a, b, c), listOf(a, b), owns(a, b)))
+ assertEquals(Plan(emptyList(), listOf(Insert(listOf(a, b), null))), QueueSyncRules.plan(listOf(a, b), emptyList(), emptyMap()))
+ }
+
+ @Test fun `play next goes before the first queued item, a list in its order`() {
+ assertEquals(Plan(emptyList(), listOf(Insert(listOf(c, d), 0))), QueueSyncRules.plan(listOf(c, d, a, b), listOf(a, b), owns(a, b)))
+ }
+
+ @Test fun `a removal here removes the song there`() {
+ assertEquals(Plan(listOf(1), emptyList()), QueueSyncRules.plan(listOf(a, c), listOf(a, b, c), owns(a, b, c)))
+ }
+
+ @Test fun `clear queue removes only what the sync queued`() {
+ assertEquals(Plan(listOf(0, 2), emptyList()), QueueSyncRules.plan(emptyList(), listOf(a, f, b), owns(a, b)))
+ }
+
+ @Test fun `another device's queued song stays where it is`() {
+ val plan = QueueSyncRules.plan(listOf(a, b, c), listOf(a, f, b), owns(a, b))
+ assertEquals(Plan(emptyList(), listOf(Insert(listOf(c), null))), plan)
+ }
+
+ @Test fun `a reorder is a removal and an insertion`() {
+ // b moved before a: a matched first, b found nowhere after it, so the old b goes and a new one is added after a.
+ assertEquals(Plan(listOf(0), listOf(Insert(listOf(b), null))), QueueSyncRules.plan(listOf(a, b), listOf(b, a), owns(a, b)))
+ assertEquals(Plan(listOf(0), listOf(Insert(listOf(a), 2))), QueueSyncRules.plan(listOf(b, a, c), listOf(a, b, c), owns(a, b, c)))
+ }
+
+ @Test fun `a song queued twice is two copies`() {
+ assertEquals(Plan(emptyList(), listOf(Insert(listOf(a), null))), QueueSyncRules.plan(listOf(a, a), listOf(a), owns(a)))
+ assertEquals(Plan(listOf(1), emptyList()), QueueSyncRules.plan(listOf(a), listOf(a, a), owns(a, a)))
+ // Owned once: the other copy is another device's.
+ assertTrue(QueueSyncRules.plan(emptyList(), listOf(a, a), owns(a)).remove.size == 1)
+ }
+
+ @Test fun `the copy the mirror is about to play from the queue is spared`() {
+ // The local player went on to a: the copy stays until the mirror skips to it (it consumes it).
+ assertTrue(QueueSyncRules.plan(listOf(b), listOf(a, b), owns(a, b), current = a).empty)
+ // Once the mirror is on a, a copy left is a duplicate and goes.
+ assertEquals(Plan(listOf(0), emptyList()), QueueSyncRules.plan(listOf(b), listOf(a, b), owns(a, b), current = null))
+ // Spared, never matched: a queued again after it is a second copy.
+ assertEquals(Plan(emptyList(), listOf(Insert(listOf(a), null))), QueueSyncRules.plan(listOf(b, a), listOf(a, b), owns(a, b), current = a))
+ }
+
+ @Test fun `a queue wiped by a play is put back whole`() {
+ assertEquals(Plan(emptyList(), listOf(Insert(listOf(a, b, c), null))), QueueSyncRules.plan(listOf(a, b, c), emptyList(), owns(a, b, c)))
+ }
+
+ // ── A local player that starts takes Spotify's queue ──
+
+ @Test fun `the takeover list has Spotify's queue after the song already`() {
+ assertEquals(listOf(0, 1), QueueSyncRules.adopt(listOf(a, b, c, d), listOf(a, b)))
+ }
+
+ @Test fun `queued songs the list does not have are added, in Spotify's order`() {
+ assertEquals(listOf(null, null), QueueSyncRules.adopt(listOf(c, d), listOf(a, b)))
+ // b left out of the list (once per song): added where Spotify has it.
+ assertEquals(listOf(0, null, 1), QueueSyncRules.adopt(listOf(a, c, d), listOf(a, b, c)))
+ assertEquals(emptyList<Int?>(), QueueSyncRules.adopt(listOf(a), emptyList()))
+ }
+
+ // ── How the mirror puts the page on a new song ──
+
+ @Test fun `a queued song is skipped to, not played anew`() {
+ assertEquals(Way.Skip(1), QueueSyncRules.way(b, pageUri = c, pagePlaying = true, pageQueued = listOf(a, b)))
+ assertEquals(Way.Play, QueueSyncRules.way(d, pageUri = c, pagePlaying = true, pageQueued = listOf(a, b)))
+ }
+
+ @Test fun `a page already on the song is only kept in step`() {
+ assertEquals(Way.Already, QueueSyncRules.way(a, pageUri = a, pagePlaying = true, pageQueued = listOf(b)))
+ assertEquals(Way.Play, QueueSyncRules.way(a, pageUri = a, pagePlaying = false, pageQueued = listOf(b)))
+ }
+
+ @Test fun `playback is pulled here only before the run's first play`() {
+ assertTrue(QueueSyncRules.pullsHere(firstPlay = true, elsewhere = true))
+ assertFalse(QueueSyncRules.pullsHere(firstPlay = false, elsewhere = true))
+ assertFalse(QueueSyncRules.pullsHere(firstPlay = true, elsewhere = false))
+ }
+}