Skip to content

Native Android client for Spotify, built with Jetpack Compose

Crossfade of extension, downloaded and device songs: the player moves to the next song with the fade, covers and colours blending and the words changing once at halfway; the fading song no longer replays its last second

kota-zo42ab5a8bfa3b
diff --git a/base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt b/base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt
index cac74764..119a0bb3 100644
--- a/base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt
+++ b/base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt
@@ -275,19 +275,34 @@ object LocalPlayer {
// The copy starts a little ahead of the main player: it is heard once it is ready.
out.setMediaItem(item, p.currentPosition + 300)
out.addListener(object : Player.Listener {
+ private var aligned = false
override fun onPlaybackStateChanged(state: Int) {
if (state != Player.STATE_READY || exo == null) return
+ val main = exo ?: return
+ // Ready later than its lead (an extension's stream opened at an offset can take a
+ // second): started there, the copy would play again what was just heard. Moved
+ // once to where the main player is, inside what it has loaded, then started.
+ if (!aligned && main.currentMediaItemIndex == index && main.currentPosition + 50 > out.currentPosition) {
+ aligned = true
+ out.seekTo(main.currentPosition + 100)
+ return
+ }
out.removeListener(this)
preparingFade = false
- val main = exo ?: return out.release()
if (!active.value || main.currentMediaItemIndex != index || !main.playWhenReady || !canFade(main)) return out.release()
- outgoing = out; fadeMs = fade
+ // What is left of the song now, not when the copy was asked for: a longer fade would
+ // run past the copy's end, the next song not yet at full volume.
+ val length = minOf(fade, (main.duration - main.currentPosition).coerceAtLeast(0))
+ if (length < 500) { noFadeFor = index; return out.release() }
+ outgoing = out; fadeMs = length
out.play()
startingFade = true
main.volume = 0f
main.seekToNextMediaItem()
startingFade = false
- log("crossfade $fade ms")
+ // After the switch, synchronously: the screens' state still shows the song fading out.
+ SongPlayer.onLocalFade(true)
+ log("crossfade $length ms")
tick.run()
}
override fun onPlayerError(error: androidx.media3.common.PlaybackException) {
@@ -306,10 +321,22 @@ object LocalPlayer {
private fun endFade() {
handler.removeCallbacks(tick)
outgoing?.let { it.stop(); it.release() }
+ if (outgoing != null) SongPlayer.onLocalFade(false)
outgoing = null
exo?.let { it.volume = 1f; if (it.isPlaying) handler.postDelayed(tick, 200) }
}
+ /**
+ * How far the fade is, 0 (the song going out alone) to 1 (the next one alone); 1 with no fade.
+ * Follows the incoming song's own position, as the volumes do: a stall holds it.
+ */
+ fun fadeProgress(): Float {
+ val p = exo ?: return 1f
+ return if (outgoing == null) 1f else CrossfadeRamp.progress(p.currentPosition, fadeMs)
+ }
+ /** Where the song fading out is (0 with no fade). */
+ fun fadeOutPosition(): Long = outgoing?.currentPosition ?: 0L
+
/** A player stopped by an error (idle) is prepared again first: a play alone does nothing there. */
fun resume() {
val p = exo ?: return
diff --git a/base/app/src/main/java/com/music/spotui/di/SongPlayer.kt b/base/app/src/main/java/com/music/spotui/di/SongPlayer.kt
index 99ddeb95..93df4330 100644
--- a/base/app/src/main/java/com/music/spotui/di/SongPlayer.kt
+++ b/base/app/src/main/java/com/music/spotui/di/SongPlayer.kt
@@ -2400,6 +2400,24 @@ object SongPlayer {
/** True while a crossfade is fading this song out, or the next one in (see [SpotifyPlayer]). */
fun isCrossfadeActive(): Boolean =
MyspotiRuntime.isStarted && MyspotiRuntime.spotify.player.isCrossfading()
+
+ /** The song a real crossfade fades out, as the screens showed it when the fade began. */
+ data class FadingSong(val title: String, val artist: String, val coverUri: String, val durationMs: Long)
+
+ private val fadingOutState = mutableStateOf<FadingSong?>(null)
+ /**
+ * Set while the local player's crossfade overlaps two songs (none for Spotify's own fades,
+ * which do not overlap): the players blend this one into the current song.
+ */
+ val fadingOut: State<FadingSong?> get() = fadingOutState
+
+ /** [LocalPlayer]'s fade starts (just after its switch to the next song) or ends. */
+ fun onLocalFade(on: Boolean) {
+ // The new song's state is posted: what the screens hold is still the song going out.
+ fadingOutState.value = if (!on) null else boundState?.let {
+ FadingSong(it.title.value, it.singer.value, it.coverUri.value, durationMs)
+ }
+ }
fun release() {}
// ── Play-key helpers (url = "spotify:track:<id>|<search text>") ──
diff --git a/base/app/src/main/java/com/music/spotui/ui/components/AppComponents.kt b/base/app/src/main/java/com/music/spotui/ui/components/AppComponents.kt
index 25e21ac4..ddcf8a5c 100644
--- a/base/app/src/main/java/com/music/spotui/ui/components/AppComponents.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/components/AppComponents.kt
@@ -47,6 +47,7 @@ import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.layout.boundsInWindow
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.draw.clip
+import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.draw.clipToBounds
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
@@ -208,6 +209,11 @@ fun MiniPlayer(navController: NavHostController) {
// A new song cross-fades the card's colour instead of snapping to it.
val animatedTint by androidx.compose.animation.animateColorAsState(tint, androidx.compose.animation.core.tween(400), label = "miniTint")
+ // A real crossfade (see SongBlend): cover and colour go from the outgoing song to this one with
+ // the fade's progress; the words and the progress line switch once, half way.
+ val blend = rememberSongBlend()
+ val outgoing = blend?.takeIf { it.outgoingWords }?.song
+ val outgoingTint = remember(blend) { animatedTint }
// The Canvas of the song playing is looked up and loaded now, so the full player
// opens on it directly instead of showing the cover first.
@@ -264,7 +270,8 @@ fun MiniPlayer(navController: NavHostController) {
.onGloballyPositioned { com.music.spotui.ui.navigation.PlayerSheet.miniTop = it.boundsInWindow().top }
.padding(horizontal = 8.dp)
.clip(RoundedCornerShape(8.dp))
- .background(animatedTint)
+ // Drawn: the colour follows a crossfade frame by frame without recomposing the card.
+ .drawBehind { drawRect(blend?.let { androidx.compose.ui.graphics.lerp(outgoingTint, animatedTint, it.progress()) } ?: animatedTint) }
) {
Row(
verticalAlignment = Alignment.CenterVertically,
@@ -285,26 +292,30 @@ fun MiniPlayer(navController: NavHostController) {
// the notification) crossfades instead of swapping in one frame. After a swipe the
// new song is already on screen (the page swiped to): no fade then, or the page
// jumped back to would show the old song fading out.
- val shown = MiniSong(s?.title ?: songTitle, s?.singer ?: songSinger, s?.coverUri ?: songCoverUri)
+ // Through a crossfade the blend below is the transition: no fade of its own.
+ val shown = MiniSong(s?.title ?: outgoing?.title ?: songTitle, s?.singer ?: outgoing?.artist ?: songSinger, s?.coverUri ?: songCoverUri)
androidx.compose.animation.Crossfade(
targetState = shown,
- animationSpec = androidx.compose.animation.core.tween(if (page == 1 && pager.currentPage == 1) 220 else 0),
+ animationSpec = androidx.compose.animation.core.tween(if (page == 1 && pager.currentPage == 1 && blend == null) 220 else 0),
label = "miniSong",
) { m ->
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
- GlideImage(
- transition = CrossFade,
- modifier = Modifier
- .size(40.dp)
- .clip(RoundedCornerShape(4.dp)),
- model = m.cover,
- contentScale = ContentScale.Crop,
- failure = placeholder(R.drawable.placeholder),
- loading = placeholder(R.drawable.placeholder),
- contentDescription = ""
- )
+ Box(Modifier.size(40.dp).clip(RoundedCornerShape(4.dp))) {
+ GlideImage(
+ transition = CrossFade,
+ modifier = Modifier.size(40.dp),
+ model = m.cover,
+ contentScale = ContentScale.Crop,
+ failure = placeholder(R.drawable.placeholder),
+ loading = placeholder(R.drawable.placeholder),
+ contentDescription = ""
+ )
+ // The outgoing cover dissolving into this one, laid over it.
+ if (page == 1) SongBlendCover(blend, Modifier.size(40.dp))
+ }
val remote = SongPlayer.activeDevice.value
- Column(modifier = Modifier.padding(start = 12.dp, end = 8.dp)) {
+ Column(modifier = Modifier.padding(start = 12.dp, end = 8.dp)
+ .graphicsLayer { alpha = if (page == 1) blend?.wordsAlpha() ?: 1f else 1f }) {
if (remote == null) {
Text(text = if (adPlaying) stringResource(R.string.ad_playing) else (m.title), color = Color.White, fontSize = 13.sp, lineHeight = 15.sp, fontWeight = FontWeight.Bold, maxLines = 1, overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis)
if (!adPlaying) Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
@@ -401,8 +412,9 @@ fun MiniPlayer(navController: NavHostController) {
.graphicsLayer()
) {
frame.value
- val dur = SongPlayer.getDuration().toFloat()
- val p = if (dur > 0f) (SongPlayer.getCurrentPosition() / dur).coerceIn(0f, 1f) else 0f
+ val o = blend?.takeIf { it.outgoingWords }
+ val dur = (o?.song?.durationMs ?: SongPlayer.getDuration()).toFloat()
+ val p = if (dur > 0f) ((o?.positionMs() ?: SongPlayer.getCurrentPosition()) / dur).coerceIn(0f, 1f) else 0f
drawRect(Color.White.copy(alpha = 0.25f))
drawRect(Color.White, size = size.copy(width = size.width * p))
}
diff --git a/base/app/src/main/java/com/music/spotui/ui/components/SongBlend.kt b/base/app/src/main/java/com/music/spotui/ui/components/SongBlend.kt
new file mode 100644
index 00000000..4f0b331d
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/ui/components/SongBlend.kt
@@ -0,0 +1,88 @@
+package com.music.spotui.ui.components
+
+import android.graphics.drawable.Drawable
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.Stable
+import androidx.compose.runtime.derivedStateOf
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableFloatStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.withFrameNanos
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.graphics.graphicsLayer
+import androidx.compose.ui.layout.ContentScale
+import com.bumptech.glide.RequestBuilder
+import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi
+import com.bumptech.glide.integration.compose.GlideImage
+import com.music.spotui.di.LocalPlayer
+import com.music.spotui.di.SongPlayer
+import com.music.spotui.ui.look.rememberReduceMotion
+import kotlin.math.abs
+
+/**
+ * The song a real crossfade (an extension's stream, a download, a file of the device) fades out
+ * while the next one fades in, and how far the fade is. The players dissolve its cover and colours
+ * into the current song's with the fade's own [progress], and switch the words (title, artist,
+ * times) once, half way, through a dip of [wordsAlpha]: what is shown follows what is heard.
+ */
+@Stable
+class SongBlend internal constructor(val song: SongPlayer.FadingSong) {
+ internal val t = mutableFloatStateOf(0f)
+
+ /** 0 (the song going out alone) to 1 (the new one alone): read it in a draw or layer block. */
+ fun progress(): Float = t.floatValue
+
+ /** The first half: the words still say the song going out. Changes once per fade. */
+ val outgoingWords: Boolean by derivedStateOf { t.floatValue < 0.5f }
+
+ /** The words fade out to nothing half way, and back in with the new song's. */
+ fun wordsAlpha(): Float = abs(1f - 2f * t.floatValue)
+
+ /** Where the song going out is, for the times shown while its words are. */
+ fun positionMs(): Long = LocalPlayer.fadeOutPosition()
+}
+
+/**
+ * The crossfade going on, or null: with no overlap (Spotify's own fades are an ordinary song
+ * change) and with reduce motion, where the change is a cut. Its progress is read every frame
+ * while it lasts; only the draw and the layers that read it follow, not the screen.
+ */
+@Composable
+fun rememberSongBlend(): SongBlend? {
+ val from = SongPlayer.fadingOut.value
+ val reduceMotion = rememberReduceMotion()
+ val blend = remember(from, reduceMotion) { from?.takeIf { !reduceMotion }?.let(::SongBlend) }
+ LaunchedEffect(blend) {
+ val b = blend ?: return@LaunchedEffect
+ while (true) {
+ // Paused mid-fade, the progress holds still: a few checks a second instead of every frame.
+ if (!LocalPlayer.isPlaying()) { kotlinx.coroutines.delay(250); continue }
+ withFrameNanos { b.t.floatValue = LocalPlayer.fadeProgress() }
+ }
+ }
+ return blend
+}
+
+/**
+ * The cover of the song going out, laid over the current one and fading as the fade goes: the
+ * two dissolve into each other. Over it rather than under, so the current cover still loading
+ * (or its placeholder) never shows through early. Give it the same [modifier] and decode
+ * ([requestBuilderTransform]) as the cover under it, so it comes from the memory cache at once.
+ */
+@OptIn(ExperimentalGlideComposeApi::class)
+@Composable
+fun SongBlendCover(
+ blend: SongBlend?,
+ modifier: Modifier = Modifier,
+ requestBuilderTransform: (RequestBuilder<Drawable>) -> RequestBuilder<Drawable> = { it },
+) {
+ val cover = blend?.song?.coverUri?.takeIf { it.isNotBlank() } ?: return
+ GlideImage(
+ model = cover,
+ contentDescription = null,
+ contentScale = ContentScale.Crop,
+ modifier = modifier.graphicsLayer { alpha = 1f - blend.progress() },
+ requestBuilderTransform = requestBuilderTransform,
+ )
+}
diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/player/ImmersiveMiniPlayer.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/player/ImmersiveMiniPlayer.kt
index b3bbeba3..7794530d 100644
--- a/base/app/src/main/java/com/music/spotui/ui/immersive/player/ImmersiveMiniPlayer.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/player/ImmersiveMiniPlayer.kt
@@ -40,6 +40,7 @@ import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
+import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.input.pointer.positionChange
@@ -83,9 +84,12 @@ private val TRACK_SWIPE_THRESHOLD = 72.dp
@Composable
fun ImmersiveMiniPlayer(navController: NavController, modifier: Modifier = Modifier) {
val vm: PlayerViewModel = viewModel()
- val title = vm.currentSongTitle.value
+ // A crossfade: the words stay the outgoing song's until half way (see SongBlend).
+ val blend = com.music.spotui.ui.components.rememberSongBlend()
+ val outgoing = blend?.takeIf { it.outgoingWords }?.song
+ val title = outgoing?.title ?: vm.currentSongTitle.value
if (title.isBlank()) return
- val singer = vm.currentSongSinger.value
+ val singer = outgoing?.artist ?: vm.currentSongSinger.value
val cover = vm.currentSongCoverUri.value
val playing = vm.currentSongPlayingState.value
val adPlaying = SongPlayer.adPlaying
@@ -106,17 +110,21 @@ fun ImmersiveMiniPlayer(navController: NavController, modifier: Modifier = Modif
.padding(horizontal = 12.dp, vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically,
) {
- GlideImage(
- model = cover.takeIf { it.isNotBlank() },
- contentDescription = null,
- contentScale = ContentScale.Crop,
- transition = CrossFade,
- loading = placeholder(R.drawable.placeholder),
- failure = placeholder(R.drawable.placeholder),
- modifier = Modifier.size(40.dp).clip(RoundedCornerShape(ART_CORNER)).background(Color.Black.copy(alpha = 0.18f)),
- )
+ Box(Modifier.size(40.dp).clip(RoundedCornerShape(ART_CORNER)).background(Color.Black.copy(alpha = 0.18f))) {
+ GlideImage(
+ model = cover.takeIf { it.isNotBlank() },
+ contentDescription = null,
+ contentScale = ContentScale.Crop,
+ transition = CrossFade,
+ loading = placeholder(R.drawable.placeholder),
+ failure = placeholder(R.drawable.placeholder),
+ modifier = Modifier.size(40.dp),
+ )
+ // The outgoing cover dissolving into this one.
+ com.music.spotui.ui.components.SongBlendCover(blend, Modifier.size(40.dp))
+ }
Spacer(Modifier.width(10.dp))
- Column(Modifier.weight(1f)) {
+ Column(Modifier.weight(1f).graphicsLayer { alpha = blend?.wordsAlpha() ?: 1f }) {
Text(
text = if (adPlaying) stringResource(R.string.immersive_player_ad) else title,
// Title and artist set close, as the official mini player: the default line heights left a gap.
@@ -138,7 +146,7 @@ fun ImmersiveMiniPlayer(navController: NavController, modifier: Modifier = Modif
Haptics.click()
// The same optimistic update as the Classic mini player: the glyph flips at once.
if (playing) SongPlayer.pause() else SongPlayer.play()
- vm.updateSongState(cover, title, singer, !playing, vm.currentSongId.value, vm.currentSongIndex.value, vm.currentSongAlbum.value)
+ vm.updateSongState(cover, vm.currentSongTitle.value, vm.currentSongSinger.value, !playing, vm.currentSongId.value, vm.currentSongIndex.value, vm.currentSongAlbum.value)
},
contentAlignment = Alignment.Center,
) {
diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/player/ImmersivePlayer.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/player/ImmersivePlayer.kt
index 18e26767..ef084fee 100644
--- a/base/app/src/main/java/com/music/spotui/ui/immersive/player/ImmersivePlayer.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/player/ImmersivePlayer.kt
@@ -104,6 +104,10 @@ import com.music.spotui.ui.immersive.Immersive
import com.music.spotui.ui.immersive.lyrics.ImmersiveLyricsPanel
import com.music.spotui.ui.immersive.lyrics.ImmersiveQueuePanel
import com.music.spotui.ui.look.MeshGradientBackground
+import com.music.spotui.ui.look.MeshPalette
+import com.music.spotui.ui.look.lerp
+import com.music.spotui.ui.components.SongBlend
+import com.music.spotui.ui.components.SongBlendCover
import com.music.spotui.ui.look.rememberArtworkColors
import com.music.spotui.ui.look.rememberPauseScale
@@ -200,7 +204,13 @@ fun ImmersivePlayer(
) {
val context = LocalContext.current
val palette = rememberArtworkColors(state.coverUrl.takeIf { it.isNotBlank() })
- val tint by animateColorAsState(playerTintOf(palette), tween(com.music.spotui.ui.immersive.motion.ImmersiveMotion.TINT_MS), label = "playerTint")
+ // A crossfade: the colours of the song going out, as they were when it began (the new cover's
+ // own come once it is loaded, and rememberArtworkColors keeps the old ones until then).
+ val blend = state.blend
+ val outgoingPalette = remember(blend) { palette }
+ // The tint is the words' colour: it changes with them, half way.
+ val tintPalette = if (blend?.outgoingWords == true) outgoingPalette else palette
+ val tint by animateColorAsState(playerTintOf(tintPalette), tween(com.music.spotui.ui.immersive.motion.ImmersiveMotion.TINT_MS), label = "playerTint")
var panel by rememberSaveable { mutableIntStateOf(Panel.NONE) }
var showMenu by remember { mutableStateOf(false) }
@@ -224,7 +234,7 @@ fun ImmersivePlayer(
BoxWithConstraints(modifier.fillMaxSize().background(Color.Black)) {
// Wider than tall (a phone on its side, a tablet): the cover beside the controls.
val landscape = maxWidth > maxHeight
- MeshGradientBackground(palette = palette, trackKey = state.coverUrl)
+ PlayerBackdrop(palette, outgoingPalette, blend, state.coverUrl)
CompositionLocalProvider(LocalPlayerTint provides tint) {
if (landscape) LandscapePlayer(
state = state,
@@ -324,6 +334,7 @@ fun ImmersivePlayer(
// first measured (or reloaded) while collapsed stays a small bitmap.
requestBuilderTransform = { it.override(COVER_DECODE_PX) },
)
+ SongBlendCover(blend, Modifier.fillMaxSize()) { it.override(COVER_DECODE_PX) }
}
// ---- Title + round glyphs ----
@@ -394,6 +405,21 @@ fun ImmersivePlayer(
}
}
+/**
+ * The mesh behind the player. During a crossfade its colours go from [outgoing] to [palette] with
+ * the fade's progress, read here so only the backdrop follows it frame by frame, not the player.
+ */
+@Composable
+private fun PlayerBackdrop(palette: MeshPalette, outgoing: MeshPalette, blend: SongBlend?, trackKey: String) {
+ MeshGradientBackground(
+ palette = if (blend == null) palette else lerp(outgoing, palette, blend.progress()),
+ trackKey = trackKey,
+ // Following the fade, a short smoothing only: the new cover's colours, known a moment
+ // into it, do not jump in.
+ colorFadeMillis = if (blend == null) 1400 else 250,
+ )
+}
+
/**
* The credits row of the player: title (with its explicit badge), artist and the source line,
* then the like glyph and, when [onMore] is given, the more glyph. [collapse] is the cover's
@@ -424,6 +450,8 @@ private fun RowScope.PlayerCredits(
scaleX = scale
scaleY = scale
transformOrigin = TransformOrigin(0f, 0.5f)
+ // A crossfade: the outgoing song's words fade out, the new one's in, once.
+ alpha = state.blend?.wordsAlpha() ?: 1f
},
) {
Row(verticalAlignment = Alignment.CenterVertically) {
@@ -606,6 +634,7 @@ private fun LandscapePlayer(
modifier = Modifier.fillMaxSize(),
requestBuilderTransform = { it.override(COVER_DECODE_PX) },
)
+ SongBlendCover(state.blend, Modifier.fillMaxSize()) { it.override(COVER_DECODE_PX) }
}
}
}
diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/player/PlayerBridge.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/player/PlayerBridge.kt
index 902fc716..c9e61f20 100644
--- a/base/app/src/main/java/com/music/spotui/ui/immersive/player/PlayerBridge.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/player/PlayerBridge.kt
@@ -72,6 +72,11 @@ data class ImmersivePlayerState(
val deviceName: String? = null,
/** The track as the options sheet wants it; null while nothing is known. */
val song: SongsModel? = null,
+ /**
+ * A real crossfade going on: its outgoing cover is laid over [coverUrl] and the colours
+ * blend; until half way [title], [artist] and the times are still the outgoing song's.
+ */
+ val blend: com.music.spotui.ui.components.SongBlend? = null,
)
/** What the player does; nothing here touches the UI, the screen owns its sheets and panels. */
@@ -132,15 +137,18 @@ fun rememberImmersivePlayer(navController: NavController): ImmersivePlayerBridge
}
}
+ // The words follow what is heard: the song going out until half way through a crossfade.
+ val blend = com.music.spotui.ui.components.rememberSongBlend()
+ val outgoing = blend?.takeIf { it.outgoingWords }
val state = ImmersivePlayerState(
- title = title,
- artist = singer,
+ title = outgoing?.song?.title ?: title,
+ artist = outgoing?.song?.artist ?: singer,
album = album,
coverUrl = app.myspoti.host.android.Covers.large(cover),
playing = playing,
buffering = buffering,
- positionMs = remember { { SongPlayer.getCurrentPosition() } },
- durationMs = duration,
+ positionMs = remember(outgoing) { outgoing?.let { o -> { o.positionMs() } } ?: { SongPlayer.getCurrentPosition() } },
+ durationMs = outgoing?.song?.durationMs ?: duration,
shuffle = shuffle,
smart = smart,
repeatMode = repeat,
@@ -151,6 +159,7 @@ fun rememberImmersivePlayer(navController: NavController): ImmersivePlayerBridge
contextName = np.contextName.ifBlank { SongPlayer.knownContextName(np.contextUri) }.ifBlank { album },
deviceName = device,
song = if (title.isBlank()) null else nowPlayingSong(vm),
+ blend = blend,
)
// Read at the moment of the tap, not captured: the lambdas below live as long as the screen.
diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/player/PlayerControls.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/player/PlayerControls.kt
index e9391a20..050f585c 100644
--- a/base/app/src/main/java/com/music/spotui/ui/immersive/player/PlayerControls.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/player/PlayerControls.kt
@@ -130,7 +130,9 @@ internal fun PlayerScrubber(
val scrub = rememberPlayerScrub(state.title, state.positionMs, state.durationMs)
// As many ticks as the bar has pixels to move, as the Classic player's: ~5 a second on a long song.
val frame = rememberFrameClock(state.playing && !state.buffering, fps = 15)
- Column(Modifier.fillMaxWidth()) {
+ // A crossfade: the times go from the outgoing song to the new one half way, with the
+ // credits, dimmed through the switch rather than jumping at full strength.
+ Column(Modifier.fillMaxWidth().graphicsLayer { alpha = state.blend?.let { 0.3f + 0.7f * it.wordsAlpha() } ?: 1f }) {
ThinSlider(
value = { frame.value; scrub.shown(state.positionMs(), state.durationMs) },
onValueChange = scrub::drag,
diff --git a/base/app/src/main/java/com/music/spotui/ui/look/MeshGradient.kt b/base/app/src/main/java/com/music/spotui/ui/look/MeshGradient.kt
index 05fb56b3..a70b0767 100644
--- a/base/app/src/main/java/com/music/spotui/ui/look/MeshGradient.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/look/MeshGradient.kt
@@ -67,6 +67,12 @@ private val FallbackColors = listOf(
@Immutable
data class MeshPalette(val colors: List<Color>)
+/** [from] blended into [to] by [fraction], colour by colour (a crossfade between two songs). */
+fun lerp(from: MeshPalette, to: MeshPalette, fraction: Float): MeshPalette {
+ fun four(p: MeshPalette) = (p.colors.ifEmpty { FallbackColors } + FallbackColors).take(4)
+ return MeshPalette(four(from).zip(four(to)) { a, b -> androidx.compose.ui.graphics.lerp(a, b, fraction) })
+}
+
/**
* The Immersive player's backdrop: four luminous colour blobs sampled from
* the album art, drawn as soft radial gradients and blurred into a mesh.
@@ -236,9 +242,12 @@ fun cyclingMeshPalette(palettes: List<MeshPalette>, stepMillis: Int = MESH_CYCLE
@Composable
fun rememberArtworkColors(imageUrl: String?): MeshPalette {
val context = LocalContext.current
- var palette by remember(imageUrl) { mutableStateOf(MeshPalette(FallbackColors)) }
+ // Not reset when the url changes: the last cover's colours stay until the new ones are known,
+ // so a song change goes straight from one palette to the next, not through the stock purple.
+ var palette by remember { mutableStateOf(MeshPalette(FallbackColors)) }
DisposableEffect(imageUrl) {
+ if (imageUrl == null) palette = MeshPalette(FallbackColors)
val target = if (imageUrl == null) null else loadArtwork(context, imageUrl) { bitmap ->
palette = MeshPalette(artworkMeshColors(bitmap))
}
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/PlayerScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/PlayerScreen.kt
index 5264640e..63e256c6 100644
--- a/base/app/src/main/java/com/music/spotui/ui/screens/PlayerScreen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/PlayerScreen.kt
@@ -234,6 +234,12 @@ fun PlayerScreen(navController: NavController) {
if (songCoverUri.isNotBlank()) Palette().extractFirstColorFromImageUrl(context, songCoverUri) { tintColor = it }
}
val backdropColor by androidx.compose.animation.animateColorAsState(tintColor ?: coverColor, androidx.compose.animation.core.tween(450), label = "backdrop")
+ // A real crossfade (see SongBlend): the cover and the backdrop go from the outgoing song to
+ // this one with the fade's progress, the words and times switch once, half way.
+ val blend = com.music.spotui.ui.components.rememberSongBlend()
+ val outgoing = blend?.takeIf { it.outgoingWords }?.song
+ // The backdrop's colour when the fade began, before this song's took over.
+ val outgoingBackdrop = remember(blend) { backdropColor }
val shuffle = playerViewModel.shuffleState.value
val repeat = playerViewModel.repeatState.value
@@ -372,19 +378,22 @@ fun PlayerScreen(navController: NavController) {
modifier = Modifier
.graphicsLayer { translationY = pullToClose.offset }
.fillMaxSize()
- .background(
+ // Drawn, not composed: the colour moves every frame of a crossfade (and of a change),
+ // and only this draw follows it.
+ .drawBehind {
// The tint follows the cover in BOTH modes: AMOLED used to be pure black, and the
// colour was asked for anyway (that replaces the halo idea). The screen keeps its
// gradient, the toggle still governs the rest of the app.
// Official look: the cover's colour at the top, fading to near-black by the
// bottom (still faintly tinted halfway), so white text stays readable.
- Brush.verticalGradient(
- 0f to backdropColor,
- 0.55f to androidx.compose.ui.graphics.lerp(backdropColor, PLAYER_BASE, 0.40f),
- 0.80f to androidx.compose.ui.graphics.lerp(backdropColor, PLAYER_BASE, 0.78f),
+ val top = blend?.let { androidx.compose.ui.graphics.lerp(outgoingBackdrop, backdropColor, it.progress()) } ?: backdropColor
+ drawRect(Brush.verticalGradient(
+ 0f to top,
+ 0.55f to androidx.compose.ui.graphics.lerp(top, PLAYER_BASE, 0.40f),
+ 0.80f to androidx.compose.ui.graphics.lerp(top, PLAYER_BASE, 0.78f),
1f to PLAYER_BASE,
- )
- )
+ ))
+ }
) {
// The window's height (the inner constraints below shadow `maxHeight`) and the status
// bar's, to size the page item itself: a LazyColumn item cannot ask for "parent minus x".
@@ -560,6 +569,13 @@ fun PlayerScreen(navController: NavController) {
model = app.myspoti.host.android.Covers.large(cover),
contentScale = ContentScale.Crop,
contentDescription = "")
+ // The song a crossfade fades out, dissolving into this one.
+ if (page == 1) com.music.spotui.ui.components.SongBlendCover(
+ blend,
+ (if (immersive) Modifier.fillMaxSize()
+ else Modifier.padding(horizontal = coverInset).aspectRatio(1f).clip(RoundedCornerShape(8.dp)))
+ .graphicsLayer { alpha = coverAlpha },
+ )
}
}
}
@@ -595,9 +611,10 @@ fun PlayerScreen(navController: NavController) {
// the screen replaces the title block and every control.
if (!immersive) {
PlayerInfo(
- songTitle = songTitle,
- songSinger = songSinger,
- explicit = np.explicit || currentTrack?.explicit == true,
+ songTitle = outgoing?.title ?: songTitle,
+ songSinger = outgoing?.artist ?: songSinger,
+ wordsAlpha = { blend?.wordsAlpha() ?: 1f },
+ explicit = outgoing == null && (np.explicit || currentTrack?.explicit == true),
liked = isLiked.value,
onLikeClick = { playerViewModel.updateLikeState(!isLiked.value) },
likeSong = { nowPlayingSong(playerViewModel) },
@@ -629,13 +646,16 @@ fun PlayerScreen(navController: NavController) {
// Seek bar: follows the finger while dragging, seeks once on release.
var isDragging by remember { mutableStateOf(false) }
var dragValue by remember { mutableStateOf(0f) }
- val duration = mv.duration()
+ // The outgoing song's times until half way through a crossfade, as its words.
+ val duration = outgoing?.durationMs ?: mv.duration()
+ val outgoingAt = blend?.takeIf { outgoing != null }
SpotifySeekBar(
fraction = {
frame.value // redraw each frame
if (isDragging) dragValue else {
- val d = mv.duration()
- if (d > 0) (mv.position().toFloat() / d).coerceIn(0f, 1f) else 0f
+ val d = if (outgoingAt != null) duration else mv.duration()
+ val at = outgoingAt?.positionMs() ?: mv.position()
+ if (d > 0) (at.toFloat() / d).coerceIn(0f, 1f) else 0f
}
},
onDrag = { isDragging = true; dragValue = it },
@@ -655,7 +675,8 @@ fun PlayerScreen(navController: NavController) {
.padding(horizontal = 24.dp),
horizontalArrangement = Arrangement.SpaceBetween
) {
- ElapsedLabel(songPlayingState, if (isDragging) (dragValue * duration).toLong() else null) {
+ ElapsedLabel(songPlayingState, if (isDragging) (dragValue * duration).toLong() else null,
+ position = outgoingAt?.let { o -> { o.positionMs() } } ?: mv::position) {
playerViewModel.formatDuration(it)
}
Text(
@@ -1047,6 +1068,8 @@ fun PlayerInfo(
onTitleClick: (() -> Unit)? = null,
/** T4: an ad break is on: what the caller passes is the song from before it, not what plays. */
adPlaying: Boolean = false,
+ /** The words' dip through a crossfade's switch (SongBlend.wordsAlpha), read at draw. */
+ wordsAlpha: () -> Float = { 1f },
) {
Row(
verticalAlignment = Alignment.CenterVertically,
@@ -1064,7 +1087,7 @@ fun PlayerInfo(
textAlpha.snapTo(0f)
textAlpha.animateTo(1f, androidx.compose.animation.core.tween(200))
}
- Column(modifier = Modifier.weight(1f).padding(end = 16.dp).graphicsLayer { alpha = textAlpha.value }) {
+ Column(modifier = Modifier.weight(1f).padding(end = 16.dp).graphicsLayer { alpha = textAlpha.value * wordsAlpha() }) {
Text(
modifier = Modifier
// A few passes, after the sheet has settled (not an endless 120 Hz animation).
@@ -1113,21 +1136,22 @@ fun PlayerInfo(
/** Elapsed time text with its own ticker (doesn't recompose the whole player). */
@Composable
-private fun ElapsedLabel(playing: Boolean, override: Long?, format: (Long) -> String) {
+private fun ElapsedLabel(playing: Boolean, override: Long?, position: () -> Long, format: (Long) -> String) {
val mv = com.music.spotui.video.MusicVideoController
- var now by remember { mutableStateOf(mv.position()) }
+ val at by androidx.compose.runtime.rememberUpdatedState(position)
+ var now by remember { mutableStateOf(position()) }
val lifecycle = LocalLifecycleOwner.current.lifecycle
LaunchedEffect(playing, mv.on.value, lifecycle) {
lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
while (true) {
- now = mv.position()
+ now = at()
if (!playing) break
delay(250L)
}
}
}
// Seek while paused: pick the new position up as soon as it changes.
- LaunchedEffect(override) { if (override == null) now = mv.position() }
+ LaunchedEffect(override, position) { if (override == null) now = position() }
Text(text = format(override ?: now), color = Color.White.copy(alpha = 0.7f), fontSize = 13.sp, lineHeight = 14.sp)
}