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 up with the taps, keep the playlist, and stop dying on a panic

Lelonio5e5b5e6a7d6a
diff --git a/app/.cxx/Debug/286k5v33/arm64-v8a/configure_fingerprint.bin b/app/.cxx/Debug/286k5v33/arm64-v8a/configure_fingerprint.bin
index cb23c03..a3cdbb5 100644
--- a/app/.cxx/Debug/286k5v33/arm64-v8a/configure_fingerprint.bin
+++ b/app/.cxx/Debug/286k5v33/arm64-v8a/configure_fingerprint.bin
@@ -2,27 +2,27 @@ C/C++ Structured Logc
a
_/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/additional_project_files.txtC
A
-?com.android.build.gradle.internal.cxx.io.EncodedFileFingerPrint  ��ٲ�3  ��߈�3`
+?com.android.build.gradle.internal.cxx.io.EncodedFileFingerPrint  ҏ˴�3  ��߈�3`
^
-\/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/android_gradle_build.json  ��ٲ�3� ��߈�3e
+\/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/android_gradle_build.json  ӏ˴�3� ��߈�3e
c
-a/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/android_gradle_build_mini.json  ��ٲ�3� ��߈�3R
+a/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/android_gradle_build_mini.json  ӏ˴�3� ��߈�3R
P
-N/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/build.ninja  ��ٲ�3� ��߈�3V
+N/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/build.ninja  ӏ˴�3� ��߈�3V
T
-R/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/build.ninja.txt  ��ٲ�3[
+R/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/build.ninja.txt  ӏ˴�3[
Y
-W/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/build_file_index.txt  ��ٲ�3 @ ��߈�3\
+W/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/build_file_index.txt  ӏ˴�3 @ ��߈�3\
Z
-X/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/compile_commands.json  ��ٲ�3֚ ��߈�3`
+X/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/compile_commands.json  ӏ˴�3֚ ��߈�3`
^
-\/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/compile_commands.json.bin  ��ٲ�3 �" ��߈�3f
+\/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/compile_commands.json.bin  ӏ˴�3 �" ��߈�3f
d
-b/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/metadata_generation_command.txt  ��ٲ�3
+b/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/metadata_generation_command.txt  ӏ˴�3
� ��߈�3Y
W
-U/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/prefab_config.json  ��ٲ�3  ( ��߈�3^
+U/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/prefab_config.json  ӏ˴�3  ( ��߈�3^
\
-Z/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/symbol_folder_index.txt  ��ٲ�3  Y ��߈�3D
+Z/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/symbol_folder_index.txt  ӏ˴�3  Y ��߈�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/data/PlaybackStore.kt b/app/src/main/java/dev/emanuele/spot/data/PlaybackStore.kt
index 6e0d810..a72f692 100644
--- a/app/src/main/java/dev/emanuele/spot/data/PlaybackStore.kt
+++ b/app/src/main/java/dev/emanuele/spot/data/PlaybackStore.kt
@@ -20,6 +20,12 @@ data class SavedPlayback(
val index: Int,
val positionMs: Long,
val repeatMode: Int = 0,
+ /** The playlist or album the queue came from, when it came from one. */
+ val contextUri: String? = null,
+ /** Whether the queue is that context in its own order. */
+ val contextOrdered: Boolean = false,
+ /** What the player shows as the source: "Playlist · Estate 2025". */
+ val contextLabel: String = "",
)
/**
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 7b3c1a4..d8ef90a 100644
--- a/app/src/main/java/dev/emanuele/spot/playback/LibrespotPlayer.kt
+++ b/app/src/main/java/dev/emanuele/spot/playback/LibrespotPlayer.kt
@@ -68,28 +68,40 @@ class LibrespotPlayer(
val uris = queue.items.map { it.uri }
if (uris.isEmpty()) return
val index = queue.currentIndex
+ val contextUri = queue.contextUri.orEmpty()
+ // Only when the queue is that context in its own order, and not while
+ // shuffled: the engine would then play Spotify's order and the list on
+ // screen would be someone else's.
+ val asContext = queue.contextIsOrdered && !queue.isShuffled
+
fadeOutThen {
- // Read now, not when this was scheduled. The fade takes a moment,
- // and a tap on a track while paused arrives as "load this" followed
- // immediately by "play": with the flag frozen at schedule time the
- // load went out as paused, the play landed before it, and the track
- // sat there selected and silent.
- val wanted = startPlaying || playWhenReady
- runCatching {
- NativeBridge.loadQueue(
- uris,
- index,
- wanted,
- positionMs,
- queue.contextUri.orEmpty(),
- // Only when the queue is that context in its own order, and
- // not while shuffled: the engine would then play Spotify's
- // order and the list on screen would be someone else's.
- playAsContext = queue.contextIsOrdered && !queue.isShuffled,
- )
+ // Back on the player's looper before anything is read or called.
+ // The fade runs on its own thread, and everything here — the queue,
+ // playWhenReady, the engine's own idea of what is loaded — belongs
+ // to the looper. Reading it from the fade thread is a race, and a
+ // race in the middle of a track change is exactly the rare crash
+ // that skipping quickly could produce.
+ handler.post {
+ if (released) return@post
+ // Read now, not when this was scheduled. The fade takes a
+ // moment, and a tap on a track while paused arrives as "load
+ // this" followed immediately by "play": with the flag frozen at
+ // schedule time the load went out as paused, the play landed
+ // before it, and the track sat there selected and silent.
+ val wanted = startPlaying || playWhenReady
+ runCatching {
+ NativeBridge.loadQueue(
+ uris,
+ index,
+ wanted,
+ positionMs,
+ contextUri,
+ playAsContext = asContext,
+ )
+ }
+ .onFailure { android.util.Log.e("SpotPlayer", "load failed: ${it.message}") }
+ if (wanted) fadeIn()
}
- .onFailure { android.util.Log.e("SpotPlayer", "load failed: ${it.message}") }
- if (wanted) fadeIn()
}
}
@@ -196,6 +208,76 @@ class LibrespotPlayer(
cachedPlaylist = null
}
+ /**
+ * Where the engine actually is in the queue; -1 until it says.
+ *
+ * Kept apart from [PlayQueue.currentIndex], which now moves as soon as the
+ * user asks rather than when the engine catches up.
+ */
+ private var engineIndex = -1
+
+ /** A skip the user has made and the engine has not been told about yet. */
+ private var skipPending = false
+
+ /**
+ * Moves to a track, without making the user wait for the engine.
+ *
+ * Every skip used to be a command of its own: ten taps were ten loads, each
+ * behind its own fade, and the engine spent seconds working through a queue
+ * of decisions the user had already changed their mind about. Worse, the
+ * screen only moved when the engine did, so a fast run of skips felt stuck.
+ *
+ * Now the queue position moves immediately — the screen follows the taps —
+ * and the engine is told once the tapping stops. What it is told depends on
+ * where it ended up: one step either way is a real skip, which keeps the
+ * context playing on the account and on other devices; anything further is
+ * a load at the target, which is one request instead of a dozen.
+ */
+ private fun requestSkipTo(index: Int, positionMs: Long) {
+ queue.currentIndex = index.coerceIn(0, maxOf(0, queue.items.lastIndex))
+ this.positionMs = positionMs
+ playbackState = Player.STATE_BUFFERING
+ skipPending = true
+ invalidateState()
+
+ handler.removeCallbacks(settleSkip)
+ handler.postDelayed(settleSkip, SKIP_SETTLE_MS)
+ }
+
+ private val settleSkip = Runnable {
+ if (released) return@Runnable
+ skipPending = false
+ val target = queue.currentIndex
+ val from = engineIndex
+
+ when {
+ from == target -> {
+ if (positionMs > 0) NativeBridge.seek(positionMs)
+ }
+
+ // 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 {
+ handler.post {
+ if (released) return@post
+ runCatching { NativeBridge.next() }
+ fadeIn()
+ }
+ }
+
+ from >= 0 && target == from - 1 -> fadeOutThen {
+ handler.post {
+ if (released) return@post
+ runCatching { NativeBridge.previous() }
+ fadeIn()
+ }
+ }
+
+ else -> pushQueue(startPlaying = playWhenReady, positionMs = positionMs.toInt())
+ }
+ }
+
/**
* Restores the shuffled order after the queue has been rebuilt.
*
@@ -269,36 +351,16 @@ class LibrespotPlayer(
newPositionMs: Long,
seekCommand: @Player.Command Int,
): ListenableFuture<*> {
- val target = queue.items.getOrNull(mediaItemIndex)
- ?: return Futures.immediateVoidFuture()
-
- 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()
- }
- }
+ queue.items.getOrNull(mediaItemIndex) ?: return Futures.immediateVoidFuture()
- else -> {
- queue.currentIndex = mediaItemIndex
- pushQueue(startPlaying = true, positionMs = newPositionMs.toInt())
- }
+ if (mediaItemIndex == queue.currentIndex && !skipPending) {
+ NativeBridge.seek(newPositionMs)
+ positionMs = newPositionMs
+ invalidateState()
+ return Futures.immediateVoidFuture()
}
+
+ requestSkipTo(mediaItemIndex, newPositionMs)
positionMs = newPositionMs
return Futures.immediateVoidFuture()
}
@@ -309,6 +371,9 @@ class LibrespotPlayer(
startPositionMs: Long,
): ListenableFuture<*> {
queue.replaceFromMediaItems(mediaItems, startIndex)
+ // A new queue: whatever the engine was playing is no longer at any
+ // index of this one.
+ engineIndex = -1
// 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()
@@ -393,10 +458,21 @@ class LibrespotPlayer(
index: Int,
positionMs: Long,
repeatMode: @Player.RepeatMode Int,
+ /** The playlist or album the queue came from; see PlayQueue. */
+ contextUri: String?,
+ contextIsOrdered: Boolean,
+ contextLabel: String,
) {
if (tracks.isEmpty()) return
+ // Put back before the queue is loaded: the load itself hands the
+ // context to the engine, and a restored session with no context is one
+ // whose listens are filed under nothing and whose player has no source
+ // to show.
+ queue.restoreContext(contextUri, contextIsOrdered, contextLabel)
+
queue.replace(tracks, 0)
+ engineIndex = -1
shuffleOrder?.let(queue::applyShuffleOrder)
queue.currentIndex = index.coerceIn(0, queue.items.lastIndex)
@@ -449,6 +525,7 @@ class LibrespotPlayer(
override fun handleRelease(): ListenableFuture<*> {
released = true
+ handler.removeCallbacks(settleSkip)
focus.release()
NativeBridge.shutdown()
return Futures.immediateVoidFuture()
@@ -468,9 +545,15 @@ class LibrespotPlayer(
// 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
+ if (index >= 0) {
+ engineIndex = index
+ // Not while the user is mid-skip: those events describe the
+ // track being left, and adopting them would drag the screen
+ // back to it between taps.
+ if (!skipPending && index != queue.currentIndex) {
+ queue.currentIndex = index
+ positionMs = 0
+ }
}
}
@@ -494,6 +577,7 @@ class LibrespotPlayer(
onPlaybackActive(false)
}
"position" -> {
+ if (skipPending) return
positionMs = eventPositionMs
}
"stopped" -> {
@@ -545,6 +629,14 @@ class LibrespotPlayer(
.build()
private companion object {
+ /**
+ * How long skips are gathered for before the engine is told.
+ *
+ * Long enough that a run of taps becomes one decision, short enough
+ * that a single skip does not feel delayed.
+ */
+ const val SKIP_SETTLE_MS = 220L
+
/** Ducked volume, as a fraction of the current one. */
const val DUCK_FACTOR = 0.3
diff --git a/app/src/main/java/dev/emanuele/spot/playback/PlayQueue.kt b/app/src/main/java/dev/emanuele/spot/playback/PlayQueue.kt
index 6a153c1..5030587 100644
--- a/app/src/main/java/dev/emanuele/spot/playback/PlayQueue.kt
+++ b/app/src/main/java/dev/emanuele/spot/playback/PlayQueue.kt
@@ -201,6 +201,19 @@ class PlayQueue {
var contextLabel: String = ""
private set
+ /**
+ * Puts back a context read from disk.
+ *
+ * The queue survives a restart and the context did not, so a paused song
+ * came back belonging to nothing: no source in the player, and a listen
+ * that Spotify would file outside the playlist it actually came from.
+ */
+ fun restoreContext(uri: String?, ordered: Boolean, label: String) {
+ contextUri = uri
+ contextIsOrdered = ordered
+ contextLabel = label
+ }
+
/** Insert controller-supplied items; see [replaceFromMediaItems] for the id rule. */
fun addFromMediaItems(index: Int, mediaItems: List<MediaItem>) {
add(index, mediaItems.mapNotNull(::toTrack))
diff --git a/app/src/main/java/dev/emanuele/spot/playback/PlaybackService.kt b/app/src/main/java/dev/emanuele/spot/playback/PlaybackService.kt
index 0f937fc..2c56715 100644
--- a/app/src/main/java/dev/emanuele/spot/playback/PlaybackService.kt
+++ b/app/src/main/java/dev/emanuele/spot/playback/PlaybackService.kt
@@ -196,6 +196,9 @@ class PlaybackService : MediaSessionService() {
index = saved.index,
positionMs = saved.positionMs,
repeatMode = saved.repeatMode,
+ contextUri = saved.contextUri,
+ contextIsOrdered = saved.contextOrdered,
+ contextLabel = saved.contextLabel,
)
android.util.Log.i(TAG, "restored ${saved.tracks.size} tracks at ${saved.index}")
}
@@ -256,6 +259,9 @@ class PlaybackService : MediaSessionService() {
index = queue.currentIndex,
positionMs = player.currentPosition.coerceAtLeast(0),
repeatMode = player.repeatMode,
+ contextUri = queue.contextUri,
+ contextOrdered = queue.contextIsOrdered,
+ contextLabel = queue.contextLabel,
),
)
}
diff --git a/native/Cargo.toml b/native/Cargo.toml
index db32304..4c64be9 100644
--- a/native/Cargo.toml
+++ b/native/Cargo.toml
@@ -47,4 +47,11 @@ opt-level = 3
lto = "thin"
codegen-units = 1
strip = "symbols"
-panic = "abort"
+# Deliberately unwinding, not aborting.
+#
+# With `abort`, any panic anywhere in the engine — a poisoned mutex, an
+# arithmetic edge in a decoder — takes the whole app down with no message the
+# user can act on. Unwinding lets the JNI boundary turn a panic into an
+# ordinary Java exception (see ffi::guard) and lets a panic on one of
+# librespot's own worker threads kill that task instead of the process.
+panic = "unwind"
diff --git a/native/src/ffi.rs b/native/src/ffi.rs
index e1b015d..1c1bfc2 100644
--- a/native/src/ffi.rs
+++ b/native/src/ffi.rs
@@ -42,6 +42,46 @@ fn or_throw<T: Default>(env: &mut JNIEnv, result: engine::EngineResult<T>) -> T
}
}
+
+/// Runs `f`, turning a panic into a Java exception rather than an abort.
+///
+/// The Rust side owns audio decoding, the Connect state machine and a good deal
+/// of reverse-engineered parsing, and a panic in any of it used to end the
+/// process: the crash was a track change away and left nothing to read. A
+/// panic is still a bug, but it should cost the action, not the app.
+fn guard<T: Default>(
+ env: &mut JNIEnv,
+ what: &str,
+ f: impl FnOnce() -> engine::EngineResult<T>,
+) -> T {
+ match std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) {
+ Ok(result) => or_throw(env, result),
+ Err(_) => {
+ // The payload is not logged: a panic message can carry whatever was
+ // being processed, and that is the user's listening.
+ log::error!("panic in {what}");
+ let _ = env.throw_new(EXCEPTION, format!("{what} failed"));
+ T::default()
+ }
+ }
+}
+
+/// [guard] for the calls that answer with a string.
+fn guard_string(
+ env: &mut JNIEnv,
+ what: &str,
+ f: impl FnOnce() -> engine::EngineResult<String>,
+) -> jstring {
+ match std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) {
+ Ok(result) => string_or_throw(env, result),
+ Err(_) => {
+ log::error!("panic in {what}");
+ let _ = env.throw_new(EXCEPTION, format!("{what} failed"));
+ JObject::null().into_raw() as jstring
+ }
+ }
+}
+
fn read_string(env: &mut JNIEnv, s: &JString) -> engine::EngineResult<String> {
env.get_string(s)
.map(|v| v.into())
@@ -54,8 +94,7 @@ pub extern "system" fn Java_dev_emanuele_spot_nativecore_NativeBridge_nativeInit
_class: JClass,
context: JObject,
) {
- let result = engine::init_android_context(&context);
- or_throw(&mut env, result);
+ guard(&mut env, "InitContext", || engine::init_android_context(&context));
}
/// Register the Kotlin `AudioOutput` the sink writes PCM to.
@@ -68,11 +107,11 @@ pub extern "system" fn Java_dev_emanuele_spot_nativecore_NativeBridge_nativeSetA
_class: JClass,
output: JObject,
) {
- let result = env
+ // Read outside the guard: these borrow `env`, and the guard borrows it too.
+ let output = env
.new_global_ref(&output)
- .map_err(|e| format!("failed to pin the audio output: {e}"))
- .map(sink::set_output);
- or_throw(&mut env, result);
+ .map_err(|e| format!("failed to pin the audio output: {e}"));
+ guard(&mut env, "SetAudioOutput", || output.map(sink::set_output));
}
#[no_mangle]
@@ -87,16 +126,32 @@ pub extern "system" fn Java_dev_emanuele_spot_nativecore_NativeBridge_nativeStar
language: JString,
listener: JObject,
) {
- let result = (|| {
- let client_id = read_string(&mut env, &client_id)?;
- let device_name = read_string(&mut env, &device_name)?;
- let access_token = read_string(&mut env, &access_token)?;
- let credentials_dir = read_string(&mut env, &credentials_dir)?;
- let cache_dir = read_string(&mut env, &cache_dir)?;
- let language = read_string(&mut env, &language).unwrap_or_default();
- let listener = env
- .new_global_ref(&listener)
- .map_err(|e| format!("failed to pin listener: {e}"))?;
+ // Every argument is read before the guard: reading borrows `env`, and so
+ // does the guard itself.
+ let arguments: engine::EngineResult<(
+ String,
+ String,
+ String,
+ String,
+ String,
+ String,
+ jni::objects::GlobalRef,
+ )> = (|| {
+ Ok((
+ read_string(&mut env, &client_id)?,
+ read_string(&mut env, &device_name)?,
+ read_string(&mut env, &access_token)?,
+ read_string(&mut env, &credentials_dir)?,
+ read_string(&mut env, &cache_dir)?,
+ read_string(&mut env, &language).unwrap_or_default(),
+ env.new_global_ref(&listener)
+ .map_err(|e| format!("failed to pin listener: {e}"))?,
+ ))
+ })();
+
+ guard(&mut env, "Start", || {
+ let (client_id, device_name, access_token, credentials_dir, cache_dir, language, listener) =
+ arguments?;
engine::start(
&client_id,
&device_name,
@@ -106,8 +161,7 @@ pub extern "system" fn Java_dev_emanuele_spot_nativecore_NativeBridge_nativeStar
&language,
listener,
)
- })();
- or_throw(&mut env, result);
+ });
}
#[no_mangle]
@@ -125,11 +179,17 @@ pub extern "system" fn Java_dev_emanuele_spot_nativecore_NativeBridge_nativeLoad
// lists for the catalogue calls, and one decoder is easier to keep correct
// than two ways of crossing the same boundary.
let context = read_string(&mut env, &context_uri).unwrap_or_default();
- 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| {
+ let raw = match read_string(&mut env, &uris_json) {
+ Ok(value) => value,
+ Err(message) => {
+ let _ = env.throw_new(EXCEPTION, message);
+ return;
+ }
+ };
+ guard(&mut env, "LoadQueue", || {
+ 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,
@@ -138,8 +198,8 @@ pub extern "system" fn Java_dev_emanuele_spot_nativecore_NativeBridge_nativeLoad
context,
play_as_context == JNI_TRUE,
)
- });
- or_throw(&mut env, result);
+ })
+ });
}
#[no_mangle]
@@ -147,8 +207,7 @@ 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);
+ guard(&mut env, "Next", || engine::next());
}
#[no_mangle]
@@ -156,8 +215,7 @@ pub extern "system" fn Java_dev_emanuele_spot_nativecore_NativeBridge_nativePrev
mut env: JNIEnv,
_class: JClass,
) {
- let result = engine::previous();
- or_throw(&mut env, result);
+ guard(&mut env, "Previous", || engine::previous());
}
#[no_mangle]
@@ -166,8 +224,7 @@ pub extern "system" fn Java_dev_emanuele_spot_nativecore_NativeBridge_nativeSetS
_class: JClass,
shuffle: jboolean,
) {
- let result = engine::set_shuffle(shuffle == JNI_TRUE);
- or_throw(&mut env, result);
+ guard(&mut env, "SetShuffle", || engine::set_shuffle(shuffle == JNI_TRUE));
}
#[no_mangle]
@@ -177,8 +234,7 @@ pub extern "system" fn Java_dev_emanuele_spot_nativecore_NativeBridge_nativeSetR
repeat_context: jboolean,
repeat_track: jboolean,
) {
- let result = engine::set_repeat(repeat_context == JNI_TRUE, repeat_track == JNI_TRUE);
- or_throw(&mut env, result);
+ guard(&mut env, "SetRepeat", || engine::set_repeat(repeat_context == JNI_TRUE, repeat_track == JNI_TRUE));
}
#[no_mangle]
@@ -186,8 +242,7 @@ pub extern "system" fn Java_dev_emanuele_spot_nativecore_NativeBridge_nativePlay
mut env: JNIEnv,
_class: JClass,
) {
- let result = engine::play();
- or_throw(&mut env, result);
+ guard(&mut env, "Play", || engine::play());
}
#[no_mangle]
@@ -195,8 +250,7 @@ pub extern "system" fn Java_dev_emanuele_spot_nativecore_NativeBridge_nativePaus
mut env: JNIEnv,
_class: JClass,
) {
- let result = engine::pause();
- or_throw(&mut env, result);
+ guard(&mut env, "Pause", || engine::pause());
}
#[no_mangle]
@@ -204,8 +258,7 @@ pub extern "system" fn Java_dev_emanuele_spot_nativecore_NativeBridge_nativeStop
mut env: JNIEnv,
_class: JClass,
) {
- let result = engine::stop();
- or_throw(&mut env, result);
+ guard(&mut env, "Stop", || engine::stop());
}
#[no_mangle]
@@ -214,8 +267,7 @@ pub extern "system" fn Java_dev_emanuele_spot_nativecore_NativeBridge_nativeSeek
_class: JClass,
position_ms: jlong,
) {
- let result = engine::seek(position_ms.clamp(0, u32::MAX as jlong) as u32);
- or_throw(&mut env, result);
+ guard(&mut env, "Seek", || engine::seek(position_ms.clamp(0, u32::MAX as jlong) as u32));
}
#[no_mangle]
@@ -224,8 +276,7 @@ pub extern "system" fn Java_dev_emanuele_spot_nativecore_NativeBridge_nativeSetV
_class: JClass,
volume: jint,
) {
- let result = engine::set_volume(volume.clamp(0, u16::MAX as jint) as u16);
- or_throw(&mut env, result);
+ guard(&mut env, "SetVolume", || engine::set_volume(volume.clamp(0, u16::MAX as jint) as u16));
}
#[no_mangle]
@@ -233,8 +284,7 @@ pub extern "system" fn Java_dev_emanuele_spot_nativecore_NativeBridge_nativeVolu
mut env: JNIEnv,
_class: JClass,
) -> jint {
- let result = engine::volume().map(|v| v as jint);
- or_throw(&mut env, result)
+ guard(&mut env, "Volume", || engine::volume().map(|v| v as jint))
}
#[no_mangle]
@@ -256,8 +306,8 @@ pub extern "system" fn Java_dev_emanuele_spot_nativecore_NativeBridge_nativeUser
mut env: JNIEnv,
_class: JClass,
) -> jstring {
- let result = catalog::username();
- string_or_throw(&mut env, result)
+ guard_string(&mut env, "Username", || catalog::username())
+
}
#[no_mangle]
@@ -265,8 +315,8 @@ pub extern "system" fn Java_dev_emanuele_spot_nativecore_NativeBridge_nativeColl
mut env: JNIEnv,
_class: JClass,
) -> jstring {
- let result = catalog::collection_uri();
- string_or_throw(&mut env, result)
+ guard_string(&mut env, "CollectionUri", || catalog::collection_uri())
+
}
#[no_mangle]
@@ -274,8 +324,8 @@ pub extern "system" fn Java_dev_emanuele_spot_nativecore_NativeBridge_nativeRoot
mut env: JNIEnv,
_class: JClass,
) -> jstring {
- let result = catalog::rootlist();
- string_or_throw(&mut env, result)
+ guard_string(&mut env, "Rootlist", || catalog::rootlist())
+
}
#[no_mangle]
@@ -284,8 +334,15 @@ pub extern "system" fn Java_dev_emanuele_spot_nativecore_NativeBridge_nativeCont
_class: JClass,
uri: JString,
) -> jstring {
- let result = read_string(&mut env, &uri).and_then(|uri| catalog::context_tracks(&uri));
- string_or_throw(&mut env, result)
+ let uri = match read_string(&mut env, &uri) {
+ Ok(value) => value,
+ Err(message) => {
+ let _ = env.throw_new(EXCEPTION, message);
+ return JObject::null().into_raw() as jstring;
+ }
+ };
+ guard_string(&mut env, "ContextTracks", || catalog::context_tracks(&uri))
+
}
#[no_mangle]
@@ -294,8 +351,15 @@ pub extern "system" fn Java_dev_emanuele_spot_nativecore_NativeBridge_nativePlay
_class: JClass,
uri: JString,
) -> jstring {
- let result = read_string(&mut env, &uri).and_then(|uri| catalog::playlist_cover(&uri));
- string_or_throw(&mut env, result)
+ let uri = match read_string(&mut env, &uri) {
+ Ok(value) => value,
+ Err(message) => {
+ let _ = env.throw_new(EXCEPTION, message);
+ return JObject::null().into_raw() as jstring;
+ }
+ };
+ guard_string(&mut env, "PlaylistCover", || catalog::playlist_cover(&uri))
+
}
#[no_mangle]
@@ -304,8 +368,15 @@ pub extern "system" fn Java_dev_emanuele_spot_nativecore_NativeBridge_nativeCanv
_class: JClass,
track_uri: JString,
) -> jstring {
- let result = read_string(&mut env, &track_uri).and_then(|uri| catalog::canvas(&uri));
- string_or_throw(&mut env, result)
+ let uri = match read_string(&mut env, &track_uri) {
+ Ok(value) => value,
+ Err(message) => {
+ let _ = env.throw_new(EXCEPTION, message);
+ return JObject::null().into_raw() as jstring;
+ }
+ };
+ guard_string(&mut env, "Canvas", || catalog::canvas(&uri))
+
}
#[no_mangle]
@@ -314,8 +385,15 @@ pub extern "system" fn Java_dev_emanuele_spot_nativecore_NativeBridge_nativeLyri
_class: JClass,
track_uri: JString,
) -> jstring {
- let result = read_string(&mut env, &track_uri).and_then(|uri| catalog::lyrics(&uri));
- string_or_throw(&mut env, result)
+ let uri = match read_string(&mut env, &track_uri) {
+ Ok(value) => value,
+ Err(message) => {
+ let _ = env.throw_new(EXCEPTION, message);
+ return JObject::null().into_raw() as jstring;
+ }
+ };
+ guard_string(&mut env, "Lyrics", || catalog::lyrics(&uri))
+
}
#[no_mangle]
@@ -324,8 +402,15 @@ pub extern "system" fn Java_dev_emanuele_spot_nativecore_NativeBridge_nativeTrac
_class: JClass,
uris_json: JString,
) -> jstring {
- let result = read_string(&mut env, &uris_json).and_then(|json| catalog::tracks_metadata(&json));
- string_or_throw(&mut env, result)
+ let json = match read_string(&mut env, &uris_json) {
+ Ok(value) => value,
+ Err(message) => {
+ let _ = env.throw_new(EXCEPTION, message);
+ return JObject::null().into_raw() as jstring;
+ }
+ };
+ guard_string(&mut env, "TracksMetadata", || catalog::tracks_metadata(&json))
+
}
#[no_mangle]
@@ -333,5 +418,5 @@ pub extern "system" fn Java_dev_emanuele_spot_nativecore_NativeBridge_nativeShut
_env: JNIEnv,
_class: JClass,
) {
- engine::shutdown();
+ let _ = std::panic::catch_unwind(engine::shutdown);
}