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.

Songs dissolve into each other on every change

Lelonio38e8142a1fe1
diff --git a/app/src/main/java/dev/lelonio/square/backend/SpotifyBackend.kt b/app/src/main/java/dev/lelonio/square/backend/SpotifyBackend.kt
index 29befd1..4aefeda 100644
--- a/app/src/main/java/dev/lelonio/square/backend/SpotifyBackend.kt
+++ b/app/src/main/java/dev/lelonio/square/backend/SpotifyBackend.kt
@@ -315,6 +315,10 @@ class SpotifyBackend(private val container: SquareApplication) : MusicBackend {
audioOutput::setSpeedAndPitch,
audioOutput::fadeOutThen,
audioOutput::fadeIn,
+ dissolves = {
+ (host.context.applicationContext as? dev.lelonio.square.SquareApplication)
+ ?.preferences?.skipFadeMs()?.let { it > 0 } ?: false
+ },
audioOutput::setPlaybackActive,
audioOutput::duckReverb,
)
diff --git a/app/src/main/java/dev/lelonio/square/backend/youtube/SkipFadePlayer.kt b/app/src/main/java/dev/lelonio/square/backend/youtube/SkipFadePlayer.kt
new file mode 100644
index 0000000..c2aefed
--- /dev/null
+++ b/app/src/main/java/dev/lelonio/square/backend/youtube/SkipFadePlayer.kt
@@ -0,0 +1,77 @@
+package dev.lelonio.square.backend.youtube
+
+import androidx.media3.common.MediaItem
+import androidx.media3.common.Player
+import androidx.media3.common.util.UnstableApi
+import androidx.media3.common.ForwardingPlayer
+
+/**
+ * The YouTube Music player, with the song being left behind faded out first.
+ *
+ * Everything that changes what is playing arrives here: the skip buttons, a
+ * song picked from a list, a queue handed over whole. Each of them used to cut
+ * the music dead and start the next one at full volume, which beside the
+ * Spotify source, where the engine dissolves the two into each other, sounded
+ * like the app changing its mind rather than changing song.
+ *
+ * One player holds one song, so the two halves cannot overlap the way the
+ * engine's do; see [YouTubeFadeController.changeWith], which owns the volume
+ * and runs them one after the other.
+ *
+ * A seek inside the song that is playing is not a change of song and is passed
+ * straight through: dragging the progress bar is not something to dissolve.
+ */
+@UnstableApi
+class SkipFadePlayer(
+ player: Player,
+ private val fades: YouTubeFadeController,
+ /** Zero while the listener has the setting off; see PreferencesStore. */
+ private val fadeMs: () -> Int,
+) : ForwardingPlayer(player) {
+
+ private fun changing(change: () -> Unit) = fades.changeWith(fadeMs(), change)
+
+ override fun seekToNext() = changing { super.seekToNext() }
+
+ override fun seekToNextMediaItem() = changing { super.seekToNextMediaItem() }
+
+ override fun seekToPrevious() = changing { super.seekToPrevious() }
+
+ override fun seekToPreviousMediaItem() = changing { super.seekToPreviousMediaItem() }
+
+ override fun seekTo(mediaItemIndex: Int, positionMs: Long) {
+ if (mediaItemIndex == currentMediaItemIndex) {
+ super.seekTo(mediaItemIndex, positionMs)
+ } else {
+ changing { super.seekTo(mediaItemIndex, positionMs) }
+ }
+ }
+
+ override fun seekToDefaultPosition(mediaItemIndex: Int) {
+ if (mediaItemIndex == currentMediaItemIndex) {
+ super.seekToDefaultPosition(mediaItemIndex)
+ } else {
+ changing { super.seekToDefaultPosition(mediaItemIndex) }
+ }
+ }
+
+ override fun setMediaItem(mediaItem: MediaItem) = changing { super.setMediaItem(mediaItem) }
+
+ override fun setMediaItem(mediaItem: MediaItem, startPositionMs: Long) =
+ changing { super.setMediaItem(mediaItem, startPositionMs) }
+
+ override fun setMediaItem(mediaItem: MediaItem, resetPosition: Boolean) =
+ changing { super.setMediaItem(mediaItem, resetPosition) }
+
+ override fun setMediaItems(mediaItems: MutableList<MediaItem>) =
+ changing { super.setMediaItems(mediaItems) }
+
+ override fun setMediaItems(mediaItems: MutableList<MediaItem>, resetPosition: Boolean) =
+ changing { super.setMediaItems(mediaItems, resetPosition) }
+
+ override fun setMediaItems(
+ mediaItems: MutableList<MediaItem>,
+ startIndex: Int,
+ startPositionMs: Long,
+ ) = changing { super.setMediaItems(mediaItems, startIndex, startPositionMs) }
+}
diff --git a/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubeFadeController.kt b/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubeFadeController.kt
index af77f15..77386cf 100644
--- a/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubeFadeController.kt
+++ b/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubeFadeController.kt
@@ -11,6 +11,7 @@ import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlin.math.PI
+import kotlin.math.cos
import kotlin.math.sin
/**
@@ -27,8 +28,19 @@ class YouTubeFadeController(
private val scope = CoroutineScope(Dispatchers.Main.immediate)
private var tickerJob: Job? = null
private var rampJob: Job? = null
+ private var skipJob: Job? = null
private var isFadingOut = false
+ /**
+ * Whether a change the listener asked for is being dissolved right now.
+ *
+ * While it is, this controller's own rules about the volume are off: the
+ * ticker would put it back to full between the two halves of the fade, and
+ * the transition and the seek that the change itself causes would each
+ * bring the incoming song in at once.
+ */
+ private var skipping = false
+
init {
player.addListener(this)
}
@@ -52,6 +64,7 @@ class YouTubeFadeController(
override fun onMediaItemTransition(mediaItem: MediaItem?, reason: Int) {
isFadingOut = false
+ if (skipping) return
val fadeMs = crossfadeStore?.durationMs() ?: 0
if (fadeMs > 0) {
rampUp(minOf(fadeMs / 2, 1500))
@@ -67,6 +80,7 @@ class YouTubeFadeController(
) {
if (reason == Player.DISCONTINUITY_REASON_SEEK) {
isFadingOut = false
+ if (skipping) return
resetVolume()
}
}
@@ -87,6 +101,7 @@ class YouTubeFadeController(
}
private fun checkFade() {
+ if (skipping) return
val fadeMs = crossfadeStore?.durationMs() ?: 0
if (fadeMs <= 0) {
if (player.volume != 1f) player.volume = 1f
@@ -133,8 +148,59 @@ class YouTubeFadeController(
}
}
+ /**
+ * Takes the song out, makes the listener's change, and brings in what it
+ * lands on.
+ *
+ * One after the other rather than over each other: this player holds one
+ * song at a time, so there is no moment where both are audible. What the
+ * listener asked for is late by the length of the first half, which is why
+ * that half is the shorter thing a dissolve can be and still be one.
+ *
+ * Nothing to fade out of, or the fade turned off, and the change happens
+ * where it was asked for, on the caller's own thread.
+ */
+ fun changeWith(fadeMs: Int, change: () -> Unit) {
+ if (fadeMs <= 0 || !player.isPlaying || player.volume <= 0f) {
+ change()
+ return
+ }
+ skipJob?.cancel()
+ skipping = true
+ skipJob = scope.launch {
+ try {
+ val half = (fadeMs / 2).coerceAtLeast(MIN_HALF_MS)
+ val from = player.volume
+ step(half) { x -> from * cos(x * (PI.toFloat() / 2f)) }
+ player.volume = 0f
+ change()
+ step(half) { x -> sin(x * (PI.toFloat() / 2f)) }
+ player.volume = 1f
+ } finally {
+ skipping = false
+ }
+ }
+ }
+
+ /** One half of a dissolve, as a curve read from nothing to everything. */
+ private suspend fun step(durationMs: Int, curve: (Float) -> Float) {
+ val steps = SKIP_STEPS
+ val wait = (durationMs / steps).toLong().coerceAtLeast(8L)
+ for (i in 1..steps) {
+ val x = i.toFloat() / steps.toFloat()
+ player.volume = curve(x).coerceIn(0f, 1f)
+ delay(wait)
+ }
+ }
+
private fun resetVolume() {
rampJob?.cancel()
player.volume = 1f
}
}
+
+/** How many volume steps each half of a listener's dissolve is made of. */
+private const val SKIP_STEPS = 16
+
+/** Shorter than this and a fade is a click with a delay in front of it. */
+private const val MIN_HALF_MS = 120
diff --git a/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubePlayerFactory.kt b/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubePlayerFactory.kt
index 268f1d4..09e4ad9 100644
--- a/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubePlayerFactory.kt
+++ b/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubePlayerFactory.kt
@@ -64,9 +64,14 @@ object YouTubePlayerFactory {
)
.setLooper(host.looper)
.build()
- .apply {
- addAnalyticsListener(Diagnostics)
- YouTubeFadeController(this, crossfadeStore)
+ .let { exo ->
+ exo.addAnalyticsListener(Diagnostics)
+ val fades = YouTubeFadeController(exo, crossfadeStore)
+ val preferences = (host.context.applicationContext as? dev.lelonio.square.SquareApplication)
+ ?.preferences
+ // Every change of song the listener asks for goes through the
+ // fade; see SkipFadePlayer.
+ SkipFadePlayer(exo, fades) { preferences?.skipFadeMs() ?: 0 }
}
}
diff --git a/app/src/main/java/dev/lelonio/square/data/PreferencesStore.kt b/app/src/main/java/dev/lelonio/square/data/PreferencesStore.kt
index 7195432..5d3eb92 100644
--- a/app/src/main/java/dev/lelonio/square/data/PreferencesStore.kt
+++ b/app/src/main/java/dev/lelonio/square/data/PreferencesStore.kt
@@ -94,6 +94,28 @@ class PreferencesStore(context: Context) {
prefs.edit().putBoolean(KEY_AUTOPLAY_INFINITE, value).apply()
}
+ private val _skipFade = MutableStateFlow(prefs.getBoolean(KEY_SKIP_FADE, true))
+
+ /**
+ * Whether a track the listener changes away from is dissolved into the one
+ * they asked for, rather than cut off.
+ *
+ * On by default, and short: see SKIP_FADE_MS. Apart from the crossfade,
+ * which is what the end of a track sounds like when it runs out on its own.
+ */
+ val skipFade: StateFlow<Boolean> = _skipFade.asStateFlow()
+
+ fun setSkipFade(value: Boolean) {
+ _skipFade.value = value
+ prefs.edit().putBoolean(KEY_SKIP_FADE, value).apply()
+ runCatching {
+ dev.lelonio.square.nativecore.NativeBridge.setSkipFade(skipFadeMs())
+ }
+ }
+
+ /** What the engine and the other source are told, in milliseconds. */
+ fun skipFadeMs(): Int = if (_skipFade.value) SKIP_FADE_MS else 0
+
private val _trimSilence = MutableStateFlow(prefs.getBoolean(KEY_TRIM_SILENCE, true))
/** Whether trailing silence triggers early crossfade. */
@@ -206,6 +228,7 @@ class PreferencesStore(context: Context) {
const val KEY_CANVAS = "canvas_enabled"
const val KEY_AUTOPLAY_INFINITE = "autoplay_infinite"
const val KEY_TRIM_SILENCE = "trim_silence"
+ const val KEY_SKIP_FADE = "skip_fade"
const val KEY_PLAYER_OPEN = "player_open"
const val KEY_BACKEND = "backend"
const val KEY_PROFILE_NAME = "profile_name"
@@ -215,3 +238,12 @@ class PreferencesStore(context: Context) {
const val KEY_USER_COUNTRY = "user_country"
}
}
+
+/**
+ * How long a track the listener changes away from takes to go, and the one
+ * they asked for to arrive, in milliseconds.
+ *
+ * A second: long enough to be a dissolve rather than a cut, short enough that
+ * the song somebody just chose is not kept waiting for it.
+ */
+const val SKIP_FADE_MS = 1_000
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 d52582c..dd3994b 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,15 @@ object NativeBridge {
*/
fun setHoldEnd(enabled: Boolean) = nativeSetHoldEnd(enabled)
+ /**
+ * How long a track the listener changes away from dissolves into the one
+ * they asked for, in milliseconds. Zero cuts, as it always did.
+ *
+ * Apart from the crossfade, which is the end of a track running into the
+ * next one on its own.
+ */
+ fun setSkipFade(ms: Int) = nativeSetSkipFade(ms)
+
/**
* Builds a new session, player and Connect device, keeping everything else.
*
@@ -459,6 +468,8 @@ object NativeBridge {
private external fun nativeSetBitrate(bitrateKbps: Int)
private external fun nativeSetTrimSilence(enabled: Boolean)
private external fun nativeSetHoldEnd(enabled: Boolean)
+
+ private external fun nativeSetSkipFade(ms: Int)
private external fun nativeReconnect()
private external fun nativePlaybackElsewhere(): Boolean
private external fun nativePublishContext(positionMs: Int): Boolean
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 3cf85b0..8031128 100644
--- a/app/src/main/java/dev/lelonio/square/playback/LibrespotPlayer.kt
+++ b/app/src/main/java/dev/lelonio/square/playback/LibrespotPlayer.kt
@@ -50,6 +50,16 @@ class LibrespotPlayer(
*/
private val fadeOutThen: (() -> Unit) -> Unit,
private val fadeIn: () -> Unit,
+ /**
+ * Whether the engine dissolves a change of track itself.
+ *
+ * When it does, the output must not be touched: the fade above ramps this
+ * app's own audio track down and *throws away* what the engine produces
+ * until it is brought back up, which is precisely the second of music the
+ * dissolve is made of. What was heard was the silence of this fade, then
+ * the tail of the old song arriving late, then the new one.
+ */
+ private val dissolves: () -> Boolean,
/**
* Told when playback starts and stops.
*
@@ -103,7 +113,15 @@ class LibrespotPlayer(
// and what is gained is that the queue plays what it shows.
val asContext = false
- fadeOutThen {
+ // A track picked from a list is not one the engine could see coming,
+ // and this used to fade the output down over its own half of the
+ // dissolve while the engine went looking for the context. Two fades
+ // over one change: the output came back up the moment the load was
+ // sent, and the engine's tail, which had only just started going down,
+ // was heard again underneath the new song rising. The engine fades the
+ // song it is leaving whether or not it has anywhere to go yet, so this
+ // one leaves the output alone; see handle_command_load in player.rs.
+ changing {
// 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
@@ -133,11 +151,21 @@ class LibrespotPlayer(
}
.onFailure { android.util.Log.e("SquarePlayer", "load failed: ${it.message}") }
.onSuccess { engineQueueStale = false }
- if (wanted) fadeIn()
+ if (wanted && !dissolves()) fadeIn()
}
}
}
+ /**
+ * Runs a change of track, through the output fade or straight through.
+ *
+ * Straight through while the engine dissolves: what it mixes has to reach
+ * the speaker to be heard at all. See [dissolves].
+ */
+ private fun changing(action: () -> Unit) {
+ if (dissolves()) action() else fadeOutThen(action)
+ }
+
/**
* Built here rather than injected because its callbacks have to reach back
* into this player, and passing it in would need the two to be constructed
@@ -631,7 +659,14 @@ class LibrespotPlayer(
// it wait. Waiting for the first was a fifth of a second between the
// tap and anything happening at all — the delay this settle exists to
// avoid, spent on the one skip that never needed it.
- val delay = if (skipInFlight) SKIP_SETTLE_MS else 0L
+ //
+ // Unless the change is dissolved, where nothing is waiting: the song
+ // being left goes on playing through it, and the fade starts when the
+ // engine takes the load. What the wait buys is one load instead of two
+ // for a double tap, and a load is an audio key: Spotify meters those
+ // per session and answers a burst by refusing everything for up to
+ // half a minute; see audio_key.rs.
+ val delay = if (skipInFlight || dissolves()) SKIP_SETTLE_MS else 0L
skipInFlight = true
handler.removeCallbacks(settleSkip)
handler.postDelayed(settleSkip, delay)
@@ -690,19 +725,19 @@ class LibrespotPlayer(
// 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.
- !engineQueueStale && from >= 0 && target == from + 1 -> fadeOutThen {
+ !engineQueueStale && from >= 0 && target == from + 1 -> changing {
handler.post {
if (released) return@post
runCatching { NativeBridge.next() }
- fadeIn()
+ if (!dissolves()) fadeIn()
}
}
- !engineQueueStale && from >= 0 && target == from - 1 -> fadeOutThen {
+ !engineQueueStale && from >= 0 && target == from - 1 -> changing {
handler.post {
if (released) return@post
runCatching { NativeBridge.previous() }
- fadeIn()
+ if (!dissolves()) fadeIn()
}
}
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 9a3ff44..2a0981e 100644
--- a/app/src/main/java/dev/lelonio/square/playback/PlaybackService.kt
+++ b/app/src/main/java/dev/lelonio/square/playback/PlaybackService.kt
@@ -1285,6 +1285,13 @@ class PlaybackService : MediaLibraryService() {
listener = engine,
)
}
+ // The engine starts on librespot's own defaults, which cut a track
+ // off the moment another is asked for; see PlayerConfig.
+ withContext(Dispatchers.IO) {
+ runCatching {
+ NativeBridge.setSkipFade(container.preferences.skipFadeMs())
+ }
+ }
}.onFailure { error ->
engineStarted = false
android.util.Log.e(TAG, "engine start failed: $error", error)
diff --git a/app/src/main/java/dev/lelonio/square/ui/settings/SettingsScreen.kt b/app/src/main/java/dev/lelonio/square/ui/settings/SettingsScreen.kt
index 445c6d4..4f315b0 100644
--- a/app/src/main/java/dev/lelonio/square/ui/settings/SettingsScreen.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/settings/SettingsScreen.kt
@@ -696,6 +696,7 @@ private fun CrossfadeSection(backdrop: Backdrop) {
}
val chosen by store.seconds.collectAsStateWithLifecycle()
val trimSilence by preferences.trimSilence.collectAsStateWithLifecycle()
+ val skipFade by preferences.skipFade.collectAsStateWithLifecycle()
Section(stringResource(R.string.crossfade)) {
CrossfadeSteps.forEachIndexed { index, seconds ->
@@ -717,6 +718,24 @@ private fun CrossfadeSection(backdrop: Backdrop) {
onChange = preferences::setTrimSilence,
)
RowDivider()
+ // Beside the crossfade, which is the same movement at the end of a
+ // track rather than at the listener's hand, and separate from it: one
+ // is about how records end, the other about what happens when somebody
+ // has heard enough.
+ DownloadSwitch(
+ label = stringResource(R.string.skip_fade),
+ checked = skipFade,
+ backdrop = backdrop,
+ onChange = preferences::setSkipFade,
+ )
+ RowDivider()
+ Text(
+ stringResource(R.string.skip_fade_note),
+ style = MaterialTheme.typography.bodySmall,
+ color = InkDim,
+ modifier = Modifier.padding(horizontal = 18.dp, vertical = 14.dp),
+ )
+ RowDivider()
Text(
stringResource(R.string.quality_restarts),
style = MaterialTheme.typography.bodySmall,
diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml
index 2350b00..d68055c 100644
--- a/app/src/main/res/values-de/strings.xml
+++ b/app/src/main/res/values-de/strings.xml
@@ -426,4 +426,6 @@
<string name="show_all">Alle anzeigen</string>
<string name="show_less">Weniger anzeigen</string>
<string name="search_library">Bibliothek durchsuchen</string>
+ <string name="skip_fade">Überblenden beim Wechseln</string>
+ <string name="skip_fade_note">Der übersprungene oder ersetzte Titel blendet aus, während der gewählte aufkommt. Bei Spotify überlappen sich beide, bei YouTube Music folgt einer auf den anderen.</string>
</resources>
diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml
index 3efa57a..fabf7ec 100644
--- a/app/src/main/res/values-es/strings.xml
+++ b/app/src/main/res/values-es/strings.xml
@@ -432,4 +432,6 @@
<string name="trim_silence">Recortar silencio</string>
<string name="trim_silence_summary">Evita el silencio al final de las canciones durante el fundido</string>
<string name="mood_mixes">Mixes por estado de ánimo</string>
+ <string name="skip_fade">Fundido al cambiar de canción</string>
+ <string name="skip_fade_note">La canción que saltas o sustituyes se desvanece mientras sube la que has elegido. Con Spotify las dos se superponen; en YouTube Music una sigue a la otra.</string>
</resources>
diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml
index 02ee43c..0ad7a4f 100644
--- a/app/src/main/res/values-fr/strings.xml
+++ b/app/src/main/res/values-fr/strings.xml
@@ -426,4 +426,6 @@
<string name="show_all">Tout afficher</string>
<string name="show_less">Afficher moins</string>
<string name="search_library">Rechercher dans la bibliothèque</string>
+ <string name="skip_fade">Fondu au changement de morceau</string>
+ <string name="skip_fade_note">Le morceau que vous passez ou remplacez s\'efface pendant que celui choisi monte. Avec Spotify les deux se superposent, sur YouTube Music l\'un suit l\'autre.</string>
</resources>
diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml
index 0aefc61..24cfaed 100644
--- a/app/src/main/res/values-hi/strings.xml
+++ b/app/src/main/res/values-hi/strings.xml
@@ -441,4 +441,6 @@
<string name="show_all">सभी दिखाएँ</string>
<string name="show_less">कम दिखाएँ</string>
<string name="search_library">लाइब्रेरी में खोजें</string>
+ <string name="skip_fade">गाना बदलते समय फ़ेड</string>
+ <string name="skip_fade_note">जिस गाने को आप छोड़ते या बदलते हैं वह धीरे-धीरे शांत होता है और चुना हुआ गाना उभरता है. Spotify पर दोनों एक साथ चलते हैं, YouTube Music पर एक के बाद एक.</string>
</resources>
diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml
index f7153fa..44cd85b 100644
--- a/app/src/main/res/values-it/strings.xml
+++ b/app/src/main/res/values-it/strings.xml
@@ -427,4 +427,6 @@
<string name="show_all">Mostra tutto</string>
<string name="show_less">Mostra meno</string>
<string name="search_library">Cerca nella libreria</string>
+ <string name="skip_fade">Dissolvenza al cambio brano</string>
+ <string name="skip_fade_note">Il brano che salti o sostituisci sfuma mentre sale quello che hai scelto. Con Spotify i due si sovrappongono, su YouTube Music uno segue l\'altro.</string>
</resources>
diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml
index facb518..47dc6c6 100644
--- a/app/src/main/res/values-pt/strings.xml
+++ b/app/src/main/res/values-pt/strings.xml
@@ -426,4 +426,6 @@
<string name="show_all">Mostrar tudo</string>
<string name="show_less">Mostrar menos</string>
<string name="search_library">Pesquisar na biblioteca</string>
+ <string name="skip_fade">Fade ao mudar de música</string>
+ <string name="skip_fade_note">A música que você pula ou substitui desaparece enquanto a escolhida sobe. No Spotify as duas se sobrepõem; no YouTube Music uma segue a outra.</string>
</resources>
diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml
index 84fd6db..5b747cb 100644
--- a/app/src/main/res/values-ru/strings.xml
+++ b/app/src/main/res/values-ru/strings.xml
@@ -453,4 +453,6 @@
<string name="trim_silence">Обрезать тишину</string>
<string name="trim_silence_summary">Пропускать тишину в конце треков во время кроссфейда</string>
<string name="mood_mixes">Миксы по настроению</string>
+ <string name="skip_fade">Плавная смена трека</string>
+ <string name="skip_fade_note">Трек, который вы переключаете или заменяете, затихает, пока поднимается выбранный. В источнике Spotify они накладываются, в YouTube Music идут друг за другом.</string>
</resources>
diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml
index 51a8468..7bb011f 100644
--- a/app/src/main/res/values-tr/strings.xml
+++ b/app/src/main/res/values-tr/strings.xml
@@ -439,4 +439,6 @@
<string name="show_all">Tümünü göster</string>
<string name="show_less">Daha az göster</string>
<string name="search_library">Kitaplıkta ara</string>
+ <string name="skip_fade">Şarkı değişiminde geçiş</string>
+ <string name="skip_fade_note">Atladığınız veya değiştirdiğiniz şarkı kısılırken seçtiğiniz şarkı yükselir. Spotify kaynağında ikisi üst üste biner, YouTube Music\'te biri diğerini izler.</string>
</resources>
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index 0b48f8d..3588cc9 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -453,4 +453,6 @@
<string name="trim_silence">Trim silence</string>
<string name="trim_silence_summary">Skip trailing silence at track ends during crossfade</string>
<string name="mood_mixes">Mood Mixes</string>
+ <string name="skip_fade">Fade when changing song</string>
+ <string name="skip_fade_note">A song you skip or replace fades out while the one you chose comes up. On the Spotify source the two overlap; on YouTube Music one follows the other.</string>
</resources>
diff --git a/native/src/engine.rs b/native/src/engine.rs
index 87f8498..a7b378d 100644
--- a/native/src/engine.rs
+++ b/native/src/engine.rs
@@ -1010,6 +1010,19 @@ pub fn set_hold_end(enabled: bool) -> EngineResult<()> {
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.
+pub fn set_skip_fade(ms: u32) -> 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.skip_fade_ms = ms;
+ if let Some(bundle) = engine.bundle.as_ref() {
+ bundle.player.set_skip_fade(ms);
+ }
+ Ok(())
+}
+
/// Throws away a bundle and builds another one, leaving the runtime and the
/// audio output alone.
///
@@ -1986,12 +1999,29 @@ pub fn previous() -> EngineResult<()> {
/// fade the app wraps a skip in is long over by then. That was the previous song
/// coming back at full volume before the new one cut in.
fn leaving() {
+ // Not while a skip is dissolved: the gate is there to keep the track being
+ // left from being heard, and that is exactly what a dissolve is made of.
+ // The player fades it out itself, and what is heard under the new track is
+ // a second of the old one going, not the wrong song carrying on.
+ if dissolves() {
+ return;
+ }
let current = current_uri();
if !current.is_empty() {
shut(Gate::Leave(current));
}
}
+/// Whether a change of track the listener asked for is dissolved rather than
+/// cut; see `PlayerConfig::skip_fade_ms`.
+fn dissolves() -> bool {
+ ENGINE
+ .lock()
+ .ok()
+ .and_then(|guard| guard.as_ref().map(|e| e.recipe.player_config.skip_fade_ms > 0))
+ .unwrap_or(false)
+}
+
/// Republishes what is playing as the context it came from.
///
/// Only useful in one moment, just before playback is handed to another device.
diff --git a/native/src/ffi.rs b/native/src/ffi.rs
index 7c35735..80ec911 100644
--- a/native/src/ffi.rs
+++ b/native/src/ffi.rs
@@ -538,6 +538,17 @@ 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_nativeSetSkipFade(
+ mut env: JNIEnv,
+ _class: JClass,
+ ms: jint,
+) {
+ guard(&mut env, "SetSkipFade", || {
+ engine::set_skip_fade(ms.max(0) as u32)
+ });
+}
+
#[no_mangle]
pub extern "system" fn Java_dev_lelonio_square_nativecore_NativeBridge_nativeSetHoldEnd(
mut env: JNIEnv,
diff --git a/native/vendor/librespot-playback/src/config.rs b/native/vendor/librespot-playback/src/config.rs
index d532775..1cef72a 100644
--- a/native/vendor/librespot-playback/src/config.rs
+++ b/native/vendor/librespot-playback/src/config.rs
@@ -204,6 +204,15 @@ pub struct PlayerConfig {
/// crossfade would start the next song under the one being stopped, and
/// the app fades this one out itself.
pub hold_end: bool,
+
+ /// LOCAL PATCH: how long a playing track dissolves into one the listener
+ /// chose, a skip or a pick from a list, in milliseconds. Zero cuts, as
+ /// upstream does.
+ ///
+ /// Apart from `crossfade_duration_ms`, which is the end of a track running
+ /// into the next: when the listener changes songs they are waiting for the
+ /// one they asked for, so this is short.
+ pub skip_fade_ms: u32,
}
impl Default for PlayerConfig {
@@ -228,6 +237,7 @@ impl Default for PlayerConfig {
downloads_only: None,
trim_silence: true,
hold_end: false,
+ skip_fade_ms: 0,
}
}
}
diff --git a/native/vendor/librespot-playback/src/player.rs b/native/vendor/librespot-playback/src/player.rs
index ff281e0..c81e1dc 100644
--- a/native/vendor/librespot-playback/src/player.rs
+++ b/native/vendor/librespot-playback/src/player.rs
@@ -188,6 +188,15 @@ struct FadeOut {
spare: std::collections::VecDeque<f64>,
/// Set when the outgoing track runs out before the fade does.
drained: bool,
+ /// LOCAL PATCH: for a fade the listener started, how far the incoming
+ /// track has risen, counted from when it started making a sound. `None`
+ /// at the end of a track, where both halves move on the one clock.
+ ///
+ /// A song picked from a list is not loaded yet when the one playing starts
+ /// to go, and the outgoing half runs on through the load. On one clock the
+ /// incoming song then came in most of the way up already, which is a cut
+ /// with a fade in front of it.
+ rising: Option<usize>,
}
static PLAYER_COUNTER: AtomicUsize = AtomicUsize::new(0);
@@ -216,6 +225,8 @@ enum PlayerCommand {
SetTrimSilence(bool),
/// LOCAL PATCH: see PlayerConfig::hold_end.
SetHoldEnd(bool),
+ /// LOCAL PATCH: see PlayerConfig::skip_fade_ms.
+ SetSkipFade(u32),
EmitSessionDisconnectedEvent {
connection_id: String,
user_name: String,
@@ -733,6 +744,11 @@ impl Player {
self.command(PlayerCommand::SetHoldEnd(enabled));
}
+ /// LOCAL PATCH: see PlayerConfig::skip_fade_ms.
+ pub fn set_skip_fade(&self, ms: u32) {
+ self.command(PlayerCommand::SetSkipFade(ms));
+ }
+
pub fn emit_filter_explicit_content_changed_event(&self, filter: bool) {
self.command(PlayerCommand::EmitFilterExplicitContentChangedEvent(filter));
}
@@ -2236,7 +2252,12 @@ impl PlayerInternal {
/// LOCAL PATCH: how long a crossfade lasts, in interleaved samples.
fn crossfade_samples(&self) -> usize {
- let ms = self.config.crossfade_duration_ms as usize;
+ Self::fade_samples(self.config.crossfade_duration_ms)
+ }
+
+ /// LOCAL PATCH: a length in milliseconds as interleaved samples.
+ fn fade_samples(ms: u32) -> usize {
+ let ms = ms as usize;
if ms == 0 {
return 0;
}
@@ -2249,28 +2270,43 @@ impl PlayerInternal {
/// LOCAL PATCH: moves the track being replaced into the outgoing half of a
/// crossfade, if there is one and crossfading is on.
fn begin_fade_out(&mut self) {
- let total = self.crossfade_samples();
- if total == 0 {
- self.fade_out = None;
- return;
- }
-
- // Only the track that announced its own end fades out.
+ // The track that announced its own end fades out over the crossfade.
//
// A fade is what the end of a track sounds like, and a skip is not the
// end of a track: it is a listener saying they have heard enough. Every
// load arrives here the same way, whoever asked for it, so the two are
// told apart by `early_end`, which names the one play request that was
// reported as finishing before it had.
+ //
+ // Any other track that is playing goes over the shorter fade the
+ // listener chose for changing songs themselves, and the incoming one
+ // rises on its own clock; see PlayerConfig::skip_fade_ms and
+ // FadeOut::rising. A track that is paused is not heard, and nothing
+ // fades out of it.
let expected = self.early_end.take();
+ let (total, rising) = match &self.state {
+ PlayerState::Playing { play_request_id, .. } if expected == Some(*play_request_id) => {
+ (self.crossfade_samples(), None)
+ }
+ PlayerState::Playing { .. } => (Self::fade_samples(self.config.skip_fade_ms), Some(0)),
+ // Nothing playing to fade out of. Whatever is already fading, if
+ // anything, is the tail this load is arriving under: it was handed
+ // over when the load began and the track it belongs to is gone
+ // from the state already, so it is left to finish.
+ _ => return,
+ };
+ if total == 0 {
+ self.fade_out = None;
+ return;
+ }
+
let previous = mem::replace(&mut self.state, PlayerState::Invalid);
match previous {
PlayerState::Playing {
decoder,
normalisation_factor,
- play_request_id,
..
- } if expected == Some(play_request_id) => {
+ } => {
self.fade_out = Some(FadeOut {
decoder,
normalisation_factor,
@@ -2278,6 +2314,7 @@ impl PlayerInternal {
done: 0,
spare: std::collections::VecDeque::new(),
drained: false,
+ rising,
});
}
// Nothing was playing: put the state back and leave the caller to
@@ -2307,9 +2344,15 @@ impl PlayerInternal {
};
let mut offset = 0;
- while offset + channels <= data.len() && fade.done < fade.total {
+ while offset + channels <= data.len() {
+ let going = fade.done < fade.total;
+ let arriving = fade.rising.map_or(going, |risen| risen < fade.total);
+ if !arriving {
+ break;
+ }
+
// Enough of the outgoing track for this frame, decoded on demand.
- while fade.spare.len() < channels && !fade.drained {
+ while going && fade.spare.len() < channels && !fade.drained {
match fade.decoder.next_packet() {
Ok(Some((_, packet))) => match packet.samples() {
Ok(samples) => fade.spare.extend(samples.iter().copied()),
@@ -2325,27 +2368,47 @@ impl PlayerInternal {
}
}
- let x = fade.done as f64 / fade.total as f64;
- // If the outgoing track has finished draining early, bring the incoming track to full scale
- let gain_in = if fade.drained && fade.spare.is_empty() {
- 1.0
+ let x = fade.done.min(fade.total) as f64 / fade.total as f64;
+ let gain_in = match fade.rising {
+ // A fade the listener started rises from nothing whatever the
+ // outgoing half has done in the meantime.
+ Some(risen) => (risen as f64 / fade.total as f64 * std::f64::consts::FRAC_PI_2).sin(),
+ // If the outgoing track has finished draining early, bring the
+ // incoming track to full scale.
+ None if fade.drained && fade.spare.is_empty() => 1.0,
+ None => (x * std::f64::consts::FRAC_PI_2).sin(),
+ };
+ let gain_out = if going {
+ (x * std::f64::consts::FRAC_PI_2).cos()
} else {
- (x * std::f64::consts::FRAC_PI_2).sin()
+ 0.0
};
- let gain_out = (x * std::f64::consts::FRAC_PI_2).cos();
for sample in data.iter_mut().skip(offset).take(channels) {
- let tail = fade.spare.pop_front().unwrap_or(0.0);
+ let tail = if going {
+ fade.spare.pop_front().unwrap_or(0.0)
+ } else {
+ 0.0
+ };
let mixed = *sample * gain_in
+ tail * gain_out * fade.normalisation_factor * volume;
*sample = soft_limit(mixed);
}
- fade.done += channels;
+ if going {
+ fade.done += channels;
+ }
+ if let Some(risen) = fade.rising.as_mut() {
+ *risen += channels;
+ }
offset += channels;
}
- if fade.done >= fade.total || (fade.drained && fade.spare.is_empty()) {
+ let finished = match fade.rising {
+ Some(risen) => risen >= fade.total,
+ None => fade.done >= fade.total || (fade.drained && fade.spare.is_empty()),
+ };
+ if finished {
// Dropping it closes the outgoing stream.
self.fade_out = None;
}
@@ -2359,10 +2422,16 @@ impl PlayerInternal {
fn pump_fade_out(&mut self) -> bool {
let volume = self.volume_getter.attenuation_factor();
- let (samples, drained) = {
+ let (samples, drained, rising) = {
let Some(fade) = self.fade_out.as_mut() else {
return false;
};
+ // A listener's fade whose outgoing half is already over: nothing
+ // is left to play through the load, and the incoming half still
+ // has its rise to come.
+ if fade.rising.is_some() && fade.done >= fade.total {
+ return false;
+ }
let mut samples: Vec<f64> = fade.spare.drain(..).collect();
if !fade.drained {
@@ -2392,12 +2461,13 @@ impl PlayerInternal {
// track arrived.
fade.done = (fade.done + samples.len()).min(fade.total);
- (samples, fade.drained)
+ (samples, fade.drained, fade.rising.is_some())
};
if samples.is_empty() {
- if drained {
- // Dropping it closes the outgoing stream.
+ // Dropping it closes the outgoing stream; a listener's fade is kept
+ // for the incoming song's rise, and closes when that is over.
+ if drained && !rising {
self.fade_out = None;
}
return false;
@@ -3027,6 +3097,20 @@ impl PlayerInternal {
let loader =
loader.unwrap_or_else(|| Box::pin(self.load_track(track_id.clone(), position_ms)));
+ // LOCAL PATCH: the track being left goes into the fade here, not when
+ // the new one starts.
+ //
+ // A track that was already preloaded reaches `start_playback` in the
+ // same breath and fades out there. One that has to be fetched does not:
+ // the state below replaces the track that is playing, and with it went
+ // its decoder and any chance of fading it, so a skip onto a track the
+ // engine had not seen coming was a cut. The tail is played under the
+ // wait by `pump_fade_out`, and the track arriving rises from nothing on
+ // its own clock; see FadeOut::rising.
+ if play {
+ self.begin_fade_out();
+ }
+
// Set ourselves to a loading state.
self.state = PlayerState::Loading {
track_id,
@@ -3247,6 +3331,12 @@ impl PlayerInternal {
}
// LOCAL PATCH: see PlayerConfig::hold_end.
+ // LOCAL PATCH: see PlayerConfig::skip_fade_ms.
+ PlayerCommand::SetSkipFade(ms) => {
+ info!("skip_fade_ms is now {ms}");
+ self.config.skip_fade_ms = ms;
+ }
+
PlayerCommand::SetHoldEnd(enabled) => {
info!("hold_end is now {enabled}");
self.config.hold_end = enabled;
@@ -3463,6 +3553,7 @@ impl fmt::Debug for PlayerCommand {
PlayerCommand::SetTrimSilence(enabled) => {
f.debug_tuple("SetTrimSilence").field(enabled).finish()
}
+ PlayerCommand::SetSkipFade(ms) => f.debug_tuple("SetSkipFade").field(ms).finish(),
PlayerCommand::SetHoldEnd(enabled) => {
f.debug_tuple("SetHoldEnd").field(enabled).finish()
}