Unofficial YouTube Music / Spotify Premium client for Android, built in Liquid Glass. Audio effects, Spotify Connect, listening history, 8 languages. Rust core on librespot.
Kotlin alternativeandroidandroid-applicationclientglassmorphisminnertubelibrespotliquid-glassspotifyspotify-connectspotifyapiyoutube-musicyoutube-playerytdlnis
A sleep timer that waits for the end of the song, crossfade or not
Leloniof285c71db87b
diff --git a/app/src/main/java/dev/lelonio/square/nativecore/NativeBridge.kt b/app/src/main/java/dev/lelonio/square/nativecore/NativeBridge.ktindex fc3b5f1..d52582c 100644--- a/app/src/main/java/dev/lelonio/square/nativecore/NativeBridge.kt+++ b/app/src/main/java/dev/lelonio/square/nativecore/NativeBridge.kt@@ -190,6 +190,12 @@ object NativeBridge {fun setBitrate(bitrateKbps: Int) = nativeSetBitrate(bitrateKbps)fun setTrimSilence(enabled: Boolean) = nativeSetTrimSilence(enabled)+ /**+ * Lets the playing track run to its own end instead of crossfading into the+ * next one. Set by the sleep timer while it waits for the end of a track.+ */+ fun setHoldEnd(enabled: Boolean) = nativeSetHoldEnd(enabled)+/*** Builds a new session, player and Connect device, keeping everything else.*@@ -452,6 +458,7 @@ object NativeBridge {private external fun nativeSetBitrate(bitrateKbps: Int)private external fun nativeSetTrimSilence(enabled: Boolean)+ private external fun nativeSetHoldEnd(enabled: Boolean)private external fun nativeReconnect()private external fun nativePlaybackElsewhere(): Booleanprivate external fun nativePublishContext(positionMs: Int): Booleandiff --git a/app/src/main/java/dev/lelonio/square/playback/PlaybackService.kt b/app/src/main/java/dev/lelonio/square/playback/PlaybackService.ktindex b6ad864..9a3ff44 100644--- a/app/src/main/java/dev/lelonio/square/playback/PlaybackService.kt+++ b/app/src/main/java/dev/lelonio/square/playback/PlaybackService.kt@@ -20,6 +20,7 @@ import kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.SupervisorJobimport kotlinx.coroutines.cancelimport kotlinx.coroutines.launch+import kotlinx.coroutines.flow.collectLatestimport kotlinx.coroutines.withContext/**@@ -74,6 +75,12 @@ class PlaybackService : MediaLibraryService() {* not silent.*/private suspend fun fadeOutAndPause() {+ if (player is LibrespotPlayer) {+ // A song that changed or stopped during the fade still ends here:+ // the timer is about the time, not about the song.+ if (!fadeEngineOutAndPause(SLEEP_FADE_MS, player.currentMediaItem?.mediaId)) player.pause()+ return+ }if (!player.isCommandAvailable(androidx.media3.common.Player.COMMAND_SET_VOLUME)) {player.pause()return@@ -87,6 +94,47 @@ class PlaybackService : MediaLibraryService() {player.volume = was}+ /**+ * Spotify's engine down to silence over [durationMs], then paused, then+ * put back to the level it was at.+ *+ * Through the engine's own volume, which is the one this player has: the+ * same the ducking for a notification uses. Given up, with the level put+ * back, if the song changes or stops playing on the way down, since the+ * fade was for a song that is no longer the one being heard.+ *+ * @return true when it got to the end and paused.+ */+ private suspend fun fadeEngineOutAndPause(durationMs: Long, mediaId: String?): Boolean {+ val level = withContext(Dispatchers.IO) { runCatching { NativeBridge.volume }.getOrNull() }+ if (level == null || durationMs <= 0) {+ player.pause()+ return true+ }+ val steps = (durationMs / ENGINE_FADE_STEP_MS).coerceIn(1, 400).toInt()+ try {+ for (step in 1..steps) {+ if (!player.isPlaying || player.currentMediaItem?.mediaId != mediaId) return false+ val gain = 1f - step.toFloat() / steps+ withContext(Dispatchers.IO) {+ runCatching { NativeBridge.volume = (level * gain).toInt() }+ }+ kotlinx.coroutines.delay(durationMs / steps)+ }+ player.pause()+ return true+ } finally {+ withContext(kotlinx.coroutines.NonCancellable + Dispatchers.IO) {+ runCatching { NativeBridge.volume = level }+ }+ }+ }++ /** Tells Spotify's engine whether to hold the end of the track; see SleepTimer. */+ private suspend fun holdEngineEnd(hold: Boolean) {+ withContext(Dispatchers.IO) { runCatching { NativeBridge.setHoldEnd(hold) } }+ }+private var autoplayInFlight = falseprivate var lastAutoplayTrackUri: String? = null@@ -281,6 +329,71 @@ class PlaybackService : MediaLibraryService() {}}+ // The end-of-track timer, watched by position.+ //+ // It used to wait for the player to report moving on by itself, and+ // Spotify's player never says so: it is a SimpleBasePlayer, whose+ // reason for a change of track is worked out from where the position+ // was, and the engine moves on before the estimated position reaches+ // the end. So the change arrived as something else and the music went+ // on (#22). Watching the clock works the same for every player.+ //+ // With a crossfade the engine also asks for the next track a fade+ // early, and from then on the song ending is no longer the one it+ // reports: stopping there cut the last seconds off. While this is armed+ // the engine is told to hold the end instead, the song is faded to+ // silence over those seconds, and it pauses on the last of them. A song+ // the listener skipped away from early is not the end of anything, and+ // the timer moves on with them.+ scope.launch {+ SleepTimer.atTrackEnd.collectLatest { armed ->+ if (!armed) return@collectLatest+ holdEngineEnd(true)+ try {+ var watched = player.currentMediaItem?.mediaId+ var lastLeft = Long.MAX_VALUE+ while (true) {+ kotlinx.coroutines.delay(END_WATCH_MS)+ val id = player.currentMediaItem?.mediaId+ if (id != watched) {+ if (lastLeft <= END_NEAR_MS) {+ player.pause()+ SleepTimer.cancel()+ return@collectLatest+ }+ watched = id+ lastLeft = Long.MAX_VALUE+ continue+ }+ val duration = player.duration+ if (duration <= 0 || duration == androidx.media3.common.C.TIME_UNSET) continue+ val left = duration - player.currentPosition+ lastLeft = left+ if (!player.isPlaying) continue++ // Spotify's engine: faded here, over what the crossfade+ // would have taken. YouTube Music's player fades its own+ // ending already, so it only needs stopping at the end.+ val fade = container.crossfade.durationMs().toLong()+ if (player is LibrespotPlayer && fade > 0 && left <= fade + END_STOP_MS) {+ if (fadeEngineOutAndPause(left - END_STOP_MS, watched)) {+ SleepTimer.cancel()+ return@collectLatest+ }+ continue+ }+ if (left <= END_STOP_MS) {+ player.pause()+ SleepTimer.cancel()+ return@collectLatest+ }+ }+ } finally {+ holdEngineEnd(false)+ }+ }+ }+// The sleep timer runs here rather than on the screen that set it; see// SleepTimer.scope.launch {@@ -1543,6 +1656,18 @@ class PlaybackService : MediaLibraryService() {private const val SLEEP_FADE_MS = 6_000Lprivate const val SLEEP_FADE_STEPS = 60+ /** How often the end-of-track timer looks at the clock. */+ private const val END_WATCH_MS = 200L++ /** How close to its end a song is stopped, before any crossfade. */+ private const val END_STOP_MS = 400L++ /** How close a song has to have been for a change of track to be its end. */+ private const val END_NEAR_MS = 2_500L++ /** One step of a fade through the engine's volume. */+ private const val ENGINE_FADE_STEP_MS = 50L+/** Maximum upcoming tracks to buffer in queue for autoplay. */private const val AUTOPLAY_QUEUE_CAP = 10diff --git a/native/src/engine.rs b/native/src/engine.rsindex 96e6eee..87f8498 100644--- a/native/src/engine.rs+++ b/native/src/engine.rs@@ -997,6 +997,19 @@ pub fn set_trim_silence(enabled: bool) -> EngineResult<()> {Ok(())}+/// Lets the playing track run to its own end rather than crossfading into the+/// next; see `PlayerConfig::hold_end`. Kept in the recipe, so a rebuilt player+/// still holds.+pub fn set_hold_end(enabled: bool) -> EngineResult<()> {+ let mut guard = ENGINE.lock().map_err(|_| "engine mutex poisoned")?;+ let engine = guard.as_mut().ok_or("engine not started")?;+ engine.recipe.player_config.hold_end = enabled;+ if let Some(bundle) = engine.bundle.as_ref() {+ bundle.player.set_hold_end(enabled);+ }+ Ok(())+}+/// Throws away a bundle and builds another one, leaving the runtime and the/// audio output alone.///diff --git a/native/src/ffi.rs b/native/src/ffi.rsindex 2282ef1..7c35735 100644--- a/native/src/ffi.rs+++ b/native/src/ffi.rs@@ -537,6 +537,16 @@ pub extern "system" fn Java_dev_lelonio_square_nativecore_NativeBridge_nativeSet});}+/// Holds the end of the playing track for the sleep timer, with no rebuild.+#[no_mangle]+pub extern "system" fn Java_dev_lelonio_square_nativecore_NativeBridge_nativeSetHoldEnd(+ mut env: JNIEnv,+ _class: JClass,+ enabled: jboolean,+) {+ guard(&mut env, "SetHoldEnd", || engine::set_hold_end(enabled != 0));+}+#[no_mangle]pub extern "system" fn Java_dev_lelonio_square_nativecore_NativeBridge_nativeReconnect(mut env: JNIEnv,diff --git a/native/vendor/librespot-playback/src/config.rs b/native/vendor/librespot-playback/src/config.rsindex e8d5a5d..d532775 100644--- a/native/vendor/librespot-playback/src/config.rs+++ b/native/vendor/librespot-playback/src/config.rs@@ -196,6 +196,14 @@ pub struct PlayerConfig {/// LOCAL PATCH: whether trailing silence near the end of a track triggers early crossfade.pub trim_silence: bool,++ /// LOCAL PATCH: let the playing track run to its own end instead of asking+ /// for the next one a crossfade early.+ ///+ /// Set while the app's sleep timer is waiting for the end of the track: a+ /// crossfade would start the next song under the one being stopped, and+ /// the app fades this one out itself.+ pub hold_end: bool,}impl Default for PlayerConfig {@@ -219,6 +227,7 @@ impl Default for PlayerConfig {download_lookup: None,downloads_only: None,trim_silence: true,+ hold_end: false,}}}diff --git a/native/vendor/librespot-playback/src/player.rs b/native/vendor/librespot-playback/src/player.rsindex fcc9008..ff281e0 100644--- a/native/vendor/librespot-playback/src/player.rs+++ b/native/vendor/librespot-playback/src/player.rs@@ -214,6 +214,8 @@ enum PlayerCommand {SetBitrate(Bitrate),/// LOCAL PATCH: whether trailing silence triggers early crossfade.SetTrimSilence(bool),+ /// LOCAL PATCH: see PlayerConfig::hold_end.+ SetHoldEnd(bool),EmitSessionDisconnectedEvent {connection_id: String,user_name: String,@@ -726,6 +728,11 @@ impl Player {self.command(PlayerCommand::SetTrimSilence(enabled));}+ /// LOCAL PATCH: see PlayerConfig::hold_end.+ pub fn set_hold_end(&self, enabled: bool) {+ self.command(PlayerCommand::SetHoldEnd(enabled));+ }+pub fn emit_filter_explicit_content_changed_event(&self, filter: bool) {self.command(PlayerCommand::EmitFilterExplicitContentChangedEvent(filter));}@@ -2129,7 +2136,7 @@ impl Future for PlayerInternal {let crossfade_ms = self.config.crossfade_duration_ms as i64;let position = stream_position_ms as i64;let duration = duration_ms as i64;- if crossfade_ms > 0 && duration > crossfade_ms {+ if crossfade_ms > 0 && duration > crossfade_ms && !self.config.hold_end {let silence_threshold_samples = (SAMPLE_RATE as usize * NUM_CHANNELS as usize * 350) / 1000;let trailing_silence = self.config.trim_silence&& self.consecutive_silent_samples >= silence_threshold_samples@@ -3239,6 +3246,12 @@ impl PlayerInternal {self.config.trim_silence = enabled;}+ // LOCAL PATCH: see PlayerConfig::hold_end.+ PlayerCommand::SetHoldEnd(enabled) => {+ info!("hold_end is now {enabled}");+ self.config.hold_end = enabled;+ }+PlayerCommand::EmitFilterExplicitContentChangedEvent(filter) => {self.send_event(PlayerEvent::FilterExplicitContentChanged { filter });@@ -3450,6 +3463,9 @@ impl fmt::Debug for PlayerCommand {PlayerCommand::SetTrimSilence(enabled) => {f.debug_tuple("SetTrimSilence").field(enabled).finish()}+ PlayerCommand::SetHoldEnd(enabled) => {+ f.debug_tuple("SetHoldEnd").field(enabled).finish()+ }PlayerCommand::SetAutoNormaliseAsAlbum(setting) => f.debug_tuple("SetAutoNormaliseAsAlbum").field(&setting)