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 the song that is on the screen

Lelonio323cd06055d6
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 b85a24b..d9b36de 100644
--- a/app/src/main/java/dev/lelonio/square/playback/LibrespotPlayer.kt
+++ b/app/src/main/java/dev/lelonio/square/playback/LibrespotPlayer.kt
@@ -475,6 +475,21 @@ class LibrespotPlayer(
private var engineIndex = -1
+ /**
+ * Whether the track the queue is on has actually started.
+ *
+ * A load is not a change of track. The engine fetches what is coming while
+ * the current song plays, and each of those arrives here as a load: taken
+ * as "the engine has moved on", the screen ran forward a song or two and
+ * the one just started vanished from under the listener.
+ *
+ * A load still counts while nothing is sounding, and that case is the one
+ * loads were followed for: a run of tracks the account cannot play is
+ * loaded one after another with no play in between, and ignoring those
+ * left the app behind the speaker.
+ */
+ private var sounding = false
+
/**
* True when the list the engine was given no longer matches ours.
*
@@ -534,11 +549,24 @@ class LibrespotPlayer(
skipInFlight = true
handler.removeCallbacks(settleSkip)
handler.postDelayed(settleSkip, delay)
+ // Held until the engine says it is on the track that was asked for.
+ //
+ // Cleared as soon as the command went out, the events still coming in
+ // about the track being left were taken as the truth, and the screen
+ // walked backwards to the song the listener had just skipped. The
+ // timeout is the way out of a command that never lands.
+ handler.removeCallbacks(skipGaveUp)
+ handler.postDelayed(skipGaveUp, SKIP_CONFIRM_MS)
+ }
+
+ /** The engine never confirmed the skip; stop ignoring what it says. */
+ private val skipGaveUp = Runnable {
+ skipPending = false
+ skipInFlight = false
}
private val settleSkip = Runnable {
if (released) return@Runnable
- skipPending = false
val target = queue.currentIndex
val from = engineIndex
@@ -551,7 +579,9 @@ class LibrespotPlayer(
// accepted by a dead device and discarded, and the old track would
// play on. The queue is pushed instead, which rebuilds the device
// first and then loads the track that was asked for.
- deviceGone -> pushQueue(startPlaying = playWhenReady, positionMs = 0)
+ deviceGone -> {
+ pushQueue(startPlaying = playWhenReady, positionMs = 0)
+ }
// 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
@@ -572,7 +602,9 @@ class LibrespotPlayer(
}
}
- else -> pushQueue(startPlaying = playWhenReady, positionMs = positionMs.toInt())
+ else -> {
+ pushQueue(startPlaying = playWhenReady, positionMs = positionMs.toInt())
+ }
}
}
@@ -729,6 +761,7 @@ class LibrespotPlayer(
// A new queue: whatever the engine was playing is no longer at any
// index of this one.
engineIndex = -1
+ sounding = false
// Shuffle before picking the track to load: with the mode on, the tapped
// track moves to the front and the rest are reordered behind it.
reapplyShuffle()
@@ -828,6 +861,7 @@ class LibrespotPlayer(
if (released || queue.items.isEmpty()) return
engineQueueStale = true
engineIndex = -1
+ sounding = false
this.positionMs = positionMs
wantPlay = playing
pushQueue(startPlaying = playing, positionMs = positionMs.toInt())
@@ -838,6 +872,7 @@ class LibrespotPlayer(
queue.replace(emptyList(), 0)
wantPlay = false
engineIndex = -1
+ sounding = false
engineQueueStale = false
skipPending = false
skipInFlight = false
@@ -890,6 +925,7 @@ class LibrespotPlayer(
queue.replace(tracks, 0)
engineIndex = -1
+ sounding = false
shuffleOrder?.let(queue::applyShuffleOrder)
queue.currentIndex = index.coerceIn(0, queue.items.lastIndex)
@@ -1071,11 +1107,17 @@ class LibrespotPlayer(
private fun applyEvent(type: String, uri: String, eventPositionMs: Long) {
if (released) return
+ // Nothing is coming out of the speaker any more, so the next load is a
+ // real move rather than a head start on what is coming.
+ if (type == "stopped" || type == "end_of_track" || type == "unavailable") {
+ sounding = false
+ }
+
// The engine decides what plays next now, so the current index is
// followed rather than set: an advance, a remote skip from another
// device and a local one all arrive here the same way.
if (uri.isNotEmpty()) {
- val index = queue.items.indexOfFirst { it.uri == uri }
+ val index = queue.nearestIndexOf(uri, engineIndex.takeIf { it >= 0 } ?: queue.currentIndex)
if (index < 0 && (type == "playing" || type == "loading") && unknownAsked != uri) {
// Not ours: somebody else chose it. Asked for once per track,
// and only on a track that is actually starting, so a position
@@ -1087,26 +1129,29 @@ class LibrespotPlayer(
unknownAsked = null
engineIndex = index
if (index == queue.currentIndex) {
+ // The engine is where it was asked to be.
+ skipPending = false
+ handler.removeCallbacks(skipGaveUp)
skipInFlight = false
+ if (type == "playing") sounding = true
if (type == "playing" || type == "loading") positionMs = 0
- } else if (
- !skipPending &&
- (type == "playing" || (!skipInFlight && type == "loading"))
- ) {
+ } else if (!skipPending && type == "playing") {
// The engine is the truth about what is coming out of the
// speaker. While a skip is on its way its events are about
// the track being left, and following them dragged the
// screen backwards — but once nothing is outstanding, the
// screen was simply wrong to disagree.
//
- // Loading counts, not only playing: a run of tracks the
- // account cannot play — region-locked, delisted — is
- // skipped by the engine one after another, and each of
- // those is a load with no play. Following only plays left
- // the app three songs behind what was in the speaker,
- // which is exactly how the two came apart.
+ // Only what is playing. A load is not a track change:
+ // the engine fetches what is coming next while the current
+ // song plays, and following those walked the screen one or
+ // two songs ahead of the speaker. A run of tracks the
+ // account cannot play still lands here, because each of
+ // those ends in the engine playing something and that is
+ // the event this follows.
queue.currentIndex = index
skipInFlight = false
+ sounding = type == "playing"
positionMs = 0
}
}
@@ -1282,6 +1327,15 @@ class LibrespotPlayer(
*/
const val SKIP_SETTLE_MS = 220L
+ /**
+ * How long a skip is given to land before its events count again.
+ *
+ * Long enough for a slow load — the network is the reason this exists —
+ * and short enough that a command lost on the way does not leave the
+ * screen ignoring the engine for ever.
+ */
+ const val SKIP_CONFIRM_MS = 8_000L
+
/** Ducked volume, as a fraction of the current one. */
const val DUCK_FACTOR = 0.3
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 56d4d07..02ab68f 100644
--- a/app/src/main/java/dev/lelonio/square/playback/PlayQueue.kt
+++ b/app/src/main/java/dev/lelonio/square/playback/PlayQueue.kt
@@ -233,7 +233,22 @@ class PlayQueue {
contextLabel = mediaItems.firstNotNullOfOrNull {
it.mediaMetadata.extras?.getString(EXTRA_CONTEXT_LABEL)
}.orEmpty()
- replace(mediaItems.mapNotNull(::toTrack), startIndex)
+ // The index has to be carried across the filter, not handed over as
+ // it arrived.
+ //
+ // Items without a Spotify uri are dropped — a local file, an advert,
+ // anything the engine cannot be asked to play — and every drop above
+ // the chosen track pulls it one place further down a list that has not
+ // moved on screen. Tapping the third song and hearing the fifth is
+ // that, and it is consistent per playlist because the same rows are
+ // dropped every time.
+ val tracks = ArrayList<Track>(mediaItems.size)
+ var chosen = 0
+ mediaItems.forEachIndexed { position, item ->
+ if (position == startIndex) chosen = tracks.size
+ toTrack(item)?.let(tracks::add)
+ }
+ replace(tracks, chosen)
}
/**
@@ -298,6 +313,32 @@ class PlayQueue {
return names.zip(uris) { name, uri -> dev.lelonio.square.data.CatalogArtist(name, uri) }
}
+ /**
+ * Where a uri is in this queue, counted from where the queue already is.
+ *
+ * A song can be in a playlist twice, and albums repeat across a queue built
+ * from several of them. Asked for the first match, a queue told "the engine
+ * is playing X" would jump to whichever X came first — which is what made
+ * the screen walk backwards to a song played twenty minutes ago while the
+ * speaker carried on. The nearest one is the one it means.
+ *
+ * Returns -1 when the uri is not here at all, which is a real answer: it
+ * means another device chose something outside this queue.
+ */
+ fun nearestIndexOf(uri: String, from: Int): Int {
+ var best = -1
+ var bestDistance = Int.MAX_VALUE
+ items.forEachIndexed { index, track ->
+ if (track.uri != uri) return@forEachIndexed
+ val distance = kotlin.math.abs(index - from)
+ if (distance < bestDistance) {
+ best = index
+ bestDistance = distance
+ }
+ }
+ return best
+ }
+
private fun toTrack(item: MediaItem): Track? {
val uri = item.mediaId.takeIf { it.startsWith("spotify:") } ?: return null
val metadata = item.mediaMetadata
diff --git a/native/vendor/librespot-playback/src/player.rs b/native/vendor/librespot-playback/src/player.rs
index e2bb350..717976c 100644
--- a/native/vendor/librespot-playback/src/player.rs
+++ b/native/vendor/librespot-playback/src/player.rs
@@ -799,6 +799,22 @@ enum PlayerState {
}
impl PlayerState {
+ /// LOCAL PATCH: where the track had got to, for reloading it after a
+ /// failure. Zero when nothing is loaded, which is the right answer for a
+ /// reload that will start from the beginning anyway.
+ fn stream_position_ms(&self) -> u32 {
+ use self::PlayerState::*;
+ match *self {
+ Playing {
+ stream_position_ms, ..
+ }
+ | Paused {
+ stream_position_ms, ..
+ } => stream_position_ms,
+ _ => 0,
+ }
+ }
+
fn is_playing(&self) -> bool {
use self::PlayerState::*;
match *self {
@@ -1664,13 +1680,16 @@ impl Future for PlayerInternal {
}
}
Err(e) => {
+ // LOCAL PATCH: a failure is not the
+ // end of the song; see reload_track.
error!(
- "Skipping to next track, unable to decode samples for track <{track_id:?}>: {e:?}"
+ "unable to decode samples for track <{track_id:?}>: {e:?}"
);
- self.send_event(PlayerEvent::EndOfTrack {
+ self.reload_track(
track_id,
play_request_id,
- })
+ new_stream_position_ms,
+ );
}
}
}
@@ -1679,13 +1698,11 @@ impl Future for PlayerInternal {
self.handle_packet(result, normalisation_factor);
}
Err(e) => {
- error!(
- "Skipping to next track, unable to get next packet for track <{track_id:?}>: {e:?}"
- );
- self.send_event(PlayerEvent::EndOfTrack {
- track_id,
- play_request_id,
- })
+ // LOCAL PATCH: a failure is not the end of the
+ // song; see reload_track.
+ error!("unable to get next packet for track <{track_id:?}>: {e:?}");
+ let position_ms = self.state.stream_position_ms();
+ self.reload_track(track_id, play_request_id, position_ms);
}
}
} else {
@@ -2701,6 +2718,43 @@ impl PlayerInternal {
.retain(|sender| sender.send(event.clone()).is_ok());
}
+ /// LOCAL PATCH: puts a failed track back on, from where it stopped.
+ ///
+ /// Upstream answers a read or decode failure with `EndOfTrack`, and Spirc
+ /// answers *that* by playing the next song — so a stumble on the network
+ /// looks exactly like a song reaching its end, and the queue walks forward
+ /// on its own. Two failures in a row and the listener is two songs along
+ /// from what they chose, which is what this is here to stop.
+ ///
+ /// The difference that matters is between a track that cannot be played and
+ /// one that did not load: the first is answered with `Unavailable` further
+ /// up, and skipping it is right. This is the second, and the only correct
+ /// answer to it is to try again — the song is there, and the listener asked
+ /// for it.
+ fn reload_track(&mut self, track_id: SpotifyUri, play_request_id: u64, position_ms: u32) {
+ let start_playback = self.state.is_playing();
+ self.send_event(PlayerEvent::Loading {
+ track_id: track_id.clone(),
+ play_request_id,
+ position_ms,
+ });
+
+ let loader = self.load_track(track_id.clone(), position_ms);
+ let loader = Box::pin(
+ async move {
+ tokio::time::sleep(LOAD_RETRY_BACKOFF).await;
+ loader.await
+ }
+ .fuse(),
+ );
+ self.state = PlayerState::Loading {
+ track_id,
+ play_request_id,
+ start_playback,
+ loader,
+ };
+ }
+
fn load_track(
&mut self,
spotify_uri: SpotifyUri,