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.

Play a queued track after the current one, not at the end

Lelonio92a4f569cce0
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 b274e05..1f32513 100644
--- a/app/src/main/java/dev/lelonio/square/playback/LibrespotPlayer.kt
+++ b/app/src/main/java/dev/lelonio/square/playback/LibrespotPlayer.kt
@@ -100,6 +100,7 @@ class LibrespotPlayer(
)
}
.onFailure { android.util.Log.e("SquarePlayer", "load failed: ${it.message}") }
+ .onSuccess { engineQueueStale = false }
if (wanted) fadeIn()
}
}
@@ -236,6 +237,17 @@ class LibrespotPlayer(
*/
private var engineIndex = -1
+ /**
+ * True when the list the engine was given no longer matches ours.
+ *
+ * Spirc holds the track list it was loaded with and advances through it by
+ * itself; there is no way to hand it an insertion. So a local edit is
+ * invisible to it until the whole queue is loaded again, and until then its
+ * "next" is not ours — which is why a skip cannot be delegated while this
+ * is set.
+ */
+ private var engineQueueStale = false
+
/** A skip the user has made and the engine has not been told about yet. */
private var skipPending = false
@@ -290,7 +302,7 @@ class LibrespotPlayer(
// A step either way is a skip, and Spirc has to be the one making
// it: reloading the queue for a skip would restart the context and
// show up on other devices as a new session rather than a next.
- from >= 0 && target == from + 1 -> fadeOutThen {
+ !engineQueueStale && from >= 0 && target == from + 1 -> fadeOutThen {
handler.post {
if (released) return@post
runCatching { NativeBridge.next() }
@@ -298,7 +310,7 @@ class LibrespotPlayer(
}
}
- from >= 0 && target == from - 1 -> fadeOutThen {
+ !engineQueueStale && from >= 0 && target == from - 1 -> fadeOutThen {
handler.post {
if (released) return@post
runCatching { NativeBridge.previous() }
@@ -450,6 +462,7 @@ class LibrespotPlayer(
mediaItems: List<MediaItem>,
): ListenableFuture<*> {
queue.addFromMediaItems(index, mediaItems)
+ engineQueueStale = true
reapplyShuffle()
onQueueChanged()
invalidateState()
@@ -458,6 +471,7 @@ class LibrespotPlayer(
override fun handleRemoveMediaItems(fromIndex: Int, toIndex: Int): ListenableFuture<*> {
queue.remove(fromIndex, toIndex)
+ engineQueueStale = true
reapplyShuffle()
onQueueChanged()
invalidateState()
@@ -470,6 +484,7 @@ class LibrespotPlayer(
newIndex: Int,
): ListenableFuture<*> {
queue.move(fromIndex, toIndex, newIndex)
+ engineQueueStale = true
reapplyShuffle()
onQueueChanged()
invalidateState()
@@ -569,6 +584,21 @@ class LibrespotPlayer(
handler.post { applyEvent(type, uri, positionMs) }
}
+ /**
+ * Jumps to the next track if it is one the engine cannot know about.
+ *
+ * Called as the current track ends, not when the track was queued: a reload
+ * mid-playback restarts what is playing, while here there is a moment of
+ * silence to do it in anyway.
+ */
+ private fun takeOverForQueued(): Boolean {
+ val next = queue.currentIndex + 1
+ if (!engineQueueStale || next > queue.items.lastIndex) return false
+ if (!queue.items[next].queued) return false
+ requestSkipTo(next, 0L)
+ return true
+ }
+
private fun applyEvent(type: String, uri: String, eventPositionMs: Long) {
if (released) return
@@ -639,7 +669,16 @@ class LibrespotPlayer(
// Both used to advance the queue from here. The engine does it now
// — it owns the queue — so acting on them as well would skip two
// tracks for every one that ended.
- "end_of_track", "unavailable" -> return
+ //
+ // Except for a track put here by "add to queue": the engine's list
+ // does not contain it, so left alone it would play the playlist's
+ // own next one and the queued track would never be heard. Taking
+ // over reloads the queue, which is the only way to tell Spirc about
+ // an insertion.
+ "end_of_track", "unavailable" -> {
+ takeOverForQueued()
+ return
+ }
else -> return
}
invalidateState()
diff --git a/app/src/main/java/dev/lelonio/square/playback/PlayQueue.kt b/app/src/main/java/dev/lelonio/square/playback/PlayQueue.kt
index e7e3375..5dc6eed 100644
--- a/app/src/main/java/dev/lelonio/square/playback/PlayQueue.kt
+++ b/app/src/main/java/dev/lelonio/square/playback/PlayQueue.kt
@@ -5,6 +5,7 @@ import androidx.media3.common.MediaItem
import dev.lelonio.square.ui.EXTRA_CONTEXT_LABEL
import dev.lelonio.square.ui.EXTRA_CONTEXT_ORDERED
import dev.lelonio.square.ui.EXTRA_CONTEXT_URI
+import dev.lelonio.square.ui.EXTRA_PLAY_NEXT
/**
* The queue the engine plays through.
@@ -29,6 +30,16 @@ class PlayQueue {
val artist: String,
val durationMs: Long,
val artworkUri: Uri?,
+ /**
+ * Put here by "add to queue" rather than by the list this came from.
+ *
+ * Kept on the track so the insertion point never has to be remembered:
+ * a queued run is simply the tracks marked this way sitting right after
+ * the current one, and playing past them removes them from it by
+ * itself. Not persisted — a queue survives a restart, the distinction
+ * between "queued" and "in the playlist" does not.
+ */
+ val queued: Boolean = false,
)
private val _items = mutableListOf<Track>()
@@ -118,6 +129,51 @@ class PlayQueue {
clearShuffle()
}
+ /**
+ * Inserts tracks to play right after the current one.
+ *
+ * Queueing two tracks in a row has to play them in the order they were
+ * queued, so the second goes *after* the first rather than in front of it:
+ * the insertion point is the end of the run of already-queued tracks
+ * following the current one, which is why [Track.queued] exists.
+ *
+ * Unlike [add] this keeps a shuffled queue shuffled. Dropping the
+ * permutation would make the caller re-shuffle, and the track just placed
+ * behind the current one would land somewhere random — the one thing the
+ * gesture promises not to do.
+ */
+ fun insertNext(tracks: List<Track>) {
+ if (tracks.isEmpty()) return
+ val marked = tracks.map { it.copy(queued = true) }
+ val at = nextInsertIndex()
+
+ val order = originalIndices
+ val original = originalOrder
+ if (order != null && original != null) {
+ // Appended to the pre-shuffle order rather than inserted into it:
+ // every existing index in the permutation then stays valid.
+ originalOrder = original + marked
+ originalIndices = order.toMutableList().apply {
+ addAll(at, (original.size until original.size + marked.size).toList())
+ }
+ }
+
+ _items.addAll(at, marked)
+
+ // The queue is no longer the context in its own order, so it must not
+ // be handed to the engine as one: played that way Spotify supplies the
+ // playlist's own track list and the inserted track is nowhere in it.
+ contextIsOrdered = false
+ }
+
+ /** Just past the queued run that follows the current track. */
+ fun nextInsertIndex(): Int {
+ if (_items.isEmpty()) return 0
+ var at = (currentIndex + 1).coerceAtMost(_items.size)
+ while (at < _items.size && _items[at].queued) at++
+ return at
+ }
+
fun remove(fromIndex: Int, toIndex: Int) {
val from = fromIndex.coerceIn(0, _items.size)
val to = toIndex.coerceIn(from, _items.size)
@@ -214,9 +270,18 @@ class PlayQueue {
contextLabel = label
}
- /** Insert controller-supplied items; see [replaceFromMediaItems] for the id rule. */
+ /**
+ * Insert controller-supplied items; see [replaceFromMediaItems] for the id
+ * rule.
+ *
+ * An item asking to play next ignores the index the controller gave: a
+ * `MediaController` lives in another process and cannot know where the
+ * queued run ends, so it states the intent and the queue decides the place.
+ */
fun addFromMediaItems(index: Int, mediaItems: List<MediaItem>) {
- add(index, mediaItems.mapNotNull(::toTrack))
+ val tracks = mediaItems.mapNotNull(::toTrack)
+ if (tracks.isNotEmpty() && tracks.all { it.queued }) insertNext(tracks)
+ else add(index, tracks)
}
private fun toTrack(item: MediaItem): Track? {
@@ -228,6 +293,7 @@ class PlayQueue {
artist = metadata.artist?.toString().orEmpty(),
durationMs = metadata.durationMs ?: 0L,
artworkUri = metadata.artworkUri,
+ queued = metadata.extras?.getBoolean(EXTRA_PLAY_NEXT) == true,
)
}
}
diff --git a/app/src/main/java/dev/lelonio/square/ui/MainActivity.kt b/app/src/main/java/dev/lelonio/square/ui/MainActivity.kt
index abe904f..9ea78dc 100644
--- a/app/src/main/java/dev/lelonio/square/ui/MainActivity.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/MainActivity.kt
@@ -135,7 +135,10 @@ class MainActivity : ComponentActivity() {
private fun enqueue(track: CatalogTrack) {
val player = controller ?: return
val wasEmpty = player.mediaItemCount == 0
- player.addMediaItem(toMediaItem(track))
+ // The index is a formality: the item asks to play next and the queue in
+ // the service picks the place, because only it knows where the run of
+ // already-queued tracks ends.
+ player.addMediaItem(toMediaItem(track, playNext = true))
if (wasEmpty) {
player.prepare()
player.play()
@@ -147,6 +150,7 @@ class MainActivity : ComponentActivity() {
contextUri: String? = null,
asContext: Boolean = false,
contextLabel: String = "",
+ playNext: Boolean = false,
): MediaItem =
MediaItem.Builder()
// The media id carries the Spotify URI; PlayQueue refuses anything else.
@@ -168,6 +172,7 @@ class MainActivity : ComponentActivity() {
if (contextLabel.isNotEmpty()) {
putString(EXTRA_CONTEXT_LABEL, contextLabel)
}
+ if (playNext) putBoolean(EXTRA_PLAY_NEXT, true)
},
)
.build(),
@@ -181,5 +186,11 @@ const val EXTRA_CONTEXT_URI = "dev.lelonio.square.CONTEXT_URI"
/** Whether that queue is the context in its own order; see SquareApp's `onPlay`. */
const val EXTRA_CONTEXT_ORDERED = "dev.lelonio.square.CONTEXT_ORDERED"
+/**
+ * Set by "add to queue": play this right after the current track rather than at
+ * the end of the queue.
+ */
+const val EXTRA_PLAY_NEXT = "dev.lelonio.square.PLAY_NEXT"
+
/** What to show the listener: "Playlist · Estate 2025", "Ricerca". */
const val EXTRA_CONTEXT_LABEL = "dev.lelonio.square.CONTEXT_LABEL"