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.

Spotify's apps can set Square's sleep timer over Connect

Lelonio9fdc604f714e
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 db319eb..4d179a9 100644
--- a/app/src/main/java/dev/lelonio/square/nativecore/NativeBridge.kt
+++ b/app/src/main/java/dev/lelonio/square/nativecore/NativeBridge.kt
@@ -196,6 +196,13 @@ object NativeBridge {
*/
fun setHoldEnd(enabled: Boolean) = nativeSetHoldEnd(enabled)
+ /**
+ * What the sleep timer is doing, for the state the account's other devices
+ * read: -1 none, 0 the end of the track, otherwise its end in epoch
+ * milliseconds. See SleepTimer and the engine's sleep_timer.
+ */
+ fun setSleepTimer(value: Long) = nativeSetSleepTimer(value)
+
/**
* How long a track the listener changes away from dissolves into the one
* they asked for, in milliseconds. Zero cuts, as it always did.
@@ -490,6 +497,7 @@ object NativeBridge {
private external fun nativeSetBitrate(bitrateKbps: Int)
private external fun nativeSetTrimSilence(enabled: Boolean)
private external fun nativeSetHoldEnd(enabled: Boolean)
+ private external fun nativeSetSleepTimer(value: Long)
private external fun nativeSetSkipFade(ms: Int)
private external fun nativeSetLanguage(language: String, rebuild: Int)
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 8ba9447..3ef936e 100644
--- a/app/src/main/java/dev/lelonio/square/playback/LibrespotPlayer.kt
+++ b/app/src/main/java/dev/lelonio/square/playback/LibrespotPlayer.kt
@@ -1390,6 +1390,18 @@ class LibrespotPlayer(
handler.post { onKeyRefused(positionMs) }
return
}
+ // Set on this device from another of the account's; the timer is the
+ // app's own, so the screen and the countdown are the ones it always has.
+ if (type == "sleep_timer") {
+ handler.post {
+ when {
+ positionMs < 0 -> SleepTimer.cancel()
+ positionMs == 0L -> SleepTimer.atEndOfTrack()
+ else -> SleepTimer.inSeconds(positionMs)
+ }
+ }
+ return
+ }
handler.post { applyEvent(type, uri, positionMs) }
}
diff --git a/app/src/main/java/dev/lelonio/square/playback/PlaybackService.kt b/app/src/main/java/dev/lelonio/square/playback/PlaybackService.kt
index b317dcd..880db17 100644
--- a/app/src/main/java/dev/lelonio/square/playback/PlaybackService.kt
+++ b/app/src/main/java/dev/lelonio/square/playback/PlaybackService.kt
@@ -425,6 +425,22 @@ class PlaybackService : MediaLibraryService() {
}
}
+ // Shown on the account's other devices, which read it back from the
+ // state this one publishes rather than keeping their own. The end is
+ // sent as a time of day, which is what they count down to.
+ scope.launch {
+ kotlinx.coroutines.flow.combine(SleepTimer.endsAt, SleepTimer.atTrackEnd) { deadline, atEnd ->
+ when {
+ atEnd -> 0L
+ deadline != null -> System.currentTimeMillis() +
+ (deadline - android.os.SystemClock.elapsedRealtime()).coerceAtLeast(0L)
+ else -> -1L
+ }
+ }.collect { value ->
+ runCatching { dev.lelonio.square.nativecore.NativeBridge.setSleepTimer(value) }
+ }
+ }
+
// Already read by the application object, and harmless twice: `load`
// returns at once once the file is open.
AudioEffects.load(this)
diff --git a/app/src/main/java/dev/lelonio/square/playback/SleepTimer.kt b/app/src/main/java/dev/lelonio/square/playback/SleepTimer.kt
index 55ce3cc..bbf35b3 100644
--- a/app/src/main/java/dev/lelonio/square/playback/SleepTimer.kt
+++ b/app/src/main/java/dev/lelonio/square/playback/SleepTimer.kt
@@ -45,6 +45,16 @@ object SleepTimer {
_endsAt.value = SystemClock.elapsedRealtime() + minutes * 60_000L
}
+ /**
+ * A length in seconds, as another Spotify device asks for it over Connect.
+ * The row shows it rounded up to the minute.
+ */
+ fun inSeconds(seconds: Long) {
+ _atTrackEnd.value = false
+ _minutes.value = ((seconds + 59) / 60).toInt()
+ _endsAt.value = SystemClock.elapsedRealtime() + seconds * 1_000L
+ }
+
fun atEndOfTrack() {
_minutes.value = null
_endsAt.value = null
diff --git a/native/src/engine.rs b/native/src/engine.rs
index 30505e8..9537a19 100644
--- a/native/src/engine.rs
+++ b/native/src/engine.rs
@@ -503,6 +503,9 @@ pub fn start(
// Spotify refusing the keys a song needs, told to the app so it can say so
// rather than sit on a song that never starts. See the patch in audio_key.
librespot_core::audio_key::on_playback_refusal(|what| emit_app("key_refused", "", what));
+ // A sleep timer set on this device from another of the account's; the
+ // timer is the app's, see librespot-connect's sleep_timer.
+ librespot_connect::sleep_timer::on_request(|value| emit_app("sleep_timer", "", value));
spawn_event_pump(
events_rx,
listener,
@@ -1047,6 +1050,16 @@ pub fn set_hold_end(enabled: bool) -> EngineResult<()> {
Ok(())
}
+/// What the app's sleep timer is doing, for the state other devices read:
+/// -1 none, 0 the end of the track, otherwise its end in epoch milliseconds.
+/// Kept by the connect crate, so a rebuilt device still publishes it.
+pub fn set_sleep_timer(value: i64) -> EngineResult<()> {
+ librespot_connect::sleep_timer::set(value);
+ // Put now if there is a device to put it; otherwise with the next state.
+ let _ = with_bundle(|bundle| bundle.spirc().map(|spirc| spirc.push_state()));
+ Ok(())
+}
+
/// How long a track the listener changes away from dissolves into the one they
/// asked for; see `PlayerConfig::skip_fade_ms`. Kept in the recipe, so a
/// rebuilt player still fades.
diff --git a/native/src/ffi.rs b/native/src/ffi.rs
index 8d9460e..eba3f97 100644
--- a/native/src/ffi.rs
+++ b/native/src/ffi.rs
@@ -575,6 +575,15 @@ pub extern "system" fn Java_dev_lelonio_square_nativecore_NativeBridge_nativeSet
guard(&mut env, "SetHoldEnd", || engine::set_hold_end(enabled != 0));
}
+#[no_mangle]
+pub extern "system" fn Java_dev_lelonio_square_nativecore_NativeBridge_nativeSetSleepTimer(
+ mut env: JNIEnv,
+ _class: JClass,
+ value: jlong,
+) {
+ guard(&mut env, "SetSleepTimer", || engine::set_sleep_timer(value));
+}
+
#[no_mangle]
pub extern "system" fn Java_dev_lelonio_square_nativecore_NativeBridge_nativeReconnect(
mut env: JNIEnv,
diff --git a/native/vendor/librespot-connect/src/lib.rs b/native/vendor/librespot-connect/src/lib.rs
index ba00aa4..d25f47c 100644
--- a/native/vendor/librespot-connect/src/lib.rs
+++ b/native/vendor/librespot-connect/src/lib.rs
@@ -11,6 +11,8 @@ use librespot_protocol as protocol;
mod context_resolver;
mod model;
mod shuffle_vec;
+/// LOCAL PATCH: see the module.
+pub mod sleep_timer;
mod spirc;
mod state;
diff --git a/native/vendor/librespot-connect/src/sleep_timer.rs b/native/vendor/librespot-connect/src/sleep_timer.rs
new file mode 100644
index 0000000..1900323
--- /dev/null
+++ b/native/vendor/librespot-connect/src/sleep_timer.rs
@@ -0,0 +1,94 @@
+//! LOCAL PATCH: the sleep timer, set from any of the account's devices.
+//!
+//! Spotify's apps do not keep a sleep timer for a Connect device themselves:
+//! they send `set_sleep_timer` to it, and read back from its published state
+//! whether one is running and when it ends. The timer itself is the app's
+//! (Square's own SleepTimer), so it is the same one whichever device set it:
+//! a request is handed to the app through [on_request], and the app says what
+//! is running through [set], which goes out with every state this device puts.
+//!
+//! The fields are newer than the protocol crate, so they are written by
+//! number: `PlayerState.sleep_timer` is 38 and
+//! `Capabilities.supports_remote_sleep_timer` is 34. After go-librespot-termux
+//! 4c50725a, 304cd012 and af659717, which captured the payloads.
+
+use std::sync::{
+ OnceLock,
+ atomic::{AtomicI64, Ordering},
+};
+
+use crate::protocol::{connect::Capabilities, player::PlayerState};
+
+/// No timer.
+pub const NONE: i64 = -1;
+/// Stops when the playing track ends.
+pub const END_OF_TRACK: i64 = 0;
+
+const PLAYER_STATE_SLEEP_TIMER: u32 = 38;
+const SUPPORTS_REMOTE_SLEEP_TIMER: u32 = 34;
+
+static ON_REQUEST: OnceLock<fn(i64)> = OnceLock::new();
+
+/// What is running: [NONE], [END_OF_TRACK], or the end as epoch milliseconds.
+static CURRENT: AtomicI64 = AtomicI64::new(NONE);
+
+/// Where requests from other devices go: [NONE] to cancel, [END_OF_TRACK], or
+/// a length in seconds. Only the first call counts.
+pub fn on_request(hook: fn(i64)) {
+ let _ = ON_REQUEST.set(hook);
+}
+
+pub(crate) fn request(value: i64) {
+ if let Some(hook) = ON_REQUEST.get() {
+ hook(value);
+ }
+}
+
+/// What the app's timer is doing now; see [CURRENT]. Published with the next
+/// state; [crate::Spirc::push_state] sends one.
+pub fn set(value: i64) {
+ CURRENT.store(value, Ordering::SeqCst);
+}
+
+pub(crate) fn advertise(mut capabilities: Capabilities) -> Capabilities {
+ capabilities
+ .special_fields
+ .mut_unknown_fields()
+ .add_varint(SUPPORTS_REMOTE_SLEEP_TIMER, 1);
+ capabilities
+}
+
+/// Written into every state before it is put, since a new context can replace
+/// the player state and take an unknown field with it.
+pub(crate) fn apply(player: &mut PlayerState) {
+ let fields = player.special_fields.mut_unknown_fields();
+ fields.remove(PLAYER_STATE_SLEEP_TIMER);
+ if let Some(bytes) = encoded() {
+ fields.add_length_delimited(PLAYER_STATE_SLEEP_TIMER, bytes);
+ }
+}
+
+/// `SleepTimer { oneof { None none = 1; Timestamp timestamp = 2; EndOfTrack end_of_track = 3; } }`
+fn encoded() -> Option<Vec<u8>> {
+ match CURRENT.load(Ordering::SeqCst) {
+ at if at < 0 => None,
+ END_OF_TRACK => Some(vec![0x1A, 0x00]),
+ at => {
+ // Timestamp { int64 timestamp = 1; }
+ let mut timestamp = vec![0x08];
+ varint(at as u64, &mut timestamp);
+ let mut out = vec![0x12];
+ varint(timestamp.len() as u64, &mut out);
+ out.extend(timestamp);
+ Some(out)
+ }
+ }
+}
+
+fn varint(mut value: u64, out: &mut Vec<u8>) {
+ while value >= 0x80 {
+ out.push((value as u8) | 0x80);
+ value >>= 7;
+ }
+ out.push(value as u8);
+}
diff --git a/native/vendor/librespot-connect/src/spirc.rs b/native/vendor/librespot-connect/src/spirc.rs
index 9676d42..d837caf 100644
--- a/native/vendor/librespot-connect/src/spirc.rs
+++ b/native/vendor/librespot-connect/src/spirc.rs
@@ -147,6 +147,8 @@ enum SpircCommand {
Activate,
Transfer(Option<TransferRequest>),
Load(LoadRequest),
+ /// LOCAL PATCH: see [`Spirc::push_state`].
+ PushState,
}
const CONTEXT_FETCH_THRESHOLD: usize = 2;
@@ -526,6 +528,12 @@ impl Spirc {
.commands
.send(SpircCommand::Transfer(transfer_request))?)
}
+
+ /// LOCAL PATCH: puts the state again, for what is kept outside it — the
+ /// sleep timer; see [`crate::sleep_timer`].
+ pub fn push_state(&self) -> Result<(), Error> {
+ Ok(self.commands.send(SpircCommand::PushState)?)
+ }
}
impl SpircTask {
@@ -850,6 +858,10 @@ impl SpircTask {
SpircCommand::Transfer(..) | SpircCommand::Activate => {
warn!("SpircCommand::{cmd:?} will be ignored while already active")
}
+ SpircCommand::PushState => {
+ self.update_state = true;
+ return Ok(());
+ }
_ if !self.connect_state.is_active() => {
warn!("SpircCommand::{cmd:?} will be ignored while Not Active")
}
@@ -1325,6 +1337,14 @@ impl SpircTask {
self.handle_repeat_context(repeat_context.value)?
}
SetRepeatingTrack(repeat_track) => self.handle_repeat_track(repeat_track.value),
+ // LOCAL PATCH: the timer is the app's; see sleep_timer.
+ SetSleepTimer(sleep_timer) => crate::sleep_timer::request(match sleep_timer.timer_type {
+ Some(timer) if timer.kind == "duration" && timer.duration_s > 0 => {
+ timer.duration_s.min(i64::MAX as u64) as i64
+ }
+ Some(timer) if timer.kind == "end_of_track" => crate::sleep_timer::END_OF_TRACK,
+ _ => crate::sleep_timer::NONE,
+ }),
AddToQueue(add_to_queue) => self.connect_state.add_to_queue(add_to_queue.track, true),
SetQueue(set_queue) => self.connect_state.handle_set_queue(set_queue),
SetOptions(set_options) => {
@@ -2099,6 +2119,7 @@ impl SpircTask {
}
self.connect_state.set_now(self.now_ms() as u64);
+ self.connect_state.apply_sleep_timer();
self.connect_state
.send_state(&self.session)
diff --git a/native/vendor/librespot-connect/src/state.rs b/native/vendor/librespot-connect/src/state.rs
index 3ab0048..de256bf 100644
--- a/native/vendor/librespot-connect/src/state.rs
+++ b/native/vendor/librespot-connect/src/state.rs
@@ -149,7 +149,7 @@ impl ConnectState {
spirc_version: version::SPOTIFY_SPIRC_VERSION.to_string(),
client_id: session.client_id(),
is_group: cfg.is_group,
- capabilities: MessageField::some(Capabilities {
+ capabilities: MessageField::some(crate::sleep_timer::advertise(Capabilities {
volume_steps: cfg.volume_steps.into(),
disable_volume: cfg.disable_volume,
@@ -189,7 +189,7 @@ impl ConnectState {
command_acks: true,
..Default::default()
- }),
+ })),
..Default::default()
};
@@ -242,6 +242,11 @@ impl ConnectState {
.expect("the request is always available")
}
+ /// LOCAL PATCH: the sleep timer goes into every state put; see sleep_timer.
+ pub(crate) fn apply_sleep_timer(&mut self) {
+ crate::sleep_timer::apply(self.player_mut());
+ }
+
fn player_mut(&mut self) -> &mut PlayerState {
self.device_mut()
.player_state
diff --git a/native/vendor/librespot-core/src/dealer/protocol/request.rs b/native/vendor/librespot-core/src/dealer/protocol/request.rs
index 8125750..ab7c20e 100644
--- a/native/vendor/librespot-core/src/dealer/protocol/request.rs
+++ b/native/vendor/librespot-core/src/dealer/protocol/request.rs
@@ -36,6 +36,8 @@ pub enum Command {
SetOptions(SetOptionsCommand),
UpdateContext(UpdateContextCommand),
SkipNext(SkipNextCommand),
+ /// LOCAL PATCH: see librespot-connect's sleep_timer.
+ SetSleepTimer(SetSleepTimerCommand),
// commands that don't send any context (at least not usually...)
SkipPrev(GenericCommand),
Resume(GenericCommand),
@@ -67,6 +69,7 @@ impl Display for Command {
SetOptions(_) => "set_options",
UpdateContext(_) => "update_context",
SkipNext(_) => "skip_next",
+ SetSleepTimer(_) => "set_sleep_timer",
SkipPrev(_) => "skip_prev",
Resume(_) => "resume",
Unknown(json) => {
@@ -119,6 +122,22 @@ pub struct SkipNextCommand {
pub logging_params: LoggingParams,
}
+/// LOCAL PATCH: `{"timer_type":{"type":"duration","duration_s":300}}`, or
+/// `"end_of_track"`; anything else cancels.
+#[derive(Clone, Debug, Deserialize)]
+pub struct SetSleepTimerCommand {
+ #[serde(default)]
+ pub timer_type: Option<SleepTimerType>,
+}
+
+#[derive(Clone, Debug, Deserialize)]
+pub struct SleepTimerType {
+ #[serde(rename = "type", default)]
+ pub kind: String,
+ #[serde(default)]
+ pub duration_s: u64,
+}
+
#[derive(Clone, Debug, Deserialize)]
pub struct SetValueCommand {
pub value: bool,