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.

Downloads keep playing offline, and shuffle keeps its order

Leloniod6d3d8243c7c
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 b96166f..db319eb 100644
--- a/app/src/main/java/dev/lelonio/square/nativecore/NativeBridge.kt
+++ b/app/src/main/java/dev/lelonio/square/nativecore/NativeBridge.kt
@@ -234,7 +234,11 @@ object NativeBridge {
*
* Blocks on the handshake. Never call it from the main thread.
*/
- fun reconnect() = nativeReconnect()
+ fun reconnect() {
+ nativeReconnect()
+ // A successful call may have rebuilt the downloads-only player.
+ dev.lelonio.square.playback.OfflineMode.setNoSession(isOffline)
+ }
// --- The account's other devices ---
//
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 f7898ff..ba3f862 100644
--- a/app/src/main/java/dev/lelonio/square/playback/LibrespotPlayer.kt
+++ b/app/src/main/java/dev/lelonio/square/playback/LibrespotPlayer.kt
@@ -462,7 +462,7 @@ class LibrespotPlayer(
* the queue instead of stepping through it.
*/
private val deviceGone: Boolean
- get() = OfflineMode.active.value ||
+ get() = runCatching { NativeBridge.isOffline }.getOrDefault(false) ||
runCatching { NativeBridge.spircLost }.getOrDefault(false)
/** Set while a reconnection is in flight, so a burst of taps starts one. */
@@ -543,6 +543,12 @@ class LibrespotPlayer(
* ahead at least reaches the engine's own fallback, which stops the sound.
*/
private fun withDevice(then: () -> Unit) {
+ // Keep downloaded tracks moving while Spotify is unavailable. A
+ // reconnect on every skip destroys the working downloads-only player.
+ if (OfflineMode.active.value && runCatching { NativeBridge.isOffline }.getOrDefault(false)) {
+ handler.post { if (!released) then() }
+ return
+ }
if (!deviceGone) {
handler.post { if (!released) then() }
return
@@ -1517,7 +1523,7 @@ class LibrespotPlayer(
skipInFlight = false
if (type == "playing") sounding = true
if (type == "playing" || type == "loading") positionMs = 0
- } else if (!skipPending && type == "playing") {
+ } else if (!skipPending && (type == "playing" || type == "paused")) {
// 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
@@ -1585,7 +1591,7 @@ class LibrespotPlayer(
// tracks overlap by the length the listener asked for. With the
// setting at zero there is nothing to run up to, and the track
// is left to end on its own.
- if (dev.lelonio.square.playback.OfflineMode.active.value) {
+ if (runCatching { NativeBridge.isOffline }.getOrDefault(false)) {
val length = queue.items.getOrNull(queue.currentIndex)?.durationMs ?: 0L
val fade = crossfade.durationMs().toLong()
if (fade > 0 && length > 0 && length - eventPositionMs in 1..fade) {
@@ -1640,7 +1646,7 @@ class LibrespotPlayer(
// two was skipped without ever being heard, which is what "it
// sometimes jumps straight to the next one" was.
if (uri == advancedFrom) return
- if (dev.lelonio.square.playback.OfflineMode.active.value) {
+ if (runCatching { NativeBridge.isOffline }.getOrDefault(false)) {
advanceOffline(early = false)
}
return
diff --git a/app/src/main/java/dev/lelonio/square/playback/NetworkWatch.kt b/app/src/main/java/dev/lelonio/square/playback/NetworkWatch.kt
index 67cbab5..a0c10ed 100644
--- a/app/src/main/java/dev/lelonio/square/playback/NetworkWatch.kt
+++ b/app/src/main/java/dev/lelonio/square/playback/NetworkWatch.kt
@@ -70,9 +70,12 @@ class NetworkWatch(context: Context, private val scope: CoroutineScope) {
/** What was last written to the log; see [evaluate]. */
private var lastReport: String? = null
+ private var lastConnected: Boolean? = null
private fun evaluate() {
val connected = connected()
+ val returned = connected && lastConnected == false
+ lastConnected = connected
// Only when it changes. The system reports every step in signal
// strength as a new set of capabilities, so this was a line every second
// or two, and it pushed out of the phone's log the very playback lines
@@ -84,7 +87,9 @@ class NetworkWatch(context: Context, private val scope: CoroutineScope) {
}
pending?.cancel()
if (connected) {
- OfflineMode.setNoSession(false)
+ // Signal-strength updates do not prove that Spotify's session is
+ // back. Only an actual network return starts a reconnection.
+ if (returned) OfflineMode.setNoSession(false)
OfflineMode.setSlow(false)
return
}
diff --git a/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt b/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt
index a3636ef..ed3a7c3 100644
--- a/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt
@@ -1900,7 +1900,7 @@ fun SquareApp(
// selection rather than the context.
onPlay(
tracks,
- 0,
+ if (tracks.isEmpty()) 0 else tracks.indices.random(),
page.uri,
false,
source,
diff --git a/native/vendor/README.md b/native/vendor/README.md
index 7a75513..db8a864 100644
--- a/native/vendor/README.md
+++ b/native/vendor/README.md
@@ -308,5 +308,7 @@ 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.
+The backing context is replaced with the same running order, at the current
+track, without loading the decoder. Otherwise refilling the next-track window,
+or disabling the Connect shuffle flag, restores the old order (#39). The new
+successor is preloaded and the state is marked for publication.
diff --git a/native/vendor/librespot-connect/src/spirc.rs b/native/vendor/librespot-connect/src/spirc.rs
index 1bf77a1..9676d42 100644
--- a/native/vendor/librespot-connect/src/spirc.rs
+++ b/native/vendor/librespot-connect/src/spirc.rs
@@ -27,15 +27,12 @@ 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,
@@ -889,7 +886,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::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?,
};
@@ -898,28 +895,22 @@ impl SpircTask {
}
/// 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_set_queue_tracks(&mut self, prev: Vec<String>, next: Vec<String>) -> Result<(), Error> {
+ let current = self.connect_state.current_track(|track| track.uri.clone());
+ if current.is_empty() {
+ return Ok(());
+ }
+ let index = prev.len();
+ let tracks = prev.into_iter().chain(std::iter::once(current)).chain(next)
+ .collect::<Vec<_>>();
+ // Replace the backing context too: refill and shuffle(false) otherwise
+ // restore the old order after the next-tracks window has been consumed.
+ self.context_resolver.clear();
+ self.connect_state.replace_running_order(tracks, index)?;
+ self.update_state = true;
+ // The old successor may already be buffered. Warm the new one instead.
+ self.handle_preload_next_track();
+ Ok(())
}
fn handle_player_event(&mut self, event: PlayerEvent) -> Result<(), Error> {
diff --git a/native/vendor/librespot-connect/src/state/context.rs b/native/vendor/librespot-connect/src/state/context.rs
index 838b104..f38f4ef 100644
--- a/native/vendor/librespot-connect/src/state/context.rs
+++ b/native/vendor/librespot-connect/src/state/context.rs
@@ -30,6 +30,44 @@ pub struct StateContext {
pub index: ContextIndex,
}
+#[cfg(test)]
+mod running_order_tests {
+ use super::*;
+ use crate::{core::{Session, config::SessionConfig}, state::ConnectConfig};
+
+ #[tokio::test]
+ async fn reordered_context_survives_refill_and_shuffle_reset() {
+ let session = Session::new(SessionConfig::default(), None);
+ let mut state = ConnectState::new(ConnectConfig::default(), &session);
+ // More than the 80-track next window, with the same song twice.
+ let original = (0..100).map(|i| {
+ format!("spotify:track:{:022}", i % 99)
+ }).collect::<Vec<_>>();
+ state.update_context(Context {
+ uri: Some("spotify:playlist:test".into()),
+ pages: vec![original.clone().into()],
+ ..Default::default()
+ }, ContextType::Default).unwrap();
+ state.reset_playback_to_position(Some(0)).unwrap();
+ let mut reordered = original.clone();
+ reordered[1..].reverse();
+ state.replace_running_order(reordered.clone(), 0).unwrap();
+ // The app keeps the account's shuffle flag off. That must not undo
+ // its order, including after the initial next window is exhausted.
+ state.handle_shuffle(false).unwrap();
+ assert_eq!(state.current_track(|t| t.uri.clone()), reordered[0]);
+ for expected in &reordered[1..] {
+ state.next_track().unwrap();
+ assert_eq!(&state.current_track(|t| t.uri.clone()), expected);
+ }
+ assert!(state.next_track().unwrap().is_none());
+ state.replace_running_order(original.clone(), 17).unwrap();
+ assert_eq!(state.current_track(|t| t.uri.clone()), original[17]);
+ state.next_track().unwrap();
+ assert_eq!(state.current_track(|t| t.uri.clone()), original[18]);
+ }
+}
+
#[derive(Default, Debug, Copy, Clone, PartialEq, Hash, Eq)]
pub enum ContextType {
#[default]
@@ -65,6 +103,21 @@ fn page_url_to_uri(page_url: &str) -> String {
}
impl ConnectState {
+ /// Replaces the running order without asking the decoder to reload.
+ pub fn replace_running_order(&mut self, uris: Vec<String>, index: usize) -> Result<(), Error> {
+ let uri = self.context_uri().clone();
+ self.update_context(Context {
+ url: Some(format!("context://{uri}")),
+ uri: Some(uri),
+ pages: vec![uris.into()],
+ ..Default::default()
+ }, ContextType::Default)?;
+ self.set_active_context(ContextType::Default);
+ self.reset_playback_to_position(Some(index))?;
+ self.update_queue_revision();
+ Ok(())
+ }
+
pub fn find_index_in_context<F: Fn(&ProvidedTrack) -> bool>(
ctx: &StateContext,
f: F,