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 through Spotify Connect

Lelonio0969b4121d3b
diff --git a/.claude/settings.local.json b/.claude/settings.local.json
index 72b5338..c7dd206 100644
--- a/.claude/settings.local.json
+++ b/.claude/settings.local.json
@@ -80,7 +80,9 @@
"Bash(git reset *)",
"Bash(git -c user.name=Emanuele -c [email protected] commit -qm 'Make the player one surface with the now-playing bar *)",
"Bash(git -c user.name=Emanuele -c [email protected] commit -qm 'Seat the sheet on the measured tab bar *)",
- "Bash(git -c user.name=Emanuele -c [email protected] commit -qm 'Give the player sheet its own background *)"
+ "Bash(git -c user.name=Emanuele -c [email protected] commit -qm 'Give the player sheet its own background *)",
+ "Bash(cd \"/Users/emanuele/Progetto *)",
+ "Bash(git -c user.name=Emanuele -c [email protected] commit -qm 'Play through Spotify Connect *)"
]
}
}
diff --git a/app/.cxx/RelWithDebInfo/151m4dr6/arm64-v8a/configure_fingerprint.bin b/app/.cxx/RelWithDebInfo/151m4dr6/arm64-v8a/configure_fingerprint.bin
index 6ee5a6b..52bb80f 100644
--- a/app/.cxx/RelWithDebInfo/151m4dr6/arm64-v8a/configure_fingerprint.bin
+++ b/app/.cxx/RelWithDebInfo/151m4dr6/arm64-v8a/configure_fingerprint.bin
@@ -2,27 +2,27 @@ C/C++ Structured Logl
j
h/Users/emanuele/Progetto Spotify/app/.cxx/RelWithDebInfo/151m4dr6/arm64-v8a/additional_project_files.txtC
A
-?com.android.build.gradle.internal.cxx.io.EncodedFileFingerPrint  �����3  ����3i
+?com.android.build.gradle.internal.cxx.io.EncodedFileFingerPrint  ���3  ����3i
g
-e/Users/emanuele/Progetto Spotify/app/.cxx/RelWithDebInfo/151m4dr6/arm64-v8a/android_gradle_build.json  �����3� ����3n
+e/Users/emanuele/Progetto Spotify/app/.cxx/RelWithDebInfo/151m4dr6/arm64-v8a/android_gradle_build.json  ���3� ����3n
l
-j/Users/emanuele/Progetto Spotify/app/.cxx/RelWithDebInfo/151m4dr6/arm64-v8a/android_gradle_build_mini.json  �����3� �����3[
+j/Users/emanuele/Progetto Spotify/app/.cxx/RelWithDebInfo/151m4dr6/arm64-v8a/android_gradle_build_mini.json  ���3� �����3[
Y
-W/Users/emanuele/Progetto Spotify/app/.cxx/RelWithDebInfo/151m4dr6/arm64-v8a/build.ninja  �����3�� ����3_
+W/Users/emanuele/Progetto Spotify/app/.cxx/RelWithDebInfo/151m4dr6/arm64-v8a/build.ninja  ���3�� ����3_
]
-[/Users/emanuele/Progetto Spotify/app/.cxx/RelWithDebInfo/151m4dr6/arm64-v8a/build.ninja.txt  �����3d
+[/Users/emanuele/Progetto Spotify/app/.cxx/RelWithDebInfo/151m4dr6/arm64-v8a/build.ninja.txt  ���3d
b
-`/Users/emanuele/Progetto Spotify/app/.cxx/RelWithDebInfo/151m4dr6/arm64-v8a/build_file_index.txt  �����3 @ ����3e
+`/Users/emanuele/Progetto Spotify/app/.cxx/RelWithDebInfo/151m4dr6/arm64-v8a/build_file_index.txt  ���3 @ ����3e
c
-a/Users/emanuele/Progetto Spotify/app/.cxx/RelWithDebInfo/151m4dr6/arm64-v8a/compile_commands.json  �����3�� ����3i
+a/Users/emanuele/Progetto Spotify/app/.cxx/RelWithDebInfo/151m4dr6/arm64-v8a/compile_commands.json  ���3�� ����3i
g
-e/Users/emanuele/Progetto Spotify/app/.cxx/RelWithDebInfo/151m4dr6/arm64-v8a/compile_commands.json.bin  �����3 �" ����3o
+e/Users/emanuele/Progetto Spotify/app/.cxx/RelWithDebInfo/151m4dr6/arm64-v8a/compile_commands.json.bin  ���3 �" ����3o
m
-k/Users/emanuele/Progetto Spotify/app/.cxx/RelWithDebInfo/151m4dr6/arm64-v8a/metadata_generation_command.txt  �����3
+k/Users/emanuele/Progetto Spotify/app/.cxx/RelWithDebInfo/151m4dr6/arm64-v8a/metadata_generation_command.txt  ���3
� ����3b
`
-^/Users/emanuele/Progetto Spotify/app/.cxx/RelWithDebInfo/151m4dr6/arm64-v8a/prefab_config.json  �����3  ( ����3g
+^/Users/emanuele/Progetto Spotify/app/.cxx/RelWithDebInfo/151m4dr6/arm64-v8a/prefab_config.json  ���3  ( ����3g
e
-c/Users/emanuele/Progetto Spotify/app/.cxx/RelWithDebInfo/151m4dr6/arm64-v8a/symbol_folder_index.txt  �����3  b ����3D
+c/Users/emanuele/Progetto Spotify/app/.cxx/RelWithDebInfo/151m4dr6/arm64-v8a/symbol_folder_index.txt  ���3  b ����3D
B
-@/Users/emanuele/Progetto Spotify/app/src/main/cpp/CMakeLists.txt  �����3 � �Ȅ��3
\ No newline at end of file
+@/Users/emanuele/Progetto Spotify/app/src/main/cpp/CMakeLists.txt  �Ř��3 � �Ȅ��3
\ No newline at end of file
diff --git a/app/src/main/java/dev/emanuele/spot/nativecore/NativeBridge.kt b/app/src/main/java/dev/emanuele/spot/nativecore/NativeBridge.kt
index 77eaed4..9a52bda 100644
--- a/app/src/main/java/dev/emanuele/spot/nativecore/NativeBridge.kt
+++ b/app/src/main/java/dev/emanuele/spot/nativecore/NativeBridge.kt
@@ -1,5 +1,9 @@
package dev.emanuele.spot.nativecore
+import kotlinx.serialization.builtins.ListSerializer
+import kotlinx.serialization.builtins.serializer
+import kotlinx.serialization.json.Json
+
/**
* Events pushed from the librespot engine. Called on a native tokio worker
* thread, never on the main thread — implementations must marshal themselves.
@@ -63,13 +67,30 @@ object NativeBridge {
listener: NativeEvents,
) = nativeStart(clientId, deviceName, accessToken, credentialsDir, cacheDir, listener)
- fun load(uri: String, startPlaying: Boolean, positionMs: Int = 0) =
- nativeLoad(uri, startPlaying, positionMs)
+ /**
+ * Hands the whole queue to the Connect device, starting at [index].
+ *
+ * A list rather than one track: since the engine went through Spirc, the
+ * queue belongs to the Connect state — it is what the account and every
+ * other device see, and it is Spirc that advances at the end of a track.
+ */
+ fun loadQueue(uris: List<String>, index: Int, startPlaying: Boolean, positionMs: Int = 0) =
+ nativeLoadQueue(
+ Json.encodeToString(ListSerializer(String.serializer()), uris),
+ index,
+ startPlaying,
+ positionMs,
+ )
fun play() = nativePlay()
fun pause() = nativePause()
fun stop() = nativeStop()
fun seek(positionMs: Long) = nativeSeek(positionMs)
+ fun next() = nativeNext()
+ fun previous() = nativePrevious()
+ fun setShuffle(shuffle: Boolean) = nativeSetShuffle(shuffle)
+ fun setRepeat(repeatContext: Boolean, repeatTrack: Boolean) =
+ nativeSetRepeat(repeatContext, repeatTrack)
/** Volume in librespot's raw 0..65535 range. */
var volume: Int
@@ -123,7 +144,16 @@ object NativeBridge {
listener: NativeEvents,
)
- private external fun nativeLoad(uri: String, startPlaying: Boolean, positionMs: Int)
+ private external fun nativeLoadQueue(
+ urisJson: String,
+ index: Int,
+ startPlaying: Boolean,
+ positionMs: Int,
+ )
+ private external fun nativeNext()
+ private external fun nativePrevious()
+ private external fun nativeSetShuffle(shuffle: Boolean)
+ private external fun nativeSetRepeat(repeatContext: Boolean, repeatTrack: Boolean)
private external fun nativePlay()
private external fun nativePause()
private external fun nativeStop()
diff --git a/app/src/main/java/dev/emanuele/spot/playback/LibrespotPlayer.kt b/app/src/main/java/dev/emanuele/spot/playback/LibrespotPlayer.kt
index bd5618d..671f0b0 100644
--- a/app/src/main/java/dev/emanuele/spot/playback/LibrespotPlayer.kt
+++ b/app/src/main/java/dev/emanuele/spot/playback/LibrespotPlayer.kt
@@ -47,10 +47,22 @@ class LibrespotPlayer(
private val fadeIn: () -> Unit,
) : SimpleBasePlayer(looper), NativeEvents {
- /** Loads a track with the fade around it. */
- private fun loadFaded(uri: String, startPlaying: Boolean, positionMs: Int = 0) {
+ /**
+ * Hands the current queue to the engine, with the fade around it.
+ *
+ * The whole list, not the current track: the engine now drives playback
+ * through Spotify Connect, where the queue is part of the state published
+ * to the account. Loading one track at a time would show every other device
+ * a queue with nothing in it, and would take the end-of-track advance away
+ * from the side that owns it.
+ */
+ private fun pushQueue(startPlaying: Boolean, positionMs: Int = 0) {
+ val uris = queue.items.map { it.uri }
+ if (uris.isEmpty()) return
+ val index = queue.currentIndex
fadeOutThen {
- NativeBridge.load(uri, startPlaying, positionMs)
+ runCatching { NativeBridge.loadQueue(uris, index, startPlaying, positionMs) }
+ .onFailure { android.util.Log.e("SpotPlayer", "load failed: ${it.message}") }
if (startPlaying) fadeIn()
}
}
@@ -232,11 +244,32 @@ class LibrespotPlayer(
val target = queue.items.getOrNull(mediaItemIndex)
?: return Futures.immediateVoidFuture()
- if (mediaItemIndex != queue.currentIndex) {
- queue.currentIndex = mediaItemIndex
- loadFaded(target.uri, startPlaying = true, positionMs = newPositionMs.toInt())
- } else {
- NativeBridge.seek(newPositionMs)
+ when {
+ mediaItemIndex == queue.currentIndex -> NativeBridge.seek(newPositionMs)
+
+ // 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.
+ mediaItemIndex == queue.currentIndex + 1 -> {
+ queue.currentIndex = mediaItemIndex
+ fadeOutThen {
+ NativeBridge.next()
+ fadeIn()
+ }
+ }
+
+ mediaItemIndex == queue.currentIndex - 1 -> {
+ queue.currentIndex = mediaItemIndex
+ fadeOutThen {
+ NativeBridge.previous()
+ fadeIn()
+ }
+ }
+
+ else -> {
+ queue.currentIndex = mediaItemIndex
+ pushQueue(startPlaying = true, positionMs = newPositionMs.toInt())
+ }
}
positionMs = newPositionMs
return Futures.immediateVoidFuture()
@@ -273,11 +306,10 @@ class LibrespotPlayer(
// all while paused.
positionMs = startPositionMs
playbackState = Player.STATE_BUFFERING
- NativeBridge.load(
- first.uri,
- startPlaying = playWhenReady,
- positionMs = startPositionMs.toInt(),
- )
+ // `first` is only read to check there is something playable; the engine
+ // is handed the whole list.
+ check(first.uri.isNotEmpty())
+ pushQueue(startPlaying = playWhenReady, positionMs = startPositionMs.toInt())
invalidateState()
return Futures.immediateVoidFuture()
}
@@ -347,10 +379,15 @@ class LibrespotPlayer(
playbackState = Player.STATE_READY
onQueueChanged()
- queue.items.getOrNull(queue.currentIndex)?.let { track ->
- // Paused: an app that starts playing by itself when opened is worse
- // than one that forgets where it was.
- loadFaded(track.uri, startPlaying = false, positionMs = positionMs.toInt())
+ // Paused: an app that starts playing by itself when opened is worse
+ // than one that forgets where it was.
+ //
+ // The load also takes over the Connect device, which is why it is not
+ // done here at all when there is nothing to restore — activating on
+ // launch would pull playback away from whatever the account is actually
+ // playing on.
+ if (queue.items.isNotEmpty()) {
+ pushQueue(startPlaying = false, positionMs = positionMs.toInt())
}
invalidateState()
}
@@ -362,12 +399,22 @@ class LibrespotPlayer(
shuffleEnabled = shuffleModeEnabled
queue.setShuffled(shuffleModeEnabled)
onQueueChanged()
+ // Told to the engine as well: shuffle is part of the published Connect
+ // state, and a device whose local order disagrees with what the account
+ // shows is worse than one that cannot shuffle at all.
+ runCatching { NativeBridge.setShuffle(shuffleModeEnabled) }
invalidateState()
return Futures.immediateVoidFuture()
}
override fun handleSetRepeatMode(repeatMode: @Player.RepeatMode Int): ListenableFuture<*> {
this.repeatMode = repeatMode
+ runCatching {
+ NativeBridge.setRepeat(
+ repeatContext = repeatMode == Player.REPEAT_MODE_ALL,
+ repeatTrack = repeatMode == Player.REPEAT_MODE_ONE,
+ )
+ }
invalidateState()
return Futures.immediateVoidFuture()
}
@@ -382,12 +429,23 @@ class LibrespotPlayer(
// --- NativeEvents: arrives on a tokio worker thread ---
override fun onEvent(type: String, uri: String, positionMs: Long) {
- handler.post { applyEvent(type, positionMs) }
+ handler.post { applyEvent(type, uri, positionMs) }
}
- private fun applyEvent(type: String, eventPositionMs: Long) {
+ private fun applyEvent(type: String, uri: String, eventPositionMs: Long) {
if (released) return
+ // 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 }
+ if (index >= 0 && index != queue.currentIndex) {
+ queue.currentIndex = index
+ positionMs = 0
+ }
+ }
+
when (type) {
"loading" -> {
playbackState = Player.STATE_BUFFERING
@@ -409,48 +467,15 @@ class LibrespotPlayer(
playbackState = Player.STATE_IDLE
playWhenReady = false
}
- "end_of_track" -> {
- advance()
- return
- }
- // The track is region-locked or otherwise unplayable; skipping keeps
- // a bad item in a playlist from stalling the whole queue.
- "unavailable" -> {
- advance()
- return
- }
+ // 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
else -> return
}
invalidateState()
}
- /**
- * Moves to whatever should play next, honouring the repeat mode.
- *
- * Done here rather than left to Media3 because end-of-track comes from the
- * engine, not from a controller command.
- */
- private fun advance() {
- val nextIndex = when {
- repeatMode == Player.REPEAT_MODE_ONE -> queue.currentIndex
- queue.currentIndex + 1 <= queue.items.lastIndex -> queue.currentIndex + 1
- repeatMode == Player.REPEAT_MODE_ALL -> 0
- else -> null
- }
-
- val next = nextIndex?.let(queue.items::getOrNull)
- if (next == null) {
- playbackState = Player.STATE_ENDED
- playWhenReady = false
- } else {
- queue.currentIndex = nextIndex
- positionMs = 0
- playbackState = Player.STATE_BUFFERING
- loadFaded(next.uri, startPlaying = true)
- }
- invalidateState()
- }
-
/**
* @param index part of the uid because Media3 requires uids to be unique
* across the playlist, and a playlist may legitimately contain the same
diff --git a/native/Cargo.lock b/native/Cargo.lock
index 1ad0d12..514c8a8 100644
--- a/native/Cargo.lock
+++ b/native/Cargo.lock
@@ -1129,6 +1129,26 @@ dependencies = [
"tokio",
]
+[[package]]
+name = "librespot-connect"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4b2a21e9e19b906c6676b1a515fc5529d5414f69049f5a167dfb2ea3206e5a27"
+dependencies = [
+ "futures-util",
+ "librespot-core",
+ "librespot-playback",
+ "librespot-protocol",
+ "log",
+ "protobuf",
+ "rand 0.9.5",
+ "serde_json",
+ "thiserror 2.0.19",
+ "tokio",
+ "tokio-stream",
+ "uuid",
+]
+
[[package]]
name = "librespot-core"
version = "0.8.0"
@@ -2317,6 +2337,7 @@ dependencies = [
"futures-util",
"http",
"jni",
+ "librespot-connect",
"librespot-core",
"librespot-metadata",
"librespot-playback",
diff --git a/native/Cargo.toml b/native/Cargo.toml
index 145d57c..db32304 100644
--- a/native/Cargo.toml
+++ b/native/Cargo.toml
@@ -14,6 +14,10 @@ librespot-core = { version = "0.8", default-features = false, features = ["rustl
# No backend feature: audio goes to an AudioTrack via src/sink.rs, so
# rodio and cpal are not built at all.
librespot-playback = { version = "0.8", default-features = false, features = ["rustls-tls-webpki-roots"] }
+# Spotify Connect. The device only appears in the user's account — and plays
+# are only recorded in their history — because this publishes state; nothing
+# about decoding audio requires it.
+librespot-connect = { version = "0.8", default-features = false, features = ["rustls-tls-webpki-roots"] }
librespot-metadata = { version = "0.8", default-features = false, features = ["rustls-tls-webpki-roots"] }
librespot-protocol = { version = "0.8", default-features = false }
protobuf = "3"
diff --git a/native/src/engine.rs b/native/src/engine.rs
index 10435b2..a2531a0 100644
--- a/native/src/engine.rs
+++ b/native/src/engine.rs
@@ -7,9 +7,12 @@
use jni::objects::{GlobalRef, JObject, JValue};
use jni::JavaVM;
+use librespot_connect::{
+ ConnectConfig, LoadRequest, LoadRequestOptions, PlayingTrack, Spirc,
+};
use librespot_core::{
- authentication::Credentials, cache::Cache, config::SessionConfig, session::Session,
- spotify_uri::SpotifyUri,
+ authentication::Credentials, cache::Cache, config::DeviceType, config::SessionConfig,
+ session::Session, spotify_uri::SpotifyUri,
};
use librespot_playback::{
config::{AudioFormat, Bitrate, PlayerConfig},
@@ -35,6 +38,8 @@ pub struct Engine {
session: Session,
player: Arc<Player>,
mixer: Arc<SoftMixer>,
+ /// The Connect device. Every transport command goes through it; see [`load`].
+ spirc: Spirc,
}
/// Errors are flattened to a string because they cross the JNI boundary and the
@@ -179,7 +184,10 @@ pub fn start(
)
.map_err(|e| format!("cache failed: {e}"))?;
- let (session, player) = rt.block_on(async move {
+ // Cloned before the async block takes ownership of the Arc as a `dyn Mixer`.
+ let mixer_for_spirc: Arc<dyn Mixer> = mixer.clone();
+
+ let (session, player, spirc, spirc_task) = rt.block_on(async move {
// Seed the cache with the OAuth credentials, then hand the cached copy
// to `connect` with storing switched off. Letting `connect` store
// instead would overwrite the cache with the handshake's reusable
@@ -192,17 +200,64 @@ pub fn start(
.and_then(|cache| cache.credentials())
.unwrap_or(credentials);
- session
- .connect(credentials, false)
- .await
- .map_err(|e| format!("login failed: {e}"))?;
+ // No `session.connect` here: `Spirc::new` registers its dealer
+ // listeners and then connects the session itself. Connecting first
+ // authenticated twice and left the second attempt reporting "Session is
+ // not connected", which is what this looked like from the outside.
let player = Player::new(player_config, session.clone(), mixer_volume, move || {
Box::new(crate::sink::AndroidSink::new(AudioFormat::S16))
});
- Ok::<_, String>((session, player))
+
+ // Spirc is what makes this a Spotify Connect device: it publishes the
+ // playback state to the account, which is also the only way plays are
+ // recorded in listening history — Spotify counts what a device reports,
+ // not what it decodes. That is why nothing appeared in the history
+ // before this existed.
+ //
+ // It owns the player from here on. Driving `player` directly as well
+ // would play audio the published state knows nothing about, so every
+ // transport command below goes through the Spirc handle instead.
+ let connect_config = ConnectConfig {
+ name: device_name.to_string(),
+ // Smartphone rather than the librespot default of Speaker: the icon
+ // in the device list should match what the user is holding.
+ device_type: DeviceType::Smartphone,
+ // Full scale, matching the mixer. Loudness belongs to the phone's
+ // own volume keys.
+ initial_volume: u16::MAX,
+ ..ConnectConfig::default()
+ };
+
+ let (spirc, spirc_task) = Spirc::new(
+ connect_config,
+ session.clone(),
+ credentials.clone(),
+ player.clone(),
+ mixer_for_spirc,
+ )
+ .await
+ .map_err(|e| format!("connect failed: {e}"))?;
+
+ // Spirc connects with credential storing switched on, which replaces
+ // the cached OAuth blob with the handshake's reusable one. login5 signs
+ // its stored-credential request with the session's client id, so the
+ // two have to agree or every catalogue call comes back BAD_REQUEST —
+ // putting the original back is what keeps the access point usable.
+ if let Some(cache) = session.cache() {
+ cache.save_credentials(&credentials);
+ }
+
+ Ok::<_, String>((session, player, spirc, spirc_task))
})?;
+ // The event loop runs for the life of the engine: it is what answers the
+ // dealer, so without it the device appears once and then goes stale.
+ rt.spawn(async move {
+ spirc_task.await;
+ log::info!("connect device stopped");
+ });
+
spawn_event_pump(&rt, player.clone(), listener, device_name.to_string());
*guard = Some(Engine {
@@ -210,6 +265,7 @@ pub fn start(
session,
player,
mixer,
+ spirc,
});
Ok(())
}
@@ -323,28 +379,86 @@ fn emit(listener: &GlobalRef, kind: &str, uri: &str, position_ms: i64) -> Result
Ok(())
}
-pub fn load(uri: &str, start_playing: bool, position_ms: u32) -> EngineResult<()> {
- let parsed = SpotifyUri::from_uri(uri).map_err(|e| format!("bad uri {uri}: {e}"))?;
- if !parsed.is_playable() {
- return Err(format!("{uri} is not a playable item"));
+/// Hands a whole queue to the Connect device.
+///
+/// A list rather than one track at a time, which is what this did before. Spirc
+/// publishes the queue as well as the current item, so loading track by track
+/// would show the account a device that never has anything coming up — and it
+/// is Spirc, not the caller, that advances at the end of a track.
+///
+/// `index` selects the starting track; anything out of range starts at the
+/// beginning, which is librespot's own behaviour rather than an error.
+pub fn load_queue(
+ uris: Vec<String>,
+ index: u32,
+ start_playing: bool,
+ position_ms: u32,
+) -> EngineResult<()> {
+ if uris.is_empty() {
+ return Err("empty queue".into());
}
- with_engine(|e| e.player.load(parsed, start_playing, position_ms))
+ for uri in &uris {
+ let parsed = SpotifyUri::from_uri(uri).map_err(|e| format!("bad uri {uri}: {e}"))?;
+ if !parsed.is_playable() {
+ return Err(format!("{uri} is not a playable item"));
+ }
+ }
+
+ let options = LoadRequestOptions {
+ start_playing,
+ seek_to: position_ms,
+ playing_track: Some(PlayingTrack::Index(index)),
+ ..LoadRequestOptions::default()
+ };
+
+ with_engine(|e| {
+ // Without this the device is registered but idle, and a load is
+ // ignored: playback belongs to whichever device the account has
+ // active, and taking that over is an explicit step.
+ e.spirc.activate()?;
+ e.spirc.load(LoadRequest::from_tracks(uris, options))
+ })?
+ .map_err(|e| format!("load failed: {e}"))
}
pub fn play() -> EngineResult<()> {
- with_engine(|e| e.player.play())
+ with_engine(|e| e.spirc.play())?.map_err(|e| format!("play failed: {e}"))
}
pub fn pause() -> EngineResult<()> {
- with_engine(|e| e.player.pause())
+ with_engine(|e| e.spirc.pause())?.map_err(|e| format!("pause failed: {e}"))
}
pub fn stop() -> EngineResult<()> {
- with_engine(|e| e.player.stop())
+ // Disconnecting rather than stopping the player: it tells the account this
+ // device has given up playback, which is what makes it disappear from the
+ // device list instead of lingering as a paused phantom.
+ with_engine(|e| e.spirc.disconnect(true))?.map_err(|e| format!("stop failed: {e}"))
}
pub fn seek(position_ms: u32) -> EngineResult<()> {
- with_engine(|e| e.player.seek(position_ms))
+ with_engine(|e| e.spirc.set_position_ms(position_ms))?.map_err(|e| format!("seek failed: {e}"))
+}
+
+pub fn next() -> EngineResult<()> {
+ with_engine(|e| e.spirc.next())?.map_err(|e| format!("next failed: {e}"))
+}
+
+pub fn previous() -> EngineResult<()> {
+ with_engine(|e| e.spirc.prev())?.map_err(|e| format!("previous failed: {e}"))
+}
+
+pub fn set_shuffle(shuffle: bool) -> EngineResult<()> {
+ with_engine(|e| e.spirc.shuffle(shuffle))?.map_err(|e| format!("shuffle failed: {e}"))
+}
+
+/// `repeat_track` takes precedence: the two are separate flags in the protocol.
+pub fn set_repeat(repeat_context: bool, repeat_track: bool) -> EngineResult<()> {
+ with_engine(|e| {
+ e.spirc.repeat_track(repeat_track)?;
+ e.spirc.repeat(repeat_context)
+ })?
+ .map_err(|e| format!("repeat failed: {e}"))
}
/// `volume` is the raw 0..=65535 range librespot uses.
@@ -364,6 +478,10 @@ pub fn is_connected() -> bool {
pub fn shutdown() {
let taken = ENGINE.lock().ok().and_then(|mut g| g.take());
if let Some(engine) = taken {
+ // Told to the account before the socket goes: a device that vanishes
+ // without disconnecting stays in the user's list until it times out.
+ let _ = engine.spirc.disconnect(true);
+ let _ = engine.spirc.shutdown();
engine.player.stop();
engine.session.shutdown();
crate::sink::clear_output();
diff --git a/native/src/ffi.rs b/native/src/ffi.rs
index 3a0979f..c394459 100644
--- a/native/src/ffi.rs
+++ b/native/src/ffi.rs
@@ -108,15 +108,68 @@ pub extern "system" fn Java_dev_emanuele_spot_nativecore_NativeBridge_nativeStar
}
#[no_mangle]
-pub extern "system" fn Java_dev_emanuele_spot_nativecore_NativeBridge_nativeLoad(
+pub extern "system" fn Java_dev_emanuele_spot_nativecore_NativeBridge_nativeLoadQueue(
mut env: JNIEnv,
_class: JClass,
- uri: JString,
+ uris_json: JString,
+ index: jint,
start_playing: jboolean,
position_ms: jint,
) {
- let result = read_string(&mut env, &uri)
- .and_then(|uri| engine::load(&uri, start_playing == JNI_TRUE, position_ms.max(0) as u32));
+ // JSON rather than a jobjectArray: the Kotlin side already serialises track
+ // lists for the catalogue calls, and one decoder is easier to keep correct
+ // than two ways of crossing the same boundary.
+ let result = read_string(&mut env, &uris_json)
+ .and_then(|raw| {
+ serde_json::from_str::<Vec<String>>(&raw).map_err(|e| format!("bad queue: {e}"))
+ })
+ .and_then(|uris| {
+ engine::load_queue(
+ uris,
+ index.max(0) as u32,
+ start_playing == JNI_TRUE,
+ position_ms.max(0) as u32,
+ )
+ });
+ or_throw(&mut env, result);
+}
+
+#[no_mangle]
+pub extern "system" fn Java_dev_emanuele_spot_nativecore_NativeBridge_nativeNext(
+ mut env: JNIEnv,
+ _class: JClass,
+) {
+ let result = engine::next();
+ or_throw(&mut env, result);
+}
+
+#[no_mangle]
+pub extern "system" fn Java_dev_emanuele_spot_nativecore_NativeBridge_nativePrevious(
+ mut env: JNIEnv,
+ _class: JClass,
+) {
+ let result = engine::previous();
+ or_throw(&mut env, result);
+}
+
+#[no_mangle]
+pub extern "system" fn Java_dev_emanuele_spot_nativecore_NativeBridge_nativeSetShuffle(
+ mut env: JNIEnv,
+ _class: JClass,
+ shuffle: jboolean,
+) {
+ let result = engine::set_shuffle(shuffle == JNI_TRUE);
+ or_throw(&mut env, result);
+}
+
+#[no_mangle]
+pub extern "system" fn Java_dev_emanuele_spot_nativecore_NativeBridge_nativeSetRepeat(
+ mut env: JNIEnv,
+ _class: JClass,
+ repeat_context: jboolean,
+ repeat_track: jboolean,
+) {
+ let result = engine::set_repeat(repeat_context == JNI_TRUE, repeat_track == JNI_TRUE);
or_throw(&mut env, result);
}