Skip to content

Native Android client for Spotify, built with Jetpack Compose

A player that no longer redraws a hidden page, recovers from a failed load, and catches a lost skip

kota-zobc02f5a34215
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d3bfbffb..2ca654a7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,15 @@
Each release on GitHub shows its section below. The app shows it too when it offers the update. Every detail: [docs/CHANGELOG-full.md](docs/CHANGELOG-full.md).
+## Unreleased
+
+- **Smoother player, lighter on the battery**: the hidden player page was redrawn with every frame the app drew (and kept animating its own UI underneath), and the progress bar redrew the whole player 15 times a second. The page now stays out of the app's drawing and the bar redraws only itself, as often as it actually moves. Measured on the player screen: 0 late frames instead of 86 %, about a third less CPU — and a tap on a song or "next" is heard ~150 ms sooner.
+- **The player recovers from a page that fails to load**: when Spotify answered an error to a reload (seen: 504), the app stayed on it, refusing every command until restarted. The page is now loaded again, sooner first, then every minute.
+- **"Next" that does nothing**: when the player page answered "ok" to a skip but stayed on the song (the sound dipped, then nothing), the song after it is now asked for by name.
+- **Spotify refusing playback (402)**: after a refusal, the app now also tries taking playback to this phone first, then the list on shuffle, before telling you; the diagnostic report now says which kind of account plays and whether a refused command targeted this phone or another device.
+- **Smart shuffle from the player keeps the song playing**: on a long playlist the song was often not found and a random one started; the playing song now always stays first.
+- **Shuffle no longer flips back**: a state sent by the page before it took the tap could turn the button off again, and the list and the player then disagreed.
+
## 2.0.0-beta.9
- **Fast skips during an ad or a reload**: the song your taps point to plays once the ad or the reload is over, and the screen shows that same song (the sound and the screen no longer drift apart); "previous" during an ad no longer restarts the ad.
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 fb10a5d8..44c1a85f 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
@@ -7,6 +7,7 @@ import app.myspoti.api.PlayerState
import app.myspoti.api.Queue
import app.myspoti.api.Repeat
import app.myspoti.api.Uri
+import app.myspoti.spotify.bridge.service
import app.myspoti.spotify.bridge.Bridge
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
@@ -78,7 +79,9 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
@Volatile private var wantedVolume: Double? = null
/** The last [play] sent: (context, track, when), for a refused command's retry. */
@Volatile private var lastPlay: Triple<Uri, Uri?, Long>? = null
- @Volatile private var refusedRetried = false
+ /** How far down [onRefused]'s steps the current play went (0: not refused). */
+ @Volatile private var refusalStep = 0
+ @Volatile private var refusalTransferring = false
private val _refused = kotlinx.coroutines.flow.MutableSharedFlow<Unit>(extraBufferCapacity = 1)
/**
* Spotify refused a play even after the retry (free accounts in some countries can't
@@ -477,13 +480,60 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
}
/** Spotify refused the last play: once, the list is played from its start instead. */
+ /**
+ * Spotify refused the last play (`402 COMMAND_FAILED`). Each refusal within the window moves
+ * one step down, so a play that works never pays for any of it:
+ * 1. the list without picking the song (an account that may not choose a track);
+ * 2. playback taken to this player first, then the song again (the command may have gone to
+ * another device of the account — the official app — which a free account cannot drive);
+ * 3. the list on shuffle (an account that may only shuffle);
+ * then the user is told.
+ */
private fun onRefused() {
val last = lastPlay ?: return
- if (System.currentTimeMillis() - last.third > REFUSED_WINDOW_MS) return
- if (refusedRetried || last.second == null) { _refused.tryEmit(Unit); return }
- refusedRetried = true
- bridge.logger?.invoke("play refused by Spotify: playing the list without picking the song")
- scope.launch { runCatching { bridge.call("player.play", buildJsonObject { put("contextUri", last.first) }, timeoutMs = PLAY_TIMEOUT_MS) } }
+ val now = System.currentTimeMillis()
+ if (now - last.third > REFUSED_WINDOW_MS) return
+ // The step's own transfer refused: the step is judged by the play that follows it.
+ if (refusalTransferring) return
+ val ctx = last.first
+ var step = ++refusalStep
+ if (step == 1 && last.second == null) step = ++refusalStep
+ // Each step's own play may be refused in its turn: it opens a new window.
+ lastPlay = last.copy(third = now)
+ suspend fun playCtx(track: Uri?) = bridge.call("player.play", buildJsonObject {
+ put("contextUri", ctx)
+ track?.let { put("trackUri", it) }
+ }, timeoutMs = PLAY_TIMEOUT_MS)
+ when (step) {
+ 1 -> {
+ bridge.logger?.invoke("play refused by Spotify: playing the list without picking the song")
+ scope.launch { runCatching { playCtx(null) } }
+ }
+ 2 -> {
+ bridge.logger?.invoke("play refused by Spotify: taking playback to this player first")
+ scope.launch {
+ refusalTransferring = true
+ try {
+ runCatching { bridge.service("ConnectTransferAPI", "pullToLocalDevice", JsonObject(emptyMap())) }
+ .onFailure { bridge.logger?.invoke("transfer to this player failed: ${it.message}") }
+ delay(REFUSAL_SETTLE_MS)
+ } finally {
+ refusalTransferring = false
+ }
+ lastPlay = last.copy(third = System.currentTimeMillis())
+ runCatching { playCtx(last.second) }
+ }
+ }
+ 3 -> {
+ bridge.logger?.invoke("play refused by Spotify: playing the list on shuffle")
+ scope.launch {
+ runCatching { setShuffle(true) }
+ lastPlay = last.copy(third = System.currentTimeMillis())
+ runCatching { playCtx(null) }
+ }
+ }
+ else -> _refused.tryEmit(Unit)
+ }
}
/** Plays the song after [s] (or [s] again when it is the last one) in its context. */
@@ -628,7 +678,7 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
adMuteTries = 0
// A real song is playing: the fallback after a refusal (play the list without picking the
// song) is armed again for the next command, not held once per five seconds for all of them.
- refusedRetried = false
+ refusalStep = 0
if (s?.item != null) lastSong = s
else if (lastTrackState?.item != null) lastSongUntil = System.currentTimeMillis()
lastTrackState = s
@@ -862,7 +912,7 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
if (trackUri == null || trackUri != liveIntent()?.item?.uri) intent = null
lastOrder = order?.let { contextUri to it }
lastPlay = Triple(contextUri, trackUri, System.currentTimeMillis())
- refusedRetried = false
+ refusalStep = 0
pausedByUser = false
withFade {
command("player.play", timeoutMs = PLAY_TIMEOUT_MS, args = buildJsonObject {
@@ -905,9 +955,24 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
val base = lastWithSong()
val after = base?.next?.takeIf { it.kind == ItemKind.TRACK || it.kind == ItemKind.EPISODE }
if (after != null && base.item?.kind != ItemKind.AD) intent = Intent(base.contextUri, after, base.item?.uri, System.currentTimeMillis())
+ val sent = intent
runCatching { withFade { command("player.next") } }.onFailure { e ->
if (!heldError(e, base?.restrictions?.canSkipNext != false)) throw e
stepIntent(1)
+ return
+ }
+ // Reported (Pixel 8, beta.8): the page answers "ok" to the skip and stays on the song, so
+ // the tap only dimmed the sound for a second. Still on it a moment later: the song the
+ // skip pointed at is asked for by name.
+ if (sent != null) scope.launch {
+ delay(NEXT_LOST_MS)
+ val i = liveIntent()
+ if (i == null || i !== sent || skipsHeld || pausedByUser) return@launch
+ val now = lastTrackState?.item?.uri
+ if (now != null && now == i.from) {
+ bridge.logger?.invoke("skip lost by the page: playing ${i.item.name}")
+ runCatching { playIntent() }
+ }
}
}
@@ -1103,6 +1168,10 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
const val PLAY_TIMEOUT_MS = 10_000L
/** A refusal that long after a play belongs to it. */
const val REFUSED_WINDOW_MS = 5_000L
+ /** A plain skip still on its song after this: the page lost it. */
+ const val NEXT_LOST_MS = 2_500L
+ /** After the refusal fallback's transfer, before the song is asked again. */
+ const val REFUSAL_SETTLE_MS = 600L
/** Never two "frozen page" reloads closer than that. */
const val FROZEN_RELOAD_GAP_MS = 60_000L
/**
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 77592ed1..65bce9bd 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
@@ -373,7 +373,9 @@ object SongPlayer {
next = s.next?.let(::songOf),
)
val state = boundState ?: return
- state.shuffle.value = s.shuffle
+ val holding = SystemClock.elapsedRealtime() < shuffleWantedUntil
+ if (holding && s.shuffle == shuffleWanted) shuffleWantedUntil = 0L
+ if (!holding || s.shuffle == shuffleWanted) state.shuffle.value = s.shuffle
// The page reports a speed other than 1 only for episodes: music stays at 1.
_speed.value = s.speed.takeIf { it > 0.0 } ?: 1.0
_repeatMode.value = s.repeat.ordinal
@@ -701,7 +703,20 @@ object SongPlayer {
}
}
- fun setShuffle(on: Boolean) { Haptics.toggle(on); if (LocalPlayer.active.value) { LocalPlayer.setShuffle(on); return }; command { api.player.setShuffle(on) } }
+ fun setShuffle(on: Boolean) {
+ Haptics.toggle(on)
+ if (LocalPlayer.active.value) { LocalPlayer.setShuffle(on); return }
+ shuffleWanted = on
+ shuffleWantedUntil = SystemClock.elapsedRealtime() + SHUFFLE_HOLD_MS
+ command { api.player.setShuffle(on) }
+ }
+
+ // Reported: shuffle out of step between the list and the player. A state the page sent
+ // before it took the tap flipped the button back, and the two screens then disagreed; the
+ // value asked for holds until the page reports it (or for SHUFFLE_HOLD_MS).
+ @Volatile private var shuffleWanted = false
+ @Volatile private var shuffleWantedUntil = 0L
+ private const val SHUFFLE_HOLD_MS = 2_500L
/** 0 = off, 1 = context, 2 = track. */
private val _repeatMode = mutableStateOf(0)
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 cc5b7bb2..719cc9ab 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
@@ -40,6 +40,7 @@ import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
+import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.clipToBounds
import androidx.compose.ui.graphics.Color
@@ -176,7 +177,8 @@ fun MiniPlayer(navController: NavHostController) {
}
// The thin bar moves ~2 px/s: 4 ticks a second look identical to 20.
- val frame = rememberFrameClock(songPlayingState, fps = 4)
+ // Covered by the full player: no ticks (they redrew the whole window under it).
+ val frame = rememberFrameClock(songPlayingState && !com.music.spotui.ui.navigation.PlayerSheet.open.value, fps = 4)
var showDevices by remember { mutableStateOf(false) }
if (showDevices) DevicesSheet { showDevices = false }
@@ -311,6 +313,8 @@ fun MiniPlayer(navController: NavHostController) {
.padding(horizontal = 8.dp)
.height(2.dp)
.clip(RoundedCornerShape(1.dp))
+ // Its own layer: a tick re-records these two rectangles, not the whole card.
+ .graphicsLayer()
) {
frame.value
val dur = SongPlayer.getDuration().toFloat()
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/ContextScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/ContextScreen.kt
index 7ee7847a..1ee32ccb 100644
--- a/base/app/src/main/java/com/music/spotui/ui/screens/ContextScreen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/ContextScreen.kt
@@ -816,7 +816,7 @@ object SmartShuffle {
// Spotify's extender gives nothing for some playlists: the radios of a few of its songs.
.ifEmpty { p.tracks.shuffled().take(3).flatMap { runCatching { api.getRecommendations(listOf(it.spotifyTrackId)).take(8) }.getOrDefault(emptyList()) } }
}.filter { it.spotifyTrackId !in inList }.distinctBy { it.spotifyTrackId }.shuffled()
- val shuffled = p.tracks.shuffled().let { list -> first?.let { f -> listOf(f) + (list - f) } ?: list }
+ val shuffled = p.tracks.shuffled().let { list -> first?.let { f -> listOf(f) + list.filter { it.spotifyTrackId != f.spotifyTrackId } } ?: list }
if (shuffled.isEmpty()) return
val mixed = ArrayList<SongsModel>()
val more = recs.iterator()
@@ -844,7 +844,12 @@ object SmartShuffle {
else -> return false
}
val page = (withContext(Dispatchers.IO) { flow.first { it !is Response.Loading } } as? Response.Success)?.data ?: return false
- start(page, page.tracks.firstOrNull { it.spotifyTrackId == currentTrackId }, SongPlayer.getCurrentPosition())
+ // Reported: turning it on from the player skipped the song. A long list's page holds only
+ // its first tracks, so the song playing was often not found and a random one started
+ // instead; the song playing now always stays first.
+ val current = page.tracks.firstOrNull { it.spotifyTrackId == currentTrackId }
+ ?: SongPlayer.engineQueue.value.current?.takeIf { it.spotifyTrackId == currentTrackId }
+ start(page, current, SongPlayer.getCurrentPosition())
return true
}
}
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 ea04bf96..7ef6ea6d 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
@@ -225,7 +225,15 @@ fun PlayerScreen(navController: NavController) {
val displayedTrackId = confirmedTrackIdForDisplay(np.uri, songId)
// Smooth progress: redrawn every frame from the engine clock (see SpotifySeekBar).
- val frame = com.music.spotui.ui.components.rememberFrameClock(songPlayingState && !audioBuffering, fps = 15)
+ // As many ticks as the knob has pixels to move: ~5 a second on a 3-minute song, up to 15 on
+ // a short one. Each tick redraws the whole window, so 15 on every song was ~3x the work for
+ // steps nobody can see.
+ val barFps = run {
+ val d = com.music.spotui.video.MusicVideoController.duration()
+ val widthPx = context.resources.displayMetrics.widthPixels
+ if (d > 0) (widthPx * 1000L / d).toInt().coerceIn(4, 15) else 15
+ }
+ val frame = com.music.spotui.ui.components.rememberFrameClock(songPlayingState && !audioBuffering, fps = barFps)
// ── Swipe the artwork to change track: [previous, current, next] from Spotify ──
val artworkPagerState = rememberPagerState(initialPage = 1, pageCount = { 3 })
@@ -674,6 +682,7 @@ private fun ImmersiveStrip(
.fillMaxWidth()
.height(2.dp)
.clip(RoundedCornerShape(1.dp))
+ .graphicsLayer()
.drawBehind {
drawRect(Color.White.copy(alpha = 0.3f))
val played = fraction().coerceIn(0f, 1f)
@@ -987,6 +996,10 @@ fun SpotifySeekBar(
androidx.compose.foundation.Canvas(
modifier = modifier
.height(24.dp)
+ // Its own layer: each tick of the clock re-records only the bar. Without it the
+ // tick invalidated the player's whole layer (cover included): ~5 ms of UI thread
+ // per tick at 15 ticks a second, measured with Perfetto.
+ .graphicsLayer()
.semantics {
contentDescription = seekDescription
progressBarRangeInfo = ProgressBarRangeInfo(semanticProgress.value, 0f..1f)
diff --git a/base/host-android/src/main/kotlin/app/myspoti/host/android/ControlRelay.kt b/base/host-android/src/main/kotlin/app/myspoti/host/android/ControlRelay.kt
index c1bd4b3c..1e6e3450 100644
--- a/base/host-android/src/main/kotlin/app/myspoti/host/android/ControlRelay.kt
+++ b/base/host-android/src/main/kotlin/app/myspoti/host/android/ControlRelay.kt
@@ -212,7 +212,21 @@ internal class ControlRelay(private val view: WebView, private val fingerprint:
Logbook.log("relay: ad in $method ${shortPath(url)} (sample kept)")
}
- private fun shortPath(url: String) = url.substringBefore('?').substringAfter(".com").replace(Regex("[0-9a-f]{20,}"), "…")
+ /**
+ * The path with device ids hidden. A command's `from/<id>/to/<id>` keeps one fact: whether it
+ * targets this player itself (`to/self`) or another device (`to/other`) — a refusal of a
+ * command sent to the official app on the same account reads very differently from one sent
+ * to this player.
+ */
+ private fun shortPath(url: String): String {
+ val path = url.substringBefore('?').substringAfter(".com")
+ val ids = Regex("/from/([0-9a-f]{20,})/to/([0-9a-f]{20,})").find(path)
+ if (ids != null) {
+ val target = if (ids.groupValues[1] == ids.groupValues[2]) "self" else "other"
+ return path.replaceRange(ids.range, "/from/…/to/$target").replace(Regex("[0-9a-f]{20,}"), "…")
+ }
+ return path.replace(Regex("[0-9a-f]{20,}"), "…")
+ }
companion object {
/**
diff --git a/base/host-android/src/main/kotlin/app/myspoti/host/android/MyspotiRuntime.kt b/base/host-android/src/main/kotlin/app/myspoti/host/android/MyspotiRuntime.kt
index 98e5d087..355d02e1 100644
--- a/base/host-android/src/main/kotlin/app/myspoti/host/android/MyspotiRuntime.kt
+++ b/base/host-android/src/main/kotlin/app/myspoti/host/android/MyspotiRuntime.kt
@@ -39,8 +39,22 @@ object MyspotiRuntime {
// changes is logged when it changes, not once every 10 s whether or not anything happened.
scope.launch {
var last = ""
+ var planLogged = false
while (true) {
kotlinx.coroutines.delay(10_000)
+ // Once per signed-in session: the account's plan, the first thing a refused play
+ // (402) needs. No name, no id — only what decides what the account may play.
+ if (!planLogged && spotify.ready.value && runCatching { isSignedIn() }.getOrDefault(false)) {
+ planLogged = true
+ runCatching {
+ val a = spotify.raw.gql("accountAttributes", kotlinx.serialization.json.buildJsonObject { })
+ .let { (it as kotlinx.serialization.json.JsonObject)["data"] as kotlinx.serialization.json.JsonObject }
+ .let { (it["me"] as kotlinx.serialization.json.JsonObject)["account"] as kotlinx.serialization.json.JsonObject }
+ val attrs = a["attributes"] as? kotlinx.serialization.json.JsonObject
+ fun v(o: kotlinx.serialization.json.JsonObject?, k: String) = (o?.get(k) as? kotlinx.serialization.json.JsonPrimitive)?.content
+ Logbook.log("account: product=${v(a, "product")} country=${v(a, "country")} catalogue=${v(attrs, "catalogue")} onDemand=${v(attrs, "onDemand")} ads=${v(attrs, "ads")}")
+ }.onFailure { planLogged = false }
+ }
val s = spotify.player.state.value
// "login" alone said nothing (it only meant "the page is on a login URL"): a bug
// report needs the session itself — a token that is anonymous means no account.
diff --git a/base/host-android/src/main/kotlin/app/myspoti/host/android/WebPlayerHost.kt b/base/host-android/src/main/kotlin/app/myspoti/host/android/WebPlayerHost.kt
index b94cc7be..861877b9 100644
--- a/base/host-android/src/main/kotlin/app/myspoti/host/android/WebPlayerHost.kt
+++ b/base/host-android/src/main/kotlin/app/myspoti/host/android/WebPlayerHost.kt
@@ -179,6 +179,7 @@ class WebPlayerHost(private val context: Context) : BridgeHost {
override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) {
Logbook.log("page start ${url.take(120)}")
+ mainFrameFailed = false
pageStarts++
_url.value = url
_loginRequired.value = isLoginPage(url)
@@ -188,15 +189,19 @@ class WebPlayerHost(private val context: Context) : BridgeHost {
override fun onReceivedError(view: WebView, request: WebResourceRequest, error: android.webkit.WebResourceError) {
if (request.url.host?.contains("spotify") == true)
Logbook.log("load error ${error.errorCode} ${error.description} ${request.url.toString().take(120)}")
+ if (request.isForMainFrame && request.url.host == PLAYER_HOST) playerPageFailed("load error ${error.errorCode}")
}
override fun onReceivedHttpError(view: WebView, request: WebResourceRequest, response: WebResourceResponse) {
if (request.url.host?.contains("spotify") == true)
Logbook.log("http ${response.statusCode} ${request.method} ${request.url.toString().substringBefore('?').take(120)}")
+ if (request.isForMainFrame && request.url.host == PLAYER_HOST && (response.statusCode >= 500 || response.statusCode == 429))
+ playerPageFailed("http ${response.statusCode}")
}
override fun onPageFinished(view: WebView, url: String) {
Logbook.log("page finished ${url.take(120)}")
+ if (url.startsWith(PLAYER_URL) && !mainFrameFailed) { pageFailures = 0; main.removeCallbacks(retryPlayerPage) }
_url.value = url
_loginRequired.value = isLoginPage(url)
if (url.startsWith(PLAYER_URL)) onPageLoaded?.invoke()
@@ -288,6 +293,29 @@ class WebPlayerHost(private val context: Context) : BridgeHost {
/** The player's own URL, not the page's current one: the bridge parks the page on an empty route. */
fun reload() = main.post { view.loadUrl(PLAYER_URL) }
+ /*
+ * A player page that did not load (Spotify answering 504 to a reload, the network down at that
+ * moment) used to stay what it was: an error page, "not ready", every command refused, until
+ * the app was restarted (seen on the test phone after an ad recovery's reload). It is loaded
+ * again, sooner first, then once a minute, until a page loads.
+ */
+ private var mainFrameFailed = false
+ private var pageFailures = 0
+ private val retryPlayerPage = Runnable {
+ if (!loadAsked || _loginRequired.value) return@Runnable
+ Logbook.log("player page: load again (attempt ${pageFailures + 1})")
+ view.loadUrl(PLAYER_URL)
+ }
+
+ private fun playerPageFailed(what: String) {
+ mainFrameFailed = true
+ val wait = RETRY_PAGE_MS[pageFailures.coerceAtMost(RETRY_PAGE_MS.lastIndex)]
+ pageFailures++
+ Logbook.log("player page failed to load ($what): again in ${wait / 1000} s")
+ main.removeCallbacks(retryPlayerPage)
+ main.postDelayed(retryPlayerPage, wait)
+ }
+
fun openLogin() = main.post { view.loadUrl(LOGIN_URL) }
/** Signs out of Spotify in this WebView, then shows the login page. */
@@ -313,8 +341,15 @@ class WebPlayerHost(private val context: Context) : BridgeHost {
}
/**
- * Keeps the page attached to a window so Chromium runs it at full speed: a tiny,
- * non-interactive view in [container] while the player is hidden.
+ * Keeps the page attached to a window, a tiny non-interactive view in [container] while the
+ * player is hidden.
+ *
+ * Hidden means INVISIBLE, not a 1 px view at 1 % alpha: a drawn WebView is replayed by the
+ * app's RenderThread on every frame the app draws (measured with Perfetto on the player
+ * screen: `WebViewFunctor::drawVk` 3.7 ms plus a 1.5 ms `postAndWait` on the UI thread, per
+ * frame, for a pixel nobody sees), and the page kept animating its own UI underneath. The
+ * page then runs as it already does whenever the app is in the background or the screen is
+ * off, which is how most listening happens.
*/
fun attach(container: ViewGroup, visible: Boolean) = main.post {
this.container = container
@@ -324,7 +359,8 @@ class WebPlayerHost(private val context: Context) : BridgeHost {
(view.parent as? ViewGroup)?.removeView(view)
val size = if (visible) ViewGroup.LayoutParams.MATCH_PARENT else 1
container.addView(view, ViewGroup.LayoutParams(size, size))
- view.alpha = if (visible) 1f else 0.01f
+ view.alpha = 1f
+ view.visibility = if (visible) View.VISIBLE else View.INVISIBLE
view.importantForAccessibility = if (visible) View.IMPORTANT_FOR_ACCESSIBILITY_AUTO else View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
// Typing in the login form needs touch focus, or the keyboard never opens.
view.isFocusable = visible
@@ -345,6 +381,8 @@ class WebPlayerHost(private val context: Context) : BridgeHost {
/** Logcat tag of the engine: `adb logcat -s Myspoti`. */
const val LOG = "Myspoti"
const val PLAYER_URL = "https://open.spotify.com/"
+ private const val PLAYER_HOST = "open.spotify.com"
+ private val RETRY_PAGE_MS = longArrayOf(2_000, 5_000, 15_000, 30_000, 60_000)
private const val LOAD_WATCH_MS = 4_000L
private const val LOAD_RETRIES = 4
const val LOGIN_URL = "https://accounts.spotify.com/login?continue=https%3A%2F%2Fopen.spotify.com%2F"
diff --git a/tools/playback_test.py b/tools/playback_test.py
index d670b8a9..4e91fa7e 100644
--- a/tools/playback_test.py
+++ b/tools/playback_test.py
@@ -414,8 +414,14 @@ def s_frozen(r, ctx):
def s_mute(r, ctx):
cur = probe()["track"]["uri"]
- n = bridge("media.mute", {"on": True})
- p = probe()
+ # Muted and read in one page call: a mute the app did not ask for is undone by its own
+ # silence watchdog ("no silence until a restart") within a tick, so a separate probe could
+ # read the restored level and fail a mute that worked (seen once in 6 runs).
+ p = evaluate("""(async () => {
+ const n = await window.Myspoti.call(-1, 'media.mute', {on: true});
+ return {n, media: await window.Myspoti.call(-1, 'media.state', {})};
+ })()""")
+ n = p.get("n")
if not isinstance(p.get("media"), dict) or p["media"]["volume"] > 0.01:
raise Fail(f"media.mute on: element not silenced ({n} set, {p.get('media')})")
# Silenced, a song that restarts must still play (Chromium pauses muted hidden media).