Skip to content

Native Android client for Spotify, built with Jetpack Compose

Skips and pauses without a click (the song is cut only once its fade is low, the level guard leaves intentional fades alone), the liked heart checked for a restored song, retried once when the check fails and refreshed on return to the app and on opening the player (one log line per check), the source line under the title fades in without moving it, the Canvas fades back to the cover when the lyrics or the queue open, -Pabis for single-ABI test builds [skip ci]

kota-zodbfe58e4da51
diff --git a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyPlayer.kt b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyPlayer.kt
index d6828526..1b6e1233 100644
--- a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyPlayer.kt
+++ b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyPlayer.kt
@@ -661,6 +661,8 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
*/
private suspend fun guardVolume(s: PlayerState?, media: Media?) {
if (s == null || s.isPaused || s.isBuffering || _adPlaying.value || fadeBackTo != null || fadeBack?.isActive == true) return
+ // A ramp of ours under way (a pause's fade, a rise just started): the level is low on purpose.
+ if (levelRamps.get() > 0 || System.currentTimeMillis() < levelHeldUntil) return
// Its volume is set through Connect: with another device playing it would be that device's.
if (remoteActive) return
// A crossfade owns the element level until it ends: the guard must not undo the ramp.
@@ -1170,6 +1172,10 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
/** The volume a fade comes back to, while one is under way. */
@Volatile private var fadeBackTo: Double? = null
+ /** Level ramps of our own going down (a pause's), which the volume guard must not take for a lost fade. */
+ private val levelRamps = java.util.concurrent.atomic.AtomicInteger(0)
+ /** Until then the level is still moving (a rise just started, a ramp just ended): the guard leaves it be. */
+ @Volatile private var levelHeldUntil = 0L
private var fadeBack: kotlinx.coroutines.Job? = null
/** The element back to the page player's own volume. */
@@ -1221,6 +1227,8 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
bridge.call("media.rise", buildJsonObject { put("ms", riseMs); put("wait", RISE_WAIT_MS); put("keep", true) },
timeoutMs = LEVEL_TIMEOUT_MS, quiet = true)
}.onFailure { runCatching { restoreLevel() } }
+ // The call answers as the rise starts: the guard waits for the ramp to be over.
+ levelHeldUntil = System.currentTimeMillis() + riseMs + LEVEL_HELD_GRACE_MS
fadeBackTo = null
}
}
@@ -1239,6 +1247,7 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
if (seen?.active == false) { if (crossfading) runCatching { restoreLevel() }; block(); return }
val target = fadeBackTo ?: seen?.own?.takeIf { crossfading && it > 0.01 } ?: seen?.level?.takeIf { it > 0.01 } ?: 1.0
val from = s.item?.uri
+ val startedAt = System.currentTimeMillis()
fadeBackTo = target
fadeBack?.cancel()
// The ramp runs in the page, so it goes down while the command is already on its way; the
@@ -1254,6 +1263,13 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
}
var sent = false
try {
+ // The page changes song a few ms after the command: sent at once, the old song was cut
+ // while still at -6 to -9 dB (heard as a click on every skip). The fade has to be down
+ // before it goes; what the fade call and the caller took already counts. A sound
+ // already down (a crossfade nearly over) waits for nothing. Cancelled or failed here,
+ // the level comes back below like for any command that is not sent.
+ val low = crossfading && (seen?.level ?: target) < target * SKIP_HOLD_LEVEL
+ if (!low) delay(SKIP_HOLD_MS - (System.currentTimeMillis() - startedAt))
block()
sent = true
} finally {
@@ -1543,17 +1559,28 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
val fadeOut = level != null && !_adPlaying.value && !adMuted && lastMedia?.active != false
if (fadeOut) {
fadeBack?.cancel()
- runCatching {
- bridge.call("media.ramp", buildJsonObject { put("to", 0); put("ms", PAUSE_MS) }, timeoutMs = LEVEL_TIMEOUT_MS, quiet = true)
- }
- delay(PAUSE_MS)
+ // A rise cancelled here leaves no one to end its mark; the pause owns the level now.
+ fadeBackTo = null
+ // The ramp takes the level below the guard's threshold on purpose: marked for it
+ // (reported: the guard put the level back to full in the middle of the fade, a blast).
+ levelRamps.incrementAndGet()
}
try {
+ if (fadeOut) {
+ runCatching {
+ bridge.call("media.ramp", buildJsonObject { put("to", 0); put("ms", PAUSE_MS) }, timeoutMs = LEVEL_TIMEOUT_MS, quiet = true)
+ }
+ delay(PAUSE_MS)
+ }
command("player.pause")
} finally {
- // The element back at its level while paused (not heard): a new song started next
- // must not begin at the bottom of the fade.
- if (fadeOut) runCatching { fade(listOf(level!!), restore = true, ms = 1) }
+ if (fadeOut) {
+ // The element back at its level while paused (not heard): a new song started next
+ // must not begin at the bottom of the fade.
+ withContext(NonCancellable) { runCatching { fade(listOf(level!!), restore = true, ms = 1) } }
+ levelHeldUntil = System.currentTimeMillis() + LEVEL_HELD_GRACE_MS
+ levelRamps.decrementAndGet()
+ }
}
}
/*
@@ -1904,6 +1931,15 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
* the song's start.
*/
const val SKIP_RISE_MS = 80L
+ /**
+ * A skip's command goes out this long after its fade began (the page changes song a few ms
+ * after it), so the old song is cut at about -25 dB, not -6. This is the latency a skip pays.
+ */
+ const val SKIP_HOLD_MS = 120L
+ /** A crossfade already below this share of the target level has nothing left to fade before a skip. */
+ const val SKIP_HOLD_LEVEL = 0.1
+ /** The volume guard keeps off this much longer after a ramp of ours, for a media read taken during it. */
+ const val LEVEL_HELD_GRACE_MS = 400L
/** All fade levels, for the floor check. */
val FADE_STEPS = FADE_OUT_STEPS
/**
diff --git a/base/app/build.gradle.kts b/base/app/build.gradle.kts
index 16d3fee7..ece74b83 100644
--- a/base/app/build.gradle.kts
+++ b/base/app/build.gradle.kts
@@ -39,7 +39,8 @@ android {
// (local builds). CI sets it to the repository it builds.
buildConfigField("String", "UPDATE_REPO", "\"${(findProperty("updateRepo") as String?) ?: System.getenv("MYSPOTI_UPDATE_REPO") ?: ""}\"")
ndk {
- abiFilters += listOf("arm64-v8a", "armeabi-v7a")
+ // -Pabis=arm64-v8a: a smaller test APK for one phone.
+ abiFilters += (findProperty("abis") as String?)?.split(",") ?: listOf("arm64-v8a", "armeabi-v7a")
}
// On-device tests (codecs): ./gradlew connectedDebugAndroidTest
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
diff --git a/base/app/src/main/java/app/myspoti/MainActivity.kt b/base/app/src/main/java/app/myspoti/MainActivity.kt
index 4237d0f8..8ed65227 100644
--- a/base/app/src/main/java/app/myspoti/MainActivity.kt
+++ b/base/app/src/main/java/app/myspoti/MainActivity.kt
@@ -252,6 +252,8 @@ class MainActivity : AppCompatActivity() {
if (com.music.spotui.data.api.UpdateChecker.isBeta || app.myspoti.engine.BuildConfig.DEBUG) app.myspoti.host.android.MainThreadWatch.start()
super.onStart()
com.music.spotui.video.MusicVideoController.onForeground()
+ // The song shown may have been liked or unliked in another app meanwhile.
+ com.music.spotui.di.SongPlayer.refreshLikedIfStale()
// Asked for over adb (TestControlReceiver's "screenon"): One UI ignores the huge
// `screen_off_timeout`, so a long unattended run holds the screen on from in here.
if (prefs.getBoolean("keep_screen_on", false)) window.addFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
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 2dabc533..286ecc91 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
@@ -650,6 +650,9 @@ object SongPlayer {
pushNotification(song, liked)
saveLastTrack(song, uri, liked)
trackListen(uri, song, com.music.spotui.data.local.ListenHistory.Source.SPOTIFY, playing)
+ // A song never asked about (the one restored at launch is not a change): its state is asked
+ // once, not read as "not liked" until the next song. A failed ask is not repeated by every state.
+ if (!trackChanged && library[uri] == null) refreshCurrentLiked(fromState = true)
if (trackChanged) {
refreshCurrentLiked()
refreshDevice()
@@ -686,16 +689,52 @@ object SongPlayer {
}
}
- private fun refreshCurrentLiked() {
+ /** Songs whose saved state is being asked for by [refreshCurrentLiked] (one check in flight per song). */
+ private val likeChecking = java.util.concurrent.ConcurrentHashMap.newKeySet<String>()
+ /** When a check of each song got no answer (even after its retry): states do not start another for a while. */
+ private val likeCheckFailedAt = java.util.concurrent.ConcurrentHashMap<String, Long>()
+ /** The last line [refreshCurrentLiked] logged, so the same answer for the same song is logged once. */
+ @Volatile private var lastLikeLog = ""
+
+ /**
+ * Asks Spotify whether the song shown is liked (a state it confirmed less than [SAVED_FRESH_MS]
+ * ago is not asked for again). [fromState]: called because the page state shows a song with no
+ * answer yet, so a song whose check just failed waits [LIKE_RETRY_AFTER_MS] before the next one.
+ * An answer that never comes leaves the heart as it is: no "not liked" is written for it.
+ */
+ private fun refreshCurrentLiked(fromState: Boolean = false) {
val uri = currentLikeUri().takeIf { it.startsWith(SPOTIFY_TRACK_PREFIX) || it.startsWith("spotify:episode:") } ?: return
+ if (fromState && SystemClock.elapsedRealtime() - (likeCheckFailedAt[uri] ?: -LIKE_RETRY_AFTER_MS) < LIKE_RETRY_AFTER_MS) return
+ if (!likeChecking.add(uri)) return
scope.launch {
- // Through the shared, cached request path: a state Spotify confirmed less than
- // [SAVED_FRESH_MS] ago is not asked for again (its row asked for it already).
- libraryContains(listOf(uri))
- library[uri]?.let { onLibraryItem(uri, it) }
+ try {
+ // Through the shared, cached request path: a state Spotify confirmed less than
+ // [SAVED_FRESH_MS] ago is not asked for again (its row asked for it already).
+ var check = checkLibrary(listOf(uri))
+ if (check.failed) {
+ // The page was not ready, or the request was lost: once more, for this song only.
+ kotlinx.coroutines.delay(LIKE_RETRY_MS)
+ if (currentLikeUri() == uri) check = checkLibrary(listOf(uri))
+ }
+ val answer = when {
+ check.failed -> "failed, from Spotify, song $uri, reason ${savedError.ifBlank { "no answer" }}"
+ uri in check.asked -> "${if (uri in check.saved) "liked" else "not liked"}, from Spotify, song $uri"
+ else -> "${if (uri in check.saved) "liked" else "not liked"}, from memory, song $uri"
+ }
+ val line = "liked check: answer $answer"
+ if (line != lastLikeLog) { lastLikeLog = line; app.myspoti.host.android.Logbook.log(line) }
+ if (check.failed) { likeCheckFailedAt[uri] = SystemClock.elapsedRealtime(); return@launch }
+ likeCheckFailedAt.remove(uri)
+ if (uri in check.asked) onLibraryItem(uri, uri in check.saved)
+ } finally {
+ likeChecking.remove(uri)
+ }
}
}
+ /** The app is on screen again, or a player opens: the song shown is asked for if its state is old (see [SAVED_FRESH_MS]). */
+ fun refreshLikedIfStale() = refreshCurrentLiked()
+
/** Back from the local player: the page is heard again if a mirror (an extension's, or the Connect mirror) had muted it. */
fun unmuteMirror() {
com.music.spotui.extensions.Extensions.mirrorReset("the local player stopped")
@@ -1737,6 +1776,12 @@ object SongPlayer {
/** Confirmed by Spotify less than that long ago: not asked for again (see [libraryContains]). */
private const val SAVED_FRESH_MS = 60_000L
+ /** A check of the song shown that got no answer is made once more after this long. */
+ private const val LIKE_RETRY_MS = 2_500L
+
+ /** After a check that failed twice, page states do not start another before this long. */
+ private const val LIKE_RETRY_AFTER_MS = 30_000L
+
/** When Spotify (or the user's own tap) last settled each uri. */
private val savedAt = java.util.concurrent.ConcurrentHashMap<String, Long>()
@@ -1744,6 +1789,8 @@ object SongPlayer {
private val savedFlights =
java.util.concurrent.ConcurrentHashMap<String, kotlinx.coroutines.Deferred<List<Boolean>?>>()
private val savedFlightLock = kotlinx.coroutines.sync.Mutex()
+ /** Why the last request for saved states got no answer (logged by [refreshCurrentLiked]). */
+ @Volatile private var savedError = ""
// The user's last like/unlike wins briefly over states that were already in flight.
@Volatile private var intentUri = ""
@@ -1777,7 +1824,8 @@ object SongPlayer {
/** Make sure [uri]'s saved state ends up in [library]. */
fun requestSaved(uri: String) {
- if (uri.isBlank() || library.containsKey(uri)) return
+ // An entry older than [SAVED_FRESH_MS] is asked again (it may have changed in another app); [libraryContains] skips the fresh ones.
+ if (uri.isBlank() || (library.containsKey(uri) && SystemClock.elapsedRealtime() - (savedAt[uri] ?: 0L) < SAVED_FRESH_MS)) return
if (wantedSaved.add(uri)) { main.removeCallbacks(flushSaved); main.postDelayed(flushSaved, 32) }
}
@@ -1845,17 +1893,22 @@ object SongPlayer {
}
}
+ /** What [checkLibrary] found: [saved] of the uris asked about, [asked] the ones that went to Spotify, [failed] when that got no answer. */
+ private class LibraryCheck(val saved: Set<String>, val asked: Set<String>, val failed: Boolean)
+
/** Which of [uris] are saved in the user's library (Liked Songs / saved albums…). */
- suspend fun libraryContains(uris: List<String>): Set<String> {
- if (uris.isEmpty()) return emptySet()
+ suspend fun libraryContains(uris: List<String>): Set<String> = checkLibrary(uris).saved
+
+ private suspend fun checkLibrary(uris: List<String>): LibraryCheck {
+ if (uris.isEmpty()) return LibraryCheck(emptySet(), emptySet(), false)
val now = SystemClock.elapsedRealtime()
// A page prefetch and the page opening ask for the same list within a second, and the
// rows of a list ask again for what the list just confirmed: only what is unknown (or
// old enough to have changed elsewhere) goes to Spotify.
val (known, unknown) = uris.partition { library.containsKey(it) && now - (savedAt[it] ?: 0L) < SAVED_FRESH_MS }
val out = known.filterTo(mutableSetOf()) { library[it] == true }
- if (unknown.isEmpty()) return out
- val flags = savedFlags(unknown) ?: return out
+ if (unknown.isEmpty()) return LibraryCheck(out, emptySet(), false)
+ val flags = savedFlags(unknown) ?: return LibraryCheck(out, emptySet(), true)
val saved = unknown.filterIndexed { i, _ -> flags.getOrNull(i) == true }.toSet()
main.post {
for (u in unknown) {
@@ -1864,7 +1917,7 @@ object SongPlayer {
savedAt[u] = now
}
}
- return out + saved
+ return LibraryCheck(out + saved, unknown.toSet(), false)
}
/** [uris] in one request; two callers asking the same list share that one request. */
@@ -1877,6 +1930,7 @@ object SongPlayer {
} catch (e: kotlinx.coroutines.CancellationException) {
throw e
} catch (e: Exception) {
+ savedError = e.message ?: e.javaClass.simpleName
null
}
}.also { d ->
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 75d1d74a..37c129c9 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
@@ -233,19 +233,25 @@ fun ImmersivePlayer(
val volume = rememberPlayerVolume()
// The song's Canvas, behind the player once its first frame is drawn. The cover opens into it:
- // the clip fades in from a little closer while the sleeve grows and fades away (and comes back
- // as the header's thumbnail when the lyrics or the queue open over the clip).
+ // the clip fades in from a little closer while the sleeve grows and fades away. The lyrics or
+ // the queue close it the same way back: the clip (paused under them) fades out to the cover's
+ // backdrop and the sleeve returns as the header's thumbnail, rather than a still clip showing
+ // around the panel; closing the panel opens the cover into the clip again.
val canvasUrl = rememberImmersiveCanvas(state)
var canvasShown by remember(canvasUrl) {
mutableStateOf(canvasUrl != null && com.music.spotui.ui.components.CanvasPlayer.isReady(canvasUrl))
}
- val canvasOn = canvasUrl != null && canvasShown && !state.adPlaying
+ val canvasOn = canvasUrl != null && canvasShown && !state.adPlaying && panel == Panel.NONE
// Opening on a clip already showing starts at the end; every later change animates from where it is.
val canvasOpen = remember { androidx.compose.animation.core.Animatable(if (canvasOn) 1f else 0f) }
+ // Opening the player: the heart of the song shown is checked again if its state is old.
+ LaunchedEffect(Unit) { com.music.spotui.di.SongPlayer.refreshLikedIfStale() }
LaunchedEffect(canvasOn) {
val target = if (canvasOn) 1f else 0f
val left = kotlin.math.abs(target - canvasOpen.value)
- if (left > 0f) canvasOpen.animateTo(target, tween((CANVAS_OPEN_MS * left).toInt(), easing = FastOutSlowInEasing))
+ // A panel opening: the clip leaves with the cover's travel to the header, not after it.
+ val ms = if (!canvasOn && panel != Panel.NONE) PANEL_TRAVEL_MS else CANVAS_OPEN_MS
+ if (left > 0f) canvasOpen.animateTo(target, tween((ms * left).toInt(), easing = FastOutSlowInEasing))
}
// Back leaves the panel first; the sheet (outside) closes on the next one.
@@ -518,11 +524,14 @@ private fun RowScope.PlayerCredits(
onMore: (() -> Unit)?,
onSource: () -> Unit,
) {
- // The header is a fixed HEADER_HEIGHT: with a source line the three lines are
- // set tighter, so none is clipped at the bottom.
+ // The header is a fixed HEADER_HEIGHT: the three lines are set tighter, so none is
+ // clipped at the bottom. The source line's room is kept from the start (it is only known
+ // a moment after the song starts), so its arrival fades in below the title and artist
+ // instead of moving them.
val sourceLabel = com.music.spotui.ui.components.playingSourceLabel()
val hasSource = sourceLabel.isNotBlank() && !state.adPlaying
- val lineH = if (hasSource) 22.sp else 24.sp
+ val sourceAlpha by animateFloatAsState(if (hasSource) 1f else 0f, tween(250), label = "sourceLine")
+ val lineH = if (state.adPlaying) 24.sp else 22.sp
Column(
Modifier
.weight(1f)
@@ -577,14 +586,18 @@ private fun RowScope.PlayerCredits(
}
// What the sound is when Myspoti's own player plays it (an extension's stream, a
// download); a tap opens what plays and its quality. Same state as the Classic player.
- if (hasSource) Text(
- text = sourceLabel,
+ if (!state.adPlaying) Text(
+ text = sourceLabel.ifEmpty { " " },
style = Immersive.Caption.copy(lineHeight = 14.sp),
color = tint.copy(alpha = 0.45f),
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier
- .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null, onClick = onSource),
+ .graphicsLayer { alpha = sourceAlpha }
+ .then(
+ if (hasSource) Modifier.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null, onClick = onSource)
+ else Modifier,
+ ),
)
}
Spacer(Modifier.width(10.dp))
diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/player/ImmersivePodcastPlayer.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/player/ImmersivePodcastPlayer.kt
index 8bb8be0d..0173275f 100644
--- a/base/app/src/main/java/com/music/spotui/ui/immersive/player/ImmersivePodcastPlayer.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/player/ImmersivePodcastPlayer.kt
@@ -1,6 +1,7 @@
package com.music.spotui.ui.immersive.player
import androidx.compose.animation.animateColorAsState
+import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
@@ -180,11 +181,14 @@ fun ImmersivePodcastPlayer(navController: NavController) {
}
// The episode and its show, the star of the saved episodes and the episode's menu.
val credits: @Composable RowScope.() -> Unit = {
+ // The source line's room is kept from the start (it is known a moment after the
+ // episode starts): it fades in below the title and the show instead of moving them.
val sourceLabel = playingSourceLabel()
+ val sourceAlpha by animateFloatAsState(if (sourceLabel.isNotBlank()) 1f else 0f, tween(250), label = "sourceLine")
Column(Modifier.weight(1f)) {
Text(
text = title,
- style = Immersive.Title.copy(fontSize = 20.sp, lineHeight = if (sourceLabel.isNotBlank()) 22.sp else 24.sp),
+ style = Immersive.Title.copy(fontSize = 20.sp, lineHeight = 22.sp),
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier
@@ -197,7 +201,7 @@ fun ImmersivePodcastPlayer(navController: NavController) {
text = showName,
style = Immersive.Title.copy(
fontSize = 20.sp,
- lineHeight = if (sourceLabel.isNotBlank()) 22.sp else 24.sp,
+ lineHeight = 22.sp,
fontWeight = FontWeight.W500,
),
color = tint.copy(alpha = 0.55f),
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 ae88d1a2..1ab3f337 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
@@ -348,6 +348,7 @@ fun PlayerScreen(navController: NavController) {
val mv = com.music.spotui.video.MusicVideoController
androidx.compose.runtime.DisposableEffect(mv) {
mv.attachPlayerScreen()
+ SongPlayer.refreshLikedIfStale()
onDispose { mv.detachPlayerScreen() }
}
LaunchedEffect(actualTrackId, songTitle, audioBuffering) {