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.

Keep the engine's running order and the screen's the same one

Lelonioc8c670b62a6f
diff --git a/app/src/main/java/dev/lelonio/square/nativecore/NativeBridge.kt b/app/src/main/java/dev/lelonio/square/nativecore/NativeBridge.kt
index 401b814..8057817 100644
--- a/app/src/main/java/dev/lelonio/square/nativecore/NativeBridge.kt
+++ b/app/src/main/java/dev/lelonio/square/nativecore/NativeBridge.kt
@@ -128,6 +128,18 @@ object NativeBridge {
playAsContext,
)
+ /**
+ * Tells the device a new running order, leaving the current track playing.
+ *
+ * For a shuffle turned on or off under a song: what comes after changes,
+ * the song does not, and a reload would put a gap in the middle of it.
+ */
+ fun setQueueOrder(uris: List<String>, index: Int) =
+ nativeSetQueueOrder(
+ Json.encodeToString(ListSerializer(String.serializer()), uris),
+ index,
+ )
+
fun play() = nativePlay()
fun pause() = nativePause()
fun stop() = nativeStop()
@@ -374,6 +386,7 @@ object NativeBridge {
appVersion: String,
): String
private external fun nativeDeviceId(): String
+ private external fun nativeSetQueueOrder(urisJson: String, index: Int)
private external fun nativePlayingHere(): String
private external fun nativeRemoteState(): String
private external fun nativeRemoteDevices(): String
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 0103604..aa9c9a2 100644
--- a/app/src/main/java/dev/lelonio/square/playback/LibrespotPlayer.kt
+++ b/app/src/main/java/dev/lelonio/square/playback/LibrespotPlayer.kt
@@ -74,6 +74,10 @@ class LibrespotPlayer(
// screen would be someone else's.
val asContext = queue.contextIsOrdered && !queue.isShuffled
+ android.util.Log.i(
+ "SquarePlayer",
+ "load ${uris.size} tracks at $index (playing=$startPlaying, context=$asContext)",
+ )
fadeOutThen {
// Back on the player's looper before anything is read or called.
// The fade runs on its own thread, and everything here — the queue,
@@ -487,6 +491,7 @@ class LibrespotPlayer(
skipPending = false
val target = queue.currentIndex
val from = engineIndex
+ android.util.Log.i("SquarePlayer", "skip settles: engine at $from, wanted $target")
when {
from == target -> {
@@ -890,6 +895,32 @@ class LibrespotPlayer(
// The order on screen is the one the user arranged, so it wins. The cost
// is that the account shows this device as not shuffling.
runCatching { NativeBridge.setShuffle(false) }
+
+ // And the engine is given the new order at once.
+ //
+ // Reordering only this side is what made shuffling break playback: the
+ // engine went on playing the list it was handed, the screen followed
+ // the tracks the engine announced, and the two orders no longer agreed
+ // on what came next. A skip then asked for the track after the one on
+ // screen while the engine stepped through its own list, so tracks
+ // appeared to be missed — and it survived shuffle being turned off
+ // again, because turning it off is another reorder this side only.
+ //
+ // Handed over as an order rather than as a load. A load would restart
+ // the decoder, and a reordering of what comes later has no business
+ // interrupting the song that is playing.
+ if (queue.items.isNotEmpty()) {
+ engineIndex = queue.currentIndex
+ runCatching {
+ NativeBridge.setQueueOrder(queue.items.map { it.uri }, queue.currentIndex)
+ }
+ .onFailure {
+ // Left for the next skip to sort out, which rebuilds the
+ // queue wholesale: better a load then than a wrong order now.
+ android.util.Log.w("SquarePlayer", "could not reorder: ${it.message}")
+ engineQueueStale = true
+ }
+ }
invalidateState()
return Futures.immediateVoidFuture()
}
@@ -931,6 +962,7 @@ class LibrespotPlayer(
val next = queue.currentIndex + 1
if (!engineQueueStale || next > queue.items.lastIndex) return false
if (!queue.items[next].queued) return false
+ android.util.Log.i("SquarePlayer", "taking over for a queued track at $next")
requestSkipTo(next, 0L)
return true
}
@@ -972,6 +1004,10 @@ class LibrespotPlayer(
// 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.
+ android.util.Log.i(
+ "SquarePlayer",
+ "following the engine to $index ($type), screen was at ${queue.currentIndex}",
+ )
queue.currentIndex = index
skipInFlight = false
positionMs = 0
diff --git a/native/src/engine.rs b/native/src/engine.rs
index 97e49d8..799c730 100644
--- a/native/src/engine.rs
+++ b/native/src/engine.rs
@@ -1338,6 +1338,18 @@ pub fn load_queue(
// ignored: playback belongs to whichever device the account has
// active, and taking that over is an explicit step.
e.spirc.activate()?;
+ // Shuffle off before the list goes in, every time.
+ //
+ // The order handed over here is the order the app is showing, shuffled
+ // or not: the app draws its own random order and the engine is only
+ // asked to play the result. But the Connect state carries a shuffle
+ // flag of the account's, which another client may have set and which
+ // survives in the state this device restores, and when a context
+ // resolves with that flag on librespot shuffles it again for itself.
+ // The engine then played its own order while the screen followed
+ // another, so a skip stepped somewhere the listener could not see and
+ // whole tracks appeared to be missed.
+ e.spirc.shuffle(false)?;
e.spirc.load(request)
})?
.inspect_err(|_| {
@@ -1650,6 +1662,28 @@ pub fn take_over() -> EngineResult<()> {
with_bundle(|e| e.spirc.activate())?.map_err(|e| format!("could not take over: {e}"))
}
+/// Hands the device a new running order without touching what is playing.
+///
+/// The app owns the order — it draws its own shuffle — and when the listener
+/// turns that on or off the list changes under a track that is still playing.
+/// Reloading the queue would say the same thing at the cost of a gap in the
+/// song, for a change that is only ever about what comes after it.
+pub fn set_queue_order(uris: Vec<String>, index: u32) -> EngineResult<()> {
+ if uris.is_empty() {
+ return Err("empty queue".into());
+ }
+ let at = (index as usize).min(uris.len() - 1);
+ let prev = uris[..at].to_vec();
+ let next = uris[at + 1..].to_vec();
+
+ if let Ok(mut stored) = QUEUE.lock() {
+ *stored = uris;
+ }
+
+ with_bundle(|e| e.spirc.set_queue_tracks(prev, next))?
+ .map_err(|e| format!("queue order failed: {e}"))
+}
+
pub fn set_shuffle(shuffle: bool) -> EngineResult<()> {
with_bundle(|e| e.spirc.shuffle(shuffle))?.map_err(|e| format!("shuffle failed: {e}"))
}
diff --git a/native/src/ffi.rs b/native/src/ffi.rs
index d7957af..a6cb38a 100644
--- a/native/src/ffi.rs
+++ b/native/src/ffi.rs
@@ -532,6 +532,29 @@ pub extern "system" fn Java_dev_lelonio_square_nativecore_NativeBridge_nativeDev
guard_string(&mut env, "DeviceId", crate::remote::device_id)
}
+/// A new running order for the queue already loaded; see `engine::set_queue_order`.
+#[no_mangle]
+pub extern "system" fn Java_dev_lelonio_square_nativecore_NativeBridge_nativeSetQueueOrder(
+ mut env: JNIEnv,
+ _class: JClass,
+ uris_json: JString,
+ index: jint,
+) {
+ // JSON, like the load above and for the same reason.
+ let raw = match read_string(&mut env, &uris_json) {
+ Ok(value) => value,
+ Err(message) => {
+ let _ = env.throw_new(EXCEPTION, message);
+ return;
+ }
+ };
+ guard(&mut env, "SetQueueOrder", || {
+ serde_json::from_str::<Vec<String>>(&raw)
+ .map_err(|e| format!("bad queue: {e}"))
+ .and_then(|uris| engine::set_queue_order(uris, index.max(0) as u32))
+ });
+}
+
/// What this device itself is playing, straight from its Connect state.
#[no_mangle]
pub extern "system" fn Java_dev_lelonio_square_nativecore_NativeBridge_nativePlayingHere(
diff --git a/native/vendor/README.md b/native/vendor/README.md
index b13cdd6..be2fc94 100644
--- a/native/vendor/README.md
+++ b/native/vendor/README.md
@@ -173,3 +173,17 @@ The track list is there for the contexts Spotify makes rather than stores. A
daily mix, a radio, "Pop Mix" resolve to nothing for a client that is not
Spotify's own, and the only copy of that queue in existence here is the one the
account handed the device to play.
+
+### The patch: a new running order, without a reload
+
+`Spirc::set_queue_tracks(prev, next)` replaces what comes before and after the
+current track and publishes the queue revision, leaving playback alone.
+
+The app draws its own shuffle: the order on screen is the order the device is
+given. Turning shuffle on or off therefore changes the list under a song that is
+still playing, and upstream has only one way to say so — load the queue again,
+which restarts the decoder. The listener heard a gap in the middle of the track
+for a change that was only ever about the tracks after it.
+
+`state::metadata` and its `Metadata` trait are `pub(crate)` for this, so a track
+built in `spirc.rs` can be stamped with the context it belongs to.
diff --git a/native/vendor/librespot-connect/src/spirc.rs b/native/vendor/librespot-connect/src/spirc.rs
index fa5cae6..783baf3 100644
--- a/native/vendor/librespot-connect/src/spirc.rs
+++ b/native/vendor/librespot-connect/src/spirc.rs
@@ -27,12 +27,15 @@ use crate::{
},
state::{
context::{ContextType, ResetContext},
+ metadata::Metadata,
provider::IsProvider,
{ConnectConfig, ConnectState},
},
};
use futures_util::StreamExt;
use librespot_protocol::context_page::ContextPage;
+use librespot_protocol::player::ProvidedTrack;
+use uuid::Uuid;
use protobuf::MessageField;
use std::{
future::Future,
@@ -132,6 +135,11 @@ enum SpircCommand {
RepeatTrack(bool),
Disconnect { pause: bool },
SetPosition(u32),
+ /// LOCAL PATCH: replace what comes before and after the current track.
+ SetQueueTracks {
+ prev: Vec<String>,
+ next: Vec<String>,
+ },
SetVolume(u16),
Activate,
Transfer(Option<TransferRequest>),
@@ -412,6 +420,21 @@ impl Spirc {
Ok(self.commands.send(SpircCommand::Shuffle(shuffle))?)
}
+ /// LOCAL PATCH: hands over a new running order, without touching what is
+ /// playing.
+ ///
+ /// The owner of this handle keeps its own list and its own idea of random,
+ /// and when that order changes the device has to be told or the two stop
+ /// agreeing about what comes next. Loading the list again would say the
+ /// same thing, but a load restarts the decoder and the listener hears a gap
+ /// in the middle of the song — for a change that is only about the tracks
+ /// after this one.
+ pub fn set_queue_tracks(&self, prev: Vec<String>, next: Vec<String>) -> Result<(), Error> {
+ Ok(self
+ .commands
+ .send(SpircCommand::SetQueueTracks { prev, next })?)
+ }
+
/// Repeats the playback context according to the value.
///
/// Does nothing if we are not the active device.
@@ -795,6 +818,7 @@ impl SpircTask {
SpircCommand::Repeat(repeat) => self.handle_repeat_context(repeat)?,
SpircCommand::RepeatTrack(repeat) => self.handle_repeat_track(repeat),
SpircCommand::SetPosition(position) => self.handle_seek(position),
+ SpircCommand::SetQueueTracks { prev, next } => self.handle_set_queue_tracks(prev, next),
SpircCommand::SetVolume(volume) => self.set_volume(volume),
SpircCommand::Load(command) => self.handle_load(command, None, None).await?,
};
@@ -802,6 +826,31 @@ impl SpircTask {
self.notify().await
}
+ /// LOCAL PATCH: see [`Spirc::set_queue_tracks`].
+ fn handle_set_queue_tracks(&mut self, prev: Vec<String>, next: Vec<String>) {
+ let context_uri = self.connect_state.context_uri().clone();
+ let track_of = |uri: &String| {
+ let mut track = ProvidedTrack {
+ uri: uri.clone(),
+ uid: Uuid::new_v4().as_simple().to_string(),
+ provider: "context".to_string(),
+ ..Default::default()
+ };
+ if !context_uri.is_empty() {
+ track.set_entity_uri(context_uri.clone());
+ track.set_context_uri(context_uri.clone());
+ }
+ track
+ };
+
+ self.connect_state
+ .set_prev_tracks(prev.iter().map(track_of).collect());
+ self.connect_state.clear_next_tracks();
+ self.connect_state
+ .set_next_tracks(next.iter().map(track_of).collect());
+ self.connect_state.update_queue_revision();
+ }
+
fn handle_player_event(&mut self, event: PlayerEvent) -> Result<(), Error> {
if let PlayerEvent::TrackChanged { audio_item } = event {
self.connect_state.update_duration(audio_item.duration_ms);
diff --git a/native/vendor/librespot-connect/src/state.rs b/native/vendor/librespot-connect/src/state.rs
index b4ee61b..3ab0048 100644
--- a/native/vendor/librespot-connect/src/state.rs
+++ b/native/vendor/librespot-connect/src/state.rs
@@ -1,6 +1,8 @@
pub(super) mod context;
mod handle;
-mod metadata;
+// LOCAL PATCH: visible to the crate, so spirc can stamp a track it builds
+// itself with the context it belongs to; see `Spirc::set_queue_tracks`.
+pub(crate) mod metadata;
mod options;
pub(super) mod provider;
mod restrictions;
diff --git a/native/vendor/librespot-connect/src/state/metadata.rs b/native/vendor/librespot-connect/src/state/metadata.rs
index 82318da..ecd330e 100644
--- a/native/vendor/librespot-connect/src/state/metadata.rs
+++ b/native/vendor/librespot-connect/src/state/metadata.rs
@@ -38,7 +38,9 @@ macro_rules! metadata_entry {
/// Allows easy access of known metadata fields
#[allow(dead_code)]
-pub(super) trait Metadata {
+// LOCAL PATCH: `pub(crate)` so spirc can stamp a track it builds itself; see
+// `Spirc::set_queue_tracks`.
+pub(crate) trait Metadata {
fn metadata(&self) -> &HashMap<String, String>;
fn metadata_mut(&mut self) -> &mut HashMap<String, String>;