Native Android client for Spotify, built with Jetpack Compose
Kotlin ad-freeadblockandroidjetpack-composekotlinlyricsmusic-playermusic-videomyspotispotifyspotify-adblockerspotify-clientspotify-connectspotui
Playback supervised against the page's media element: previous and the song after an ad no longer stay paused (no fade to 0, ads silenced without muted), reloads resume where the song was, a frozen page is caught in seconds, commands wait for the page and are retried, pull back reads the devices fresh and never hangs; playback scenario test on the phone
kota-zoa85d6fef6ea8
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 11c011dd..9e5c8aad 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,7 +5,11 @@ Each release on GitHub shows its section below. The app shows it too when it off## Unreleased- **Myspoti's icon in the notification** and in Samsung's Now Bar, instead of a generic music note.-- **Ads that get through are silent**: they are muted on the page itself, no longer through a Spotify Connect volume command that some accounts refuse (the ad was heard).+- **Ads that get through are silent**: they are muted on the page itself, no longer through a Spotify Connect volume command that some accounts refuse (the ad was heard). The song after the ad no longer stays paused.+- **Previous no longer pauses**: "previous" in the middle of a song restarts it and keeps playing (the skip fade left the sound at zero, and Android's WebView pauses silent media in the background).+- **Music comes back after a page reload**: when the player page reloads (frozen page, low memory, WebView restart) the song goes on where it was instead of staying paused; a frozen page is caught in a few seconds.+- **A song that stops being heard is restarted**: the app checks that the music really plays, not only what the page says.+- **Play right after launch works**: taps made while the player loads are sent once it is ready.- **Cover back to its full size** in the player.- **Myspoti's buttons play on this phone again** when another device (the Spotify app on the same account, for instance) took playback without being picked in Myspoti: the music comes back here first, instead of driving that device (where skips, previous and volume were refused).- **Music no longer stops for a minute**: a Web Player page that stops answering is reloaded at once, and playback goes on.diff --git a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyApi.kt b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyApi.ktindex b35731a5..2d24e2db 100644--- a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyApi.kt+++ b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyApi.kt@@ -79,5 +79,8 @@ class SpotifyApi(suspend fun onPageLoaded() = bridge.inject()+ /** The host calls this when a Web Player page load starts (reload, renderer back). */+ fun onPageStarting() = bridge.pageGone()+suspend fun awaitReady() { ready.first { it } }}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.ktindex 75e3a5d5..34082008 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@@ -19,7 +19,9 @@ import kotlinx.coroutines.launchimport kotlinx.serialization.json.JsonObjectimport kotlinx.serialization.json.addJsonObjectimport kotlinx.serialization.json.buildJsonObject+import kotlinx.serialization.json.booleanOrNullimport kotlinx.serialization.json.double+import kotlinx.serialization.json.doubleOrNullimport kotlinx.serialization.json.jsonPrimitiveimport kotlinx.serialization.json.putimport kotlinx.serialization.json.putJsonArray@@ -51,9 +53,9 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop@Volatile private var adSince = 0L@Volatile private var adState: PlayerState? = null/**- * An ad is muted. The page's own media element is muted, not the player's volume: the- * volume goes through Spotify Connect, which refuses it on some accounts- * (DEVICE_DOES_NOT_SUPPORT_COMMAND) and leaves the ad audible.+ * An ad is muted: the page's own media element is set to an unheard volume ("media.mute"),+ * not the player's volume, which goes through Spotify Connect and is refused on some+ * accounts (DEVICE_DOES_NOT_SUPPORT_COMMAND), leaving the ad audible.*/@Volatile private var adMuted = false/** A pause asked through [pause]; it holds until playback is asked for again, never expires. */@@ -96,7 +98,19 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop// A reloaded page starts on "auto": the chosen quality is set again.scope.launch {bridge.ready.collect {- if (!it) return@collect+ if (!it) {+ // The page went away (reloaded by Android, the WebView or the host): what+ // played then is picked up again once the new page is there.+ // A page that unloads reports "nothing plays" first: the song before that counts.+ val now = System.currentTimeMillis()+ val last = lastTrackState ?: lastSong?.takeIf { now - lastSongUntil < UNLOAD_NULL_MS }+ if (playingAtLoss == null) playingAtLoss = last?.takeIf { s -> !s.isPaused && !pausedByUser && s.item != null }+ ?.let { s -> s.copy(positionMs = s.positionAt(now), timestampMs = now) }+ return@collect+ }+ val lost = playingAtLoss+ playingAtLoss = null+ if (lost != null && !ownReload) scope.launch { runCatching { resumeAfterReload(lost) } }if (audioQuality != "auto") applyAudioQuality()// The page keeps its volume: an app closed during a muted ad must not stay silent.runCatching { if (volume() == 0.0) setVolume(wantedVolume?.takeIf { v -> v > 0.0 } ?: 1.0) }@@ -106,44 +120,141 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop}}- /** Reloads the page, waits for it, then plays on from [s]. */- private suspend fun reloadAndPlayOn(s: PlayerState?) {+ /** Set while [reloadAndPlayOn] runs: that reload says itself what plays next. */+ @Volatile private var ownReload = false+ /** What was playing when the page went away; null when nothing was. */+ @Volatile private var playingAtLoss: PlayerState? = null+ /** The last state with a song, and when the page stopped reporting it (a null state). */+ @Volatile private var lastSong: PlayerState? = null+ @Volatile private var lastSongUntil = 0L+ /** Bumped at every state the page reports. */+ @Volatile private var stateSeq = 0++ /**+ * Reloads the page, waits for it, then plays from [s]: the song after it ([next], a song+ * stuck at its end or an ad) or [s] itself where it was (a frozen page).+ */+ private suspend fun reloadAndPlayOn(s: PlayerState?, next: Boolean = true) {val reload = reloadHost ?: return- runCatching {+ ownReload = true+ try {+ runCatching {+ reload()+ withTimeoutOrNull(45_000) { delay(1_500); bridge.ready.first { it } } ?: return@runCatching+ if (s == null) return@runCatching+ if (next) { delay(1_500); playOn(s) } else resumeAfterReload(s)+ }+ } finally {+ ownReload = false+ playingAtLoss = null+ }+ }++ /**+ * Reloads the page and waits until it is ready again; nothing is played. For a page whose+ * Spotify Connect layer hangs (a transfer from a device that went away never ends).+ */+ suspend fun reloadPage(): Boolean {+ val reload = reloadHost ?: return false+ ownReload = true+ try {reload()- withTimeoutOrNull(45_000) { delay(1_500); bridge.ready.first { it } } ?: return@runCatching- delay(1_500)- s?.let { playOn(it) }+ return withTimeoutOrNull(45_000) { delay(1_500); bridge.ready.first { it } } != null+ } finally {+ ownReload = false+ playingAtLoss = null+ }+ }++ /**+ * A new page after [lost] was playing: the page restores the session paused, or not at+ * all, and takes commands only once its device is registered again. The song goes on from+ * where it was, checked and tried again, unless the user paused or played something since.+ */+ private suspend fun resumeAfterReload(lost: PlayerState) {+ val item = lost.item ?: return+ val uri = item.uri+ val at = lost.positionMs+ // A play newer than [since] is the user's: the restore stops there.+ var since = lastPlay?.third ?: 0L+ val seq = stateSeq+ // The restored session (or nothing, when the page has none): a real state, or a while.+ withTimeoutOrNull(RESTORE_WAIT_MS) { while (stateSeq == seq || _state.value?.item == null) delay(100) }+ bridge.logger?.invoke("page back after a reload: ${item.name} goes on at ${at / 1000} s")+ for (attempt in 1..RESTORE_ATTEMPTS) {+ if (pausedByUser || (lastPlay?.third ?: 0L) != since) return+ val s = _state.value+ if (s != null && s.item?.uri == uri && !s.isPaused) return+ runCatching {+ if (s?.item?.uri == uri) {+ resume()+ if (kotlin.math.abs(s.positionMs - at) > 5_000) seek(at)+ } else {+ val ctx = lost.contextUri ?: uri+ play(ctx, trackUri = uri.takeIf { ctx != it }, positionMs = at, order = lastOrder?.takeIf { it.first == ctx }?.second)+ }+ }.onFailure { bridge.logger?.invoke("restore attempt $attempt failed: ${it.message}") }+ // The play just sent is ours, not the user's.+ since = lastPlay?.third ?: 0L+ val ok = withTimeoutOrNull(RESTORE_CHECK_MS) { _state.first { it?.item?.uri == uri && !it.isPaused } }+ if (ok != null) return+ delay(RESTORE_GAP_MS * attempt)}+ bridge.logger?.invoke("page back after a reload: ${item.name} did not start again")+ }++ /** The page's media element as `media.state` reads it. [active]: null when unknown. */+ private data class Media(val paused: Boolean, val muted: Boolean, val level: Double, val own: Double, val time: Double, val active: Boolean?)++ private suspend fun readMedia(): Media? {+ val o = bridge.call("media.state", timeoutMs = MEDIA_TIMEOUT_MS, quiet = true) as? JsonObject ?: return null+ fun p(k: String) = o[k] as? kotlinx.serialization.json.JsonPrimitive+ return Media(+ paused = p("paused")?.booleanOrNull ?: true,+ muted = p("muted")?.booleanOrNull ?: false,+ level = p("level")?.doubleOrNull ?: 1.0,+ own = p("own")?.doubleOrNull ?: 1.0,+ time = p("time")?.doubleOrNull ?: 0.0,+ active = p("active")?.booleanOrNull,+ )}+ /**+ * Every [WATCH_TICK_MS]: the page answers (else it is frozen and reloaded), the song it+ * says it plays is heard (its media element moves), the sound is on, ads are got past,+ * and a song stuck between two others moves on.+ */private suspend fun watchStalls() {var key: String? = nullvar since = 0Lvar attempts = 0var adAttempts = 0var adReloaded = false- var frozenCheckAt = 0Lvar frozenReloadAt = 0Lvar tick = 0+ var lastMediaTime = -1.0+ var silentSince = 0Lwhile (true) {delay(WATCH_TICK_MS)tick++- val s = _state.value+ if (!bridge.ready.value || ownReload) { key = null; attempts = 0; silentSince = 0L; continue }val now = System.currentTimeMillis()- // A call timed out: is the page frozen (nothing answers, not even a sync call)?- // Then reload at once instead of waiting for each 20 s timeout to pass.- if (bridge.ready.value && now - bridge.lastTimeoutAt < FROZEN_WINDOW_MS && now - frozenCheckAt > FROZEN_WINDOW_MS) {- frozenCheckAt = now- if (!bridge.ping() && now - frozenReloadAt > FROZEN_RELOAD_GAP_MS) {+ // The page answers nothing, not even a ping: frozen (a stuck renderer). Reloaded+ // at once, the song going on where it was.+ val read = runCatching { readMedia() }+ if (read.isFailure && bridge.ready.value && !bridge.ping() && bridge.ready.value) {+ if (now - frozenReloadAt > FROZEN_RELOAD_GAP_MS) {frozenReloadAt = nowbridge.logger?.invoke("page not answering: reloading the player")- reloadAndPlayOn(if (pausedByUser) null else lastTrackState)- key = null; attempts = 0- continue+ val playing = lastTrackState?.takeIf { !pausedByUser && !it.isPaused }+ reloadAndPlayOn(playing?.copy(positionMs = playing.positionAt(now), timestampMs = now), next = false)+ key = null; attempts = 0; silentSince = 0L}+ continue}- if (tick % VOLUME_CHECK_TICKS == 0) guardVolume(s)+ val media = read.getOrNull()+ val s = _state.value+ if (tick % VOLUME_CHECK_TICKS == 0) guardVolume(s, media)if (_adPlaying.value) {val ad = adState// A refused ad sits at 0:00, buffering; a real one plays to its end.@@ -165,43 +276,64 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop}adSince = System.currentTimeMillis()}- key = null+ key = null; silentSince = 0Lcontinue}// A song really playing again: the ad break is over.if (s != null && !s.isPaused && !s.isBuffering) { adAttempts = 0; adReloaded = false }- val reason = s?.let { stallOf(it, now, pausedByUser) }+ // Silent: the state says this phone plays, yet its media element stands still.+ val fading = fadeBackTo != null || fadeBack?.isActive == true+ val playingHere = s != null && !s.isPaused && !s.isBuffering && media != null && media.active != false && !fading+ val moved = media != null && !media.paused && kotlin.math.abs(media.time - lastMediaTime) > 0.25+ lastMediaTime = media?.time ?: -1.0+ silentSince = if (playingHere && !moved) (if (silentSince == 0L) now else silentSince) else 0L+ val silent = silentSince != 0L && now - silentSince >= SILENT_MS+ val reason = s?.let { stallOf(it, now, pausedByUser) } ?: (if (silent) SILENT else null)if (s == null || reason == null) { key = null; attempts = 0; continue }val k = "${s.item?.uri}|$reason"- if (k != key) { key = k; since = now; attempts = 0; continue }- if (now - since < (if (reason == "past the end") END_STUCK_MS else STUCK_MS)) continue+ if (k != key) { key = k; since = now; attempts = 0; if (reason != SILENT) continue }+ val wait = when (reason) { "past the end" -> END_STUCK_MS; SILENT -> 0L; else -> STUCK_MS }+ if (now - since < wait) continuesince = nowattempts+++ silentSince = 0Lbridge.logger?.invoke("player stalled ($reason) on ${s.item?.name}, attempt $attempts")+ // A song stuck at its end moves on; one stuck in its middle goes on where it was.+ val onward = reason == "past the end" || reason == "paused at the end"// A frozen page answers nothing: straight to the reload.if (attempts == 1 && !bridge.ping()) attempts = 2- if (attempts == 1) runCatching { playOn(s) }+ if (attempts == 1) runCatching { if (onward) playOn(s) else seek(s.positionAt(now)) }else {attempts = 0- reloadAndPlayOn(s)+ reloadAndPlayOn(if (onward) s else s.copy(positionMs = s.positionAt(now), timestampMs = now), next = onward)}}}/**- * The page left silent while a song plays: a fade or an ad mute whose volume call was- * lost (page busy, reloaded). The sound comes back to what the user wants.+ * The page left silent while a song plays: a fade or an ad mute whose call was lost (page+ * busy, reloaded). The sound comes back to what the user wants.*/- private suspend fun guardVolume(s: PlayerState?) {+ private suspend fun guardVolume(s: PlayerState?, media: Media?) {if (s == null || s.isPaused || s.isBuffering || _adPlaying.value || fadeBackTo != null || fadeBack?.isActive == true) return// The unmute after an ad was lost (page busy): the song would play silent.if (adMuted) unmuteAfterAd()+ else if (media?.muted == true) {+ bridge.logger?.invoke("media element muted during a song: unmuted")+ runCatching { bridge.call("media.mute", buildJsonObject { put("on", false) }) }+ }val wanted = wantedVolume ?: 1.0if (wanted <= 0.0) returnval v = runCatching { volume() }.getOrNull() ?: return- if (v > 0.0) return- bridge.logger?.invoke("page silent during a song: volume back to $wanted")- runCatching { setLevel(wanted) }+ if (v <= 0.0) {+ bridge.logger?.invoke("page silent during a song: volume back to $wanted")+ runCatching { setVolume(wanted) }+ }+ // A fade that never came back: the element back to the page player's own volume.+ if (media != null && media.active != false && media.own > 0.001 && media.level < media.own * 0.5) {+ bridge.logger?.invoke("page player silent during a song: level ${media.level} back to ${media.own}")+ runCatching { restoreLevel() }+ }}/** Spotify refused the last play: once, the list is played from its start instead. */@@ -227,6 +359,7 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop}private fun onState(s: PlayerState?) {+ stateSeq++if (s?.item?.kind == ItemKind.AD) {// Keep showing the last real track, buffering, while the ad plays.if (!_adPlaying.value) {@@ -238,6 +371,8 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopreturn}_adPlaying.value = false+ if (s?.item != null) lastSong = s+ else if (lastTrackState?.item != null) lastSongUntil = System.currentTimeMillis()lastTrackState = s_state.value = s}@@ -250,15 +385,24 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop@Volatile private var fadeBackTo: Double? = nullprivate var fadeBack: kotlinx.coroutines.Job? = null+ /**+ * The page player's own level, on this phone: no Spotify Connect volume command, which+ * some accounts refuse (the fade then never came back) and which waits on the network.+ */private suspend fun setLevel(level: Double) {- bridge.call("volume.set", buildJsonObject { put("level", level.coerceIn(0.0, 1.0)) })+ bridge.call("media.volume", buildJsonObject { put("level", level.coerceIn(0.0, 1.0)) }, timeoutMs = LEVEL_TIMEOUT_MS, quiet = true)+ }++ /** The element back to the page player's own volume. */+ private suspend fun restoreLevel() {+ bridge.call("media.volume", buildJsonObject { put("restore", true) }, timeoutMs = LEVEL_TIMEOUT_MS, quiet = true)}private suspend fun withFade(block: suspend () -> Unit) {val s = _state.value// Nothing heard (paused, an ad muted): nothing to fade.if (s == null || s.isPaused || _adPlaying.value || adMuted) { block(); return }- val target = fadeBackTo ?: runCatching { volume() }.getOrNull()?.takeIf { it > 0.0 }?.also { wantedVolume = it } ?: run { block(); return }+ val target = fadeBackTo ?: runCatching { readMedia() }.getOrNull()?.takeIf { it.active != false }?.level?.takeIf { it > 0.0 } ?: run { block(); return }val from = s.item?.urifadeBackTo = targetfadeBack?.cancel()@@ -275,8 +419,9 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop_state.first { it != null && !it.isPaused && (it.item?.uri != from || it.positionMs < 1_500) }}val back = fadeBackTo ?: target- runCatching { for (f in FADE_STEPS.reversed().drop(1)) { setLevel(back * f); delay(FADE_STEP_MS) }; setLevel(back) }- .onFailure { runCatching { setLevel(back) } }+ // Ends on the page player's own volume: a volume change during the fade is kept.+ runCatching { for (f in FADE_STEPS.reversed().drop(1)) { setLevel(back * f); delay(FADE_STEP_MS) }; restoreLevel() }+ .onFailure { runCatching { restoreLevel() } }fadeBackTo = null}}@@ -300,7 +445,7 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScoprefusedRetried = falsepausedByUser = falsewithFade {- bridge.call("player.play", timeoutMs = PLAY_TIMEOUT_MS, args = buildJsonObject {+ command("player.play", timeoutMs = PLAY_TIMEOUT_MS, args = buildJsonObject {put("contextUri", contextUri)order?.let { uris -> putJsonArray("order") { uris.forEach { add(kotlinx.serialization.json.JsonPrimitive(it)) } } }trackUri?.let { put("trackUri", it) }@@ -310,11 +455,45 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop}}- override suspend fun pause() { pausedByUser = true; bridge.call("player.pause") }- override suspend fun resume() { pausedByUser = false; bridge.call("player.resume") }- override suspend fun seek(positionMs: Long) { bridge.call("player.seek", buildJsonObject { put("positionMs", positionMs) }) }- override suspend fun next() { pausedByUser = false; withFade { bridge.call("player.next") } }- override suspend fun previous() { pausedByUser = false; withFade { bridge.call("player.previous") } }+ /**+ * A playback command, sent again when the page was not able to take it yet: a page just+ * (re)loaded says "ready" a moment before Spotify Connect knows its device ("No such+ * device"), and a reload under way refuses everything ("not ready").+ */+ private suspend fun command(method: String, args: JsonObject = JsonObject(emptyMap()), timeoutMs: Long = 20_000): kotlinx.serialization.json.JsonElement {+ var attempt = 0+ while (true) {+ try {+ return bridge.call(method, args, timeoutMs)+ } catch (e: app.myspoti.spotify.bridge.BridgeException) {+ val transient = e.message.orEmpty().let { m -> TRANSIENT.any { it in m } }+ if (!transient || ++attempt > COMMAND_RETRIES) throw e+ bridge.logger?.invoke("$method not taken (${e.message}): sent again")+ delay(COMMAND_RETRY_MS * attempt)+ if (!bridge.ready.value) withTimeoutOrNull(READY_WAIT_MS) { bridge.ready.first { it } }+ }+ }+ }++ override suspend fun pause() { pausedByUser = true; command("player.pause") }+ override suspend fun resume() { pausedByUser = false; command("player.resume") }+ override suspend fun seek(positionMs: Long) { command("player.seek", buildJsonObject { put("positionMs", positionMs) }) }+ override suspend fun next() { pausedByUser = false; withFade { command("player.next") } }+ override suspend fun previous() {+ pausedByUser = false+ withFade {+ val s = _state.value+ runCatching { command("player.previous") }.onFailure { e ->+ // Refused by the page (a restriction on the account or the context): the song+ // starts over, or the one before plays, as the button would have done.+ val pos = s?.positionAt(System.currentTimeMillis()) ?: 0L+ val before = s?.previous?.takeIf { it.kind == ItemKind.TRACK }?.uri+ val ctx = s?.contextUri+ bridge.logger?.invoke("previous refused (${e.message}): ${if (pos > 3_000 || before == null || ctx == null) "song restarted" else "song before played"}")+ if (pos > 3_000 || before == null || ctx == null) seek(0) else play(ctx, trackUri = before, order = lastOrder?.takeIf { it.first == ctx }?.second)+ }+ }+ }override suspend fun setShuffle(on: Boolean) { bridge.call("player.setShuffle", buildJsonObject { put("on", on) }) }override suspend fun setRepeat(mode: Repeat) {@@ -337,7 +516,7 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopprivate fun ref(item: NowPlaying) = buildJsonObject { put("uri", item.uri); item.uid?.let { put("uid", it) } }- override suspend fun skipTo(item: NowPlaying) { pausedByUser = false; withFade { bridge.call("queue.skipTo", ref(item)) } }+ override suspend fun skipTo(item: NowPlaying) { pausedByUser = false; withFade { command("queue.skipTo", ref(item)) } }override suspend fun playNext(uris: List<Uri>) {val first = _queue.value?.queued?.firstOrNull()@@ -393,10 +572,32 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopcompanion object {/** A refused ad left current that long: the page will not move on by itself. */const val AD_STUCK_MS = 4_000L+ /** A reloaded page reports its restored state within that long. */+ const val RESTORE_WAIT_MS = 6_000L+ /** A page going away reports "nothing plays" that long before it is gone, at most. */+ const val UNLOAD_NULL_MS = 5_000L+ /** Errors of a page not able to take a command yet (see [command]). */+ val TRANSIENT = listOf("No such device", "not ready", "page reloaded")+ const val COMMAND_RETRIES = 3+ const val COMMAND_RETRY_MS = 700L+ const val READY_WAIT_MS = 30_000L+ /** After a reload, the song is asked for again that many times at most. */+ const val RESTORE_ATTEMPTS = 3+ /** A restore that has not started the song by then is tried again. */+ const val RESTORE_CHECK_MS = 5_000L+ const val RESTORE_GAP_MS = 1_500L+ /** The media element read each tick; a page that cannot answer that fast is pinged. */+ const val MEDIA_TIMEOUT_MS = 3_000L+ const val LEVEL_TIMEOUT_MS = 3_000L+ /** A song the page says it plays here while its media element stands still that long. */+ const val SILENT_MS = 6_000L+ const val SILENT = "silent"/** Longer than any ad break: the page is stuck in it. */const val AD_BREAK_MAX_MS = 4 * 60_000L/** Volume steps of a fade (down; reversed to come back). */- val FADE_STEPS = listOf(0.55, 0.25, 0.08, 0.0)+ // Never 0: Chromium pauses a hidden page's media that (re)starts at volume 0 (a+ // "previous" that restarts the song stayed paused); the bridge keeps a floor.+ val FADE_STEPS = listOf(0.55, 0.25, 0.08, 0.002)const val FADE_STEP_MS = 25L/** The sound always comes back after that long, whatever the page does. */const val FADE_BACK_MAX_MS = 2_500L@@ -404,8 +605,6 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopconst val PLAY_TIMEOUT_MS = 10_000L/** A refusal that long after a play belongs to it. */const val REFUSED_WINDOW_MS = 5_000L- /** After a timed-out call, the page is pinged at most once per window. */- const val FROZEN_WINDOW_MS = 25_000L/** Never two "frozen page" reloads closer than that. */const val FROZEN_RELOAD_GAP_MS = 60_000L/** The volume is checked every that many ticks. */diff --git a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/bridge/Bridge.kt b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/bridge/Bridge.ktindex cb96de05..e037119b 100644--- a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/bridge/Bridge.kt+++ b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/bridge/Bridge.kt@@ -62,7 +62,7 @@ class Bridge(private val host: BridgeHost, scope: CoroutineScope) {} else if (type != "queue") log("page $type: " + raw.take(300))}when (type) {- "ready" -> _ready.value = true+ "ready" -> { gone = false; _ready.value = true }"result" -> {val id = field("id")?.intOrNull ?: returnval waiter = pending.remove(id) ?: return@@ -83,6 +83,19 @@ class Bridge(private val host: BridgeHost, scope: CoroutineScope) {host.evaluate(BridgeScript.source)}+ /**+ * The page is going away (a reload or a new load started): not ready until the bridge is+ * injected again, and the calls still waiting fail now instead of each timing out.+ */+ fun pageGone() {+ gone = true+ _ready.value = false+ pending.values.forEach { it.completeExceptionally(BridgeException("page reloaded")) }+ }++ /** Between [pageGone] and the new page's "ready". */+ @Volatile private var gone = false+/** When a call last timed out (0: never). A frozen page times out every call. */@Volatile var lastTimeoutAt = 0Lprivate set@@ -93,13 +106,16 @@ class Bridge(private val host: BridgeHost, scope: CoroutineScope) {*/suspend fun ping(timeoutMs: Long = 3_000): Boolean = runCatching { call("bridge.version", timeoutMs = timeoutMs) }.isSuccess- suspend fun call(method: String, args: JsonObject = JsonObject(emptyMap()), timeoutMs: Long = 20_000): JsonElement {+ /** [quiet]: a poll made every few seconds; only its failures are logged. */+ suspend fun call(method: String, args: JsonObject = JsonObject(emptyMap()), timeoutMs: Long = 20_000, quiet: Boolean = false): JsonElement {+ // The page is reloading: nothing would answer, the call would only wait for its timeout.+ if (gone) throw BridgeException("not ready")val id = ids.incrementAndGet()val waiter = CompletableDeferred<JsonElement>()pending[id] = waitertry {val started = System.currentTimeMillis()- logger?.invoke("call #$id $method ${args.toString().take(200)}")+ if (!quiet) logger?.invoke("call #$id $method ${args.toString().take(200)}")host.evaluate("window.Myspoti && window.Myspoti.call($id, ${json.encodeToString(JsonElement.serializer(), kotlinx.serialization.json.JsonPrimitive(method))}, $args).catch(() => {})")return try {// withTimeoutOrNull, not withTimeout: a timeout must surface as a@@ -109,12 +125,13 @@ class Bridge(private val host: BridgeHost, scope: CoroutineScope) {val result = withTimeoutOrNull(timeoutMs) { waiter.await() }?: throw BridgeException("timeout after $timeoutMs ms: $method")result.also {+ if (quiet) return@alsoval shown = if (method == "token.get") "(token hidden)" else it.toString().take(200)logger?.invoke("call #$id $method ok in ${System.currentTimeMillis() - started} ms: $shown")}} catch (e: Exception) {if (e is BridgeException && e.message?.startsWith("timeout") == true) lastTimeoutAt = System.currentTimeMillis()- logger?.invoke("call #$id $method FAILED after ${System.currentTimeMillis() - started} ms: ${e.message}")+ logger?.invoke("call #$id $method${if (quiet) " " + args.toString().take(100) else ""} FAILED after ${System.currentTimeMillis() - started} ms: ${e.message}")throw e}} finally {diff --git a/base/api-spotify/src/main/resources/bridge/player-bridge.js b/base/api-spotify/src/main/resources/bridge/player-bridge.jsindex ef5b5a8e..3ac580a8 100644--- a/base/api-spotify/src/main/resources/bridge/player-bridge.js+++ b/base/api-spotify/src/main/resources/bridge/player-bridge.js@@ -197,6 +197,23 @@return [...found];};+ // The page's own audio player (PlayerSDK.harmony's streamer), once it exists.+ const localPlayer = async () => {+ const sdk = need().resolve('PlayerSDK');+ const streamer = sdk && sdk.harmony && sdk.harmony._streamer;+ if (!streamer || !streamer._playerPromise) return null;+ return Promise.race([streamer._playerPromise, new Promise(r => setTimeout(() => r(null), 2000))]);+ };++ // Not heard, yet not "muted audio" to Chromium (see 'media.mute').+ const SILENT = 0.001;++ // The element volume the page player itself sets for its volume (cubic curve or not).+ const ownLevel = player => {+ const v = typeof player._playerVolume === 'number' ? player._playerVolume : 1;+ return player._cubicVolume ? v * v * v : v;+ };+// --- commands -------------------------------------------------------------const need = () => {@@ -269,13 +286,47 @@// Mutes the page's own media elements (ads), whatever Spotify Connect says about the// volume. Elements are known from the host's document-start hook (window.__mspMedia),// or found in the document. {on} -> how many elements were set.+ //+ // Not `muted`, and never volume 0: Chromium pauses a hidden page's media that starts (a+ // new song, a restart, a seek) muted or at volume 0, and the song after the ad stayed+ // paused. A volume of SILENT is not heard and keeps playback going.'media.mute': async a => {window.__mspMuted = !!a.on;+ const player = await localPlayer().catch(() => null);const els = new Set([...(window.__mspMedia || []), ...document.querySelectorAll('audio, video'), ...await playerMedia()]);- for (const el of els) el.muted = !!a.on;+ for (const el of els) {+ el.muted = false;+ el.volume = a.on ? SILENT : (player && el === player._player ? ownLevel(player) : 1);+ }return els.size;},+ // The page player's own media element now: what is really heard, whatever the state says.+ // active: this page is Spotify Connect's active device (else the state is another device's).+ // level: the element's volume (0..1), which local fades move; own: the level the page+ // player itself wants there.+ // -> {paused, muted, volume, level, own, time, readyState, ended, active} | null (no element yet)+ 'media.state': async () => {+ const player = await localPlayer();+ const el = player && player._player;+ if (!(el instanceof HTMLMediaElement)) return null;+ let active = null;+ try { const me = (await need().resolve('ConnectDevicesAPI').getDevices()).find(d => d.isLocal); active = !!(me && me.isActive); } catch (e) { /* unknown */ }+ return { paused: el.paused, muted: el.muted, volume: el.volume, level: el.volume, own: ownLevel(player), time: el.currentTime, readyState: el.readyState, ended: el.ended, active };+ },+ // The media element's volume, on this phone only: no Spotify Connect command (refused on+ // some accounts, slow on a busy network) and nothing reported to Spotify, as the player's+ // own setVolume would. Fades go through it. {level} | {restore: true} (the player's own+ // volume back) -> the level set.+ 'media.volume': async a => {+ const player = await localPlayer();+ const el = player && player._player;+ if (!(el instanceof HTMLMediaElement)) return null;+ // Never 0: see 'media.mute'.+ el.volume = a.restore ? ownLevel(player) : Math.min(1, Math.max(SILENT, Number(a.level) || 0));+ return el.volume;+ },+'volume.get': () => need().playback.getVolume(),'volume.set': a => need().playback.setVolume(a.level),diff --git a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/StallTest.kt b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/StallTest.ktindex 355f44b6..85681b8b 100644--- a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/StallTest.kt+++ b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/StallTest.kt@@ -31,4 +31,7 @@ class StallTest {assertEquals("next", SpotifyPlayer.adRecovery(2))assertEquals("reload", SpotifyPlayer.adRecovery(3))}++ // Chromium pauses a hidden page's media that (re)starts at volume 0.+ @Test fun `a fade never reaches volume 0`() = SpotifyPlayer.FADE_STEPS.forEach { assertEquals(true, it > 0.0) }}diff --git a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/bridge/BridgeMessagesTest.kt b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/bridge/BridgeMessagesTest.ktindex c06028cd..5b761a8a 100644--- a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/bridge/BridgeMessagesTest.kt+++ b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/bridge/BridgeMessagesTest.kt@@ -54,4 +54,18 @@ class BridgeMessagesTest {val bridge = bridgeAfterGarbage { id -> """{"type":"result","id":$id,"ok":"yes","error":{"m":1}}""" }assertThrows(BridgeException::class.java) { runBlocking { bridge.call("bridge.version", timeoutMs = 2_000) } }}++ @Test fun `a page going away fails calls at once, the next page answers again`() = runBlocking {+ val host = FakeHost { id -> """{"type":"result","id":$id,"ok":true,"value":1}""" }+ val bridge = Bridge(host, scope)+ host.messages.subscriptionCount.first { it > 0 }+ bridge.pageGone()+ val started = System.currentTimeMillis()+ val e = assertThrows(BridgeException::class.java) { runBlocking { bridge.call("bridge.version", timeoutMs = 5_000) } }+ assertEquals("not ready", e.message)+ assertEquals(true, System.currentTimeMillis() - started < 1_000)+ host.messages.emit("""{"type":"ready","version":1}""")+ bridge.ready.first { it }+ assertEquals(JsonPrimitive(1), bridge.call("bridge.version", timeoutMs = 2_000))+ }}diff --git a/base/app/src/debug/AndroidManifest.xml b/base/app/src/debug/AndroidManifest.xmlnew file mode 100644index 00000000..54bbe510--- /dev/null+++ b/base/app/src/debug/AndroidManifest.xml@@ -0,0 +1,15 @@+<?xml version="1.0" encoding="utf-8"?>+<manifest xmlns:android="http://schemas.android.com/apk/res/android">+ <application>+ <!-- Debug builds only: tools/playback_test.py drives the player through it. DUMP is held+ by the adb shell, not by other apps. -->+ <receiver+ android:name="com.music.spotui.di.TestControlReceiver"+ android:exported="true"+ android:permission="android.permission.DUMP">+ <intent-filter>+ <action android:name="app.myspoti.TEST" />+ </intent-filter>+ </receiver>+ </application>+</manifest>diff --git a/base/app/src/debug/java/com/music/spotui/di/TestControlReceiver.kt b/base/app/src/debug/java/com/music/spotui/di/TestControlReceiver.ktnew file mode 100644index 00000000..f78b09e0--- /dev/null+++ b/base/app/src/debug/java/com/music/spotui/di/TestControlReceiver.kt@@ -0,0 +1,27 @@+package com.music.spotui.di++import android.content.BroadcastReceiver+import android.content.Context+import android.content.Intent+import android.util.Log++/**+ * Debug builds only: the playback test (tools/playback_test.py) sends the app's own+ * commands, as a tap would, with+ * `adb shell am broadcast -a app.myspoti.TEST -p app.myspoti.dev --es cmd <cmd> ...`.+ * cmd: play (--es track <uri> --es context <uri>), resume, pause, next, previous, seek (--el ms <n>).+ */+class TestControlReceiver : BroadcastReceiver() {+ override fun onReceive(context: Context, intent: Intent) {+ val cmd = intent.getStringExtra("cmd").orEmpty()+ Log.i("MspPlayer", "test command $cmd")+ when (cmd) {+ "play" -> SongPlayer.playSong(intent.getStringExtra("track").orEmpty(), contextUri = intent.getStringExtra("context"))+ "resume" -> SongPlayer.play()+ "pause" -> SongPlayer.pause()+ "next" -> SongPlayer.next()+ "previous" -> SongPlayer.previous()+ "seek" -> SongPlayer.seekTo(intent.getLongExtra("ms", 0L))+ }+ }+}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.ktindex 22c071ef..e47c858a 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@@ -448,12 +448,20 @@ object SongPlayer {* at once raced in the Web Player (a skip and a play crossing, a player stuck on one* song until restarted); one still waiting when a newer one comes is dropped.*/- private fun transport(block: suspend (isLatest: () -> Boolean) -> Unit) {+ /** [pullBack]: playback taken by another device comes back here first (not for a pause). */+ private fun transport(pullBack: Boolean = true, block: suspend (isLatest: () -> Boolean) -> Unit) {val gen = transportGen.incrementAndGet()scope.launch {transportLock.withLock {if (gen != transportGen.get()) return@withLock- takeBackPlayback()+ // A tap while the page loads (cold start, a reload): sent once it is there,+ // instead of failing at once with "not ready".+ if (!api.ready.value && kotlinx.coroutines.withTimeoutOrNull(READY_WAIT_MS) { api.ready.first { it } } == null) {+ Log.w(TAG, "transport dropped: the player page is not ready")+ return@withLock+ }+ if (gen != transportGen.get()) return@withLock+ if (pullBack) takeBackPlayback()runCatching { kotlinx.coroutines.withTimeout(TRANSPORT_TIMEOUT_MS) { block { gen == transportGen.get() } } }.onFailure { Log.w(TAG, "transport failed: ${it.message}") }}@@ -536,7 +544,7 @@ object SongPlayer {if (LocalPlayer.active.value) { LocalPlayer.pause(); return }intendPaused()positionMs = getCurrentPosition(); positionAt = SystemClock.elapsedRealtime(); playing = false- transport { api.player.pause() }+ transport(pullBack = false) { api.player.pause() }}fun stop() = pause()@@ -566,6 +574,10 @@ object SongPlayer {private const val SHUFFLE_QUEUE_MAX = 50/** After pulling playback back, the page needs a moment before it takes commands. */private const val PULL_BACK_SETTLE_MS = 600L+ private const val PULL_BACK_WAIT_MS = 6_000L+ private const val DEVICES_WAIT_MS = 2_000L+ /** A transport command waits that long for the page to load before it is dropped. */+ private const val READY_WAIT_MS = 30_000L/** Shuffle-play a list: Spotify picks the first track of its own shuffled context. */fun shufflePlay(songs: List<SongsModel>) {@@ -808,10 +820,24 @@ object SongPlayer {* where a free account's commands are refused. The music comes back to this phone first.*/private suspend fun takeBackPlayback() {+ // The device list as Spotify has it now: the one kept here is only refreshed on a song+ // change, and after a cold start it does not know a device that took playback before.+ kotlinx.coroutines.withTimeoutOrNull(DEVICES_WAIT_MS) { runCatching { api.devices.refresh() } }+ val active = api.devices.devices.value.firstOrNull { it.active }+ _activeDevice.value = active?.takeIf { !it.local }?.let { ConnectDevice(it.id, it.name, it.type, false, true) }val remote = _activeDevice.value ?: returnif (remote.id == chosenRemote) returnLog.i(TAG, "playback taken by ${remote.name}: pulled back here")- runCatching { api.devices.pullHere() }.onFailure { Log.w(TAG, "pull here failed: ${it.message}") }+ // Bounded: a transfer from a device that went away can leave the page's promise+ // pending for ever, and every later command waiting behind it.+ val pulled = kotlinx.coroutines.withTimeoutOrNull(PULL_BACK_WAIT_MS) { runCatching { api.devices.pullHere() } }+ if (pulled?.isSuccess != true) Log.w(TAG, "pull here failed: ${pulled?.exceptionOrNull()?.message ?: "no answer"}")+ // No answer: the page's Connect layer waits on that device and would hold every later+ // command. A new page claims playback for itself at the first command.+ if (pulled == null) {+ Log.w(TAG, "pull here hangs: player page reloaded")+ MyspotiRuntime.spotify.player.reloadPage()+ }_activeDevice.value = nullPlaybackService.setPlaybackDevice(false, remoteVolume)kotlinx.coroutines.delay(PULL_BACK_SETTLE_MS)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.ktindex ce92a54e..ca11c2b6 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@@ -86,6 +86,7 @@ internal class ControlRelay(private val view: WebView) {val text = it.body.string()android.util.Log.d(WebPlayerHost.LOG, "relay $method ${shortPath(url)} -> ${it.code}")if (it.code >= 400) android.util.Log.d(WebPlayerHost.LOG, "relay error body: ${text.take(400)}")+ if (debuggable && AD_MARK.containsMatchIn(text)) keepAdSample(method, url, body, text)reply(id, it.code, out.toString(), text)}}@@ -99,6 +100,16 @@ internal class ControlRelay(private val view: WebView) {)}+ private val debuggable = view.context.applicationInfo.flags and android.content.pm.ApplicationInfo.FLAG_DEBUGGABLE != 0++ /** Debug builds: a playback response that carries an ad, kept in cache/ad-samples for study. */+ private fun keepAdSample(method: String, url: String, sent: String?, received: String) = runCatching {+ val dir = java.io.File(view.context.cacheDir, "ad-samples").apply { mkdirs() }+ java.io.File(dir, "${System.currentTimeMillis()}.json").writeText(+ JSONObject().put("method", method).put("url", url.substringBefore('?')).put("sent", sent ?: "").put("received", received).toString())+ android.util.Log.d(WebPlayerHost.LOG, "relay: ad in $method ${shortPath(url)} (sample kept)")+ }+private fun shortPath(url: String) = url.substringBefore('?').substringAfter(".com").replace(Regex("[0-9a-f]{20,}"), "…")companion object {@@ -106,19 +117,22 @@ internal class ControlRelay(private val view: WebView) {fun isRelayed(url: String) = RELAYED.containsMatchIn(url)+ private val AD_MARK = Regex("\"is_advertisement\"\\s*:\\s*\"?true|spotify:ad:|\"ad_id\"")+/** Wraps window.fetch; the same pattern as [RELAYED]. */private val SCRIPT = """(() => {if (window.__mspNetInstalled || !window.MyspotiNet) return;window.__mspNetInstalled = true;// The player's media elements, often never added to the document: the bridge- // mutes them during an ad ("media.mute"); one started while muted starts muted.+ // silences them during an ad ("media.mute"); one started then starts silent.+ // Silent is a tiny volume, never muted: Chromium pauses muted media of a hidden page.const media = new Set();window.__mspMedia = media;const play = HTMLMediaElement.prototype.play;HTMLMediaElement.prototype.play = function () {media.add(this);- if (window.__mspMuted) this.muted = true;+ if (window.__mspMuted) { this.muted = false; this.volume = 0.001; }return play.apply(this, arguments);};const relayed = /^https:\/\/[a-z0-9-]+(\.[a-z0-9-]+)*\.spotify\.com\/(connect-state|track-playback)\/v1\//;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.ktindex b85b1f9b..9f476eac 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@@ -33,6 +33,7 @@ object MyspotiRuntime {spotify = SpotifyApi(host, scope, language = Locale.getDefault().language, ops = updater.load())spotify.bridge.logger = { line -> android.util.Log.d(WebPlayerHost.LOG, line) }host.onPageLoaded = { scope.launch { spotify.onPageLoaded() } }+ host.onPageStarting = { spotify.onPageStarting() }spotify.player.reloadHost = { host.reload() }// Every 10 s: is the bridge ready, what does the player say (diagnostics in Logcat).scope.launch {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.ktindex 7ee5d39b..0717bde0 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@@ -52,6 +52,9 @@ class WebPlayerHost(context: Context) : BridgeHost {/** Fires after each Web Player page load; the API injects the bridge then. */var onPageLoaded: (() -> Unit)? = null+ /** Fires when a Web Player page load starts: the old page and its bridge are gone. */+ var onPageStarting: (() -> Unit)? = null+init {// Debug builds only: lets desktop tools (chrome://inspect, CDP) look at the page.val debuggable = context.applicationInfo.flags and android.content.pm.ApplicationInfo.FLAG_DEBUGGABLE != 0@@ -128,7 +131,7 @@ class WebPlayerHost(context: Context) : BridgeHost {pageStarts++_url.value = url_loginRequired.value = isLoginPage(url)- if (url.startsWith(PLAYER_URL)) relay.injectNow()+ if (url.startsWith(PLAYER_URL)) { onPageStarting?.invoke(); relay.injectNow() }}override fun onReceivedError(view: WebView, request: WebResourceRequest, error: android.webkit.WebResourceError) {diff --git a/docs/CHANGELOG-full.md b/docs/CHANGELOG-full.mdindex 7b27aea9..5c0d3d37 100644--- a/docs/CHANGELOG-full.md+++ b/docs/CHANGELOG-full.md@@ -5,6 +5,14 @@ Every change, release by release. The short version is in [CHANGELOG.md](../CHAN## Unreleased- **Notification icon**: the media notification (status bar, Samsung Now Bar) showed the engine's generic two-note icon; the app now ships its wave mark under the same resource name, so it replaces it.+- **Silent media is paused by the WebView**: Chromium pauses a hidden page's media that starts (new song, restart, seek) while muted or at volume 0. Skip fades went down to 0 and ads were muted with `muted`, so "previous" mid-song and the song after an ad stayed paused. Fades now stop at a tiny level and ads are silenced with an unheard element volume (0.001), never `muted`.+- **Fades are local**: they move the media element's volume, no longer the Spotify Connect volume (a network command, refused on some accounts, which could leave the sound at 0). The volume guard checks the element too.+- **Playback supervisor**: every 2 s the page's media element is read (`media.state`). A song the page says it plays here while the element stands still for 6 s is nudged (seek where it was), then the page is reloaded. A page that answers neither that read nor a ping is reloaded at once (a few seconds instead of a 20 s call timeout).+- **Reloads resume**: any reload (ours, the WebView's, a renderer restart) remembers the song that played and its position; once the new page is up it is resumed or played again there, checked and retried up to 3 times (a new page says ready before Spotify Connect knows its device: "No such device").+- **Commands while the page loads**: calls during a reload fail at once instead of timing out; play / pause / skip wait up to 30 s for the page; playback commands refused with "No such device" are sent again.+- **Pull back from another device**: the active device is read fresh before each transport command (after a cold start the app did not know another device had playback); the pull is bounded to 6 s, and a pull that hangs (a device that went away) reloads the page, which then claims playback itself. A pause never pulls playback back.+- **Previous refused** by the page: the song restarts, or the one before plays.+- **Debug builds**: `tools/playback_test.py` drives the phone through 14 playback scenarios (debug-only `TestControlReceiver`), and track-playback responses carrying an ad are kept in `cache/ad-samples`.## 2.0.0-beta.6diff --git a/tools/playback_test.py b/tools/playback_test.pynew file mode 100644index 00000000..d23bd371--- /dev/null+++ b/tools/playback_test.py@@ -0,0 +1,533 @@+#!/usr/bin/env python3+"""Playback scenarios on a phone (debug build app.myspoti.dev, signed in).++usage: tools/playback_test.py [--serial S] [--only name,name] [--skip name,name] [--playlist URI]++Drives the app as a user would: media keys (notification, headset path) and the debug-only+test receiver (TestControlReceiver: the app's own play / seek commands). Reads the page through+CDP (tools/cdp.py) and the app's log (adb logcat -s Myspoti MspPlayer).++After each step: the expected song is current, not paused, its position advances (page state+and the page's media element), the page volume is above 0 and the media element is not muted.+Log lines that mean trouble (call timeouts, stalls, a frozen page) fail the scenario unless it+provoked them. Ads that come up are waited out; one heard (element not muted) is a failure.+Exit code 0 when every scenario passes.+"""+import argparse, json, os, re, shlex, subprocess, sys, threading, time, urllib.request++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+import cdp # noqa: E402++ADB = cdp.ADB+PKG = "app.myspoti.dev"+OTHERS = ["app.myspoti", "com.spotify.music"]+PLAYLIST = "spotify:playlist:5G7gcsU1CbvqYJYFawDRZa"+BAD = [+ (re.compile(r"timeout after \d+ ms"), "call timeout"),+ (re.compile(r"player stalled"), "player stalled"),+ (re.compile(r"page not answering"), "page not answering"),+ (re.compile(r"transport failed"), "transport failed"),+ (re.compile(r"page silent during a song"), "page left silent"),+ (re.compile(r"play of \S+ not taken"), "play not taken"),+ (re.compile(r"command failed"), "command failed"),+ (re.compile(r"FATAL EXCEPTION|AndroidRuntime"), "crash"),+]++SERIAL = None+++def adb(*args, check=True, timeout=60):+ cmd = [ADB] + (["-s", SERIAL] if SERIAL else []) + list(args)+ r = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout)+ if check and r.returncode:+ raise RuntimeError(f"adb {' '.join(args)}: {r.stderr.strip()}")+ return r.stdout.strip()+++# ── page (CDP) ────────────────────────────────────────────────────────────────++def page_socket():+ ps = adb("shell", "ps", "-A", "-o", "PID,NAME")+ unix = adb("shell", "cat", "/proc/net/unix")+ pid = next((l.split()[0] for l in ps.splitlines()[1:] if l.split()[-1] == PKG+ and f"webview_devtools_remote_{l.split()[0]}" in unix), "")+ if not pid:+ raise RuntimeError("app not running")+ adb("forward", f"tcp:{cdp.PORT}", f"localabstract:webview_devtools_remote_{pid}")+ pages = json.load(urllib.request.urlopen(f"http://127.0.0.1:{cdp.PORT}/json", timeout=5))+ cands = [p for p in pages if p.get("type") == "page" and "open.spotify.com" in p.get("url", "")]+ page = next((p for p in cands if '"height":800' in p.get("description", "")), cands[0] if cands else None)+ if not page:+ raise RuntimeError("no open.spotify.com page")+ s = cdp.ws_connect(page["webSocketDebuggerUrl"])+ return s+++def evaluate(expr, timeout=12):+ """Runs [expr] in the page; returns its value, raises on an exception or no answer."""+ s = page_socket()+ try:+ s.settimeout(timeout)+ cdp.ws_send(s, json.dumps({"id": 1, "method": "Runtime.evaluate", "params": {+ "expression": expr, "awaitPromise": True, "returnByValue": True, "timeout": timeout * 1000}}))+ while True:+ msg = json.loads(cdp.ws_recv(s))+ if msg.get("id") == 1:+ r = msg.get("result", {})+ if "exceptionDetails" in r:+ raise RuntimeError("page exception: " + str(r["exceptionDetails"].get("exception", {}).get("description", ""))[:300])+ return r.get("result", {}).get("value")+ finally:+ s.close()+++def fire(expr):+ """Runs [expr] without waiting for it (a script that freezes the page)."""+ s = page_socket()+ try:+ cdp.ws_send(s, json.dumps({"id": 1, "method": "Runtime.evaluate", "params": {"expression": expr}}))+ time.sleep(0.5)+ finally:+ s.close()+++def bridge(method, args=None, timeout=12):+ a = json.dumps(args or {})+ return evaluate(f"window.Myspoti.call(-1, {json.dumps(method)}, {a})", timeout)+++PROBE = """(async () => {+ const t = (p, ms) => Promise.race([p, new Promise((_, j) => setTimeout(() => j(new Error('no answer')), ms))]);+ const c = (m, a) => t(window.Myspoti.call(-1, m, a || {}), 4000);+ const s = await c('player.state');+ const q = await c('player.queue');+ let vol = null, media = null;+ try { vol = await c('volume.get'); } catch (e) { vol = 'ERR ' + e.message; }+ try { media = await c('media.state'); } catch (e) { media = 'ERR ' + e.message; }+ const now = Date.now();+ const pos = s ? (s.isPaused || s.isBuffering ? s.positionMs : s.positionMs + (now - s.timestamp) * (s.speed || 1)) : null;+ return { now, track: s && s.track && { uri: s.track.uri, name: s.track.name, kind: s.track.kind, durationMs: s.track.durationMs },+ next: s && s.next && s.next.uri, previous: s && s.previous && s.previous.uri, context: s && s.contextUri,+ paused: s && s.isPaused, buffering: s && s.isBuffering, pos, restrictions: s && s.restrictions,+ upcoming: q ? [...q.queued, ...q.nextUp].map(i => i.uri) : [], volume: vol, media };+})()"""+++def probe():+ return evaluate(PROBE, timeout=15)+++# ── log ───────────────────────────────────────────────────────────────────────++class Log:+ def __init__(self):+ adb("logcat", "-c")+ self.lines = []+ cmd = [ADB] + (["-s", SERIAL] if SERIAL else []) + ["logcat", "-v", "time", "-s", "Myspoti:*", "MspPlayer:*", "AndroidRuntime:E"]+ self.proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, text=True, errors="replace")+ threading.Thread(target=self._read, daemon=True).start()++ def _read(self):+ for line in self.proc.stdout:+ self.lines.append(line.rstrip("\n"))++ def mark(self):+ return len(self.lines)++ def since(self, mark):+ return self.lines[mark:]++ def stop(self, path):+ self.proc.kill()+ os.makedirs(os.path.dirname(path), exist_ok=True)+ with open(path, "w") as f:+ f.write("\n".join(self.lines) + "\n")+++# ── checks ────────────────────────────────────────────────────────────────────++class Fail(Exception):+ pass+++def name(p):+ return (p.get("track") or {}).get("name") if p else None+++def is_ad(p):+ return bool(p and (p.get("track") or {}).get("kind") == "ad")+++def wait_for(cond, timeout, what, every=0.7):+ end = time.time() + timeout+ last, err = None, None+ while time.time() < end:+ try:+ last = probe()+ err = None+ if cond(last):+ return last+ except Exception as e: # page reloading, app starting+ err = e+ time.sleep(every)+ raise Fail(f"{what}: not after {timeout}s (last: {name(last)} paused={last and last.get('paused')} err={err})")+++class Run:+ def __init__(self, log):+ self.log = log+ self.ads = 0+ self.notes = []++ def wait_out_ad(self, p, budget=75):+ """An ad is current: it must be muted, and the app must get past it."""+ if not is_ad(p):+ return p+ self.ads += 1+ print(f" ad: {name(p)!r}, waiting it out")+ end = time.time() + budget+ while time.time() < end:+ if isinstance(p.get("media"), dict) and not p["media"]["muted"] and not p["media"]["paused"] and p["media"]["volume"] > 0 and p.get("volume", 0) not in (0, 0.0):+ raise Fail(f"ad {name(p)!r} audible (media not muted)")+ time.sleep(1)+ p = probe()+ if not is_ad(p):+ return p+ raise Fail(f"stuck on the ad {name(p)!r} for {budget}s")++ def healthy(self, expect=None, label="", settle=12, allow_track_change=False):+ """[expect] (uri) becomes current and plays: position and media time advance, sound on."""+ def ok(p):+ if is_ad(p):+ return True+ return p.get("track") and (expect is None or p["track"]["uri"] == expect) and not p.get("paused") and not p.get("buffering")+ p = wait_for(ok, settle, f"{label}: {expect or 'a song'} playing")+ p = self.wait_out_ad(p)+ if expect and p["track"]["uri"] != expect:+ if not allow_track_change and self.ads == 0:+ raise Fail(f"{label}: {name(p)!r} current, expected {expect}")+ a = p+ for _ in range(3):+ time.sleep(3)+ b = self.wait_out_ad(probe())+ # The song restarted in between (a previous, a seek): measure again from there.+ if b["track"]["uri"] == a["track"]["uri"] and (b["pos"] or 0) < (a["pos"] or 0) - 1500:+ a = b+ continue+ break+ problems = []+ if b.get("paused"):+ problems.append("paused")+ if b["track"]["uri"] == a["track"]["uri"] and (b["pos"] or 0) - (a["pos"] or 0) < 1500:+ problems.append(f"position stuck ({a['pos']} -> {b['pos']})")+ ma, mb = a.get("media"), b.get("media")+ if not isinstance(mb, dict):+ problems.append(f"no media element ({mb})")+ else:+ if mb["muted"]:+ problems.append("media element muted")+ if mb["paused"]:+ problems.append("media element paused")+ if mb["volume"] < 0.05:+ problems.append(f"media element silent (volume {mb['volume']})")+ if isinstance(ma, dict) and b["track"]["uri"] == a["track"]["uri"] and mb["time"] - ma["time"] < 1.5:+ problems.append(f"media time stuck ({ma['time']:.1f} -> {mb['time']:.1f})")+ if not isinstance(b.get("volume"), (int, float)) or b["volume"] <= 0:+ problems.append(f"page volume {b.get('volume')}")+ if problems:+ raise Fail(f"{label}: {name(b)!r} " + ", ".join(problems))+ return b++ def check_log(self, mark, allowed=()):+ bad = []+ for line in self.log.since(mark):+ for rx, what in BAD:+ if what not in allowed and rx.search(line):+ bad.append(line[:220])+ if bad:+ raise Fail("log: " + " | ".join(bad[:4]))+++def key(code):+ adb("shell", "input", "keyevent", *[str(c) for c in (code if isinstance(code, list) else [code])])+++def test(cmd, **extras):+ args = ["shell", "am", "broadcast", "-a", "app.myspoti.TEST", "-p", PKG, "--es", "cmd", cmd]+ for k, v in extras.items():+ args += (["--el", k, str(v)] if isinstance(v, int) else ["--es", k, shlex.quote(v)])+ adb(*args)+++NEXT, PREV, PLAY, PAUSE, HOME, SLEEP, WAKE = 87, 88, 126, 127, 3, 223, 224+++def launch():+ adb("shell", "monkey", "-p", PKG, "-c", "android.intent.category.LAUNCHER", "1")+++def wait_ready(timeout=60):+ return wait_for(lambda p: p.get("track") is not None, timeout, "page ready", every=1.5)+++def seek_to(r, ms):+ test("seek", ms=ms)+ wait_for(lambda p: p["pos"] is not None and abs(p["pos"] - ms) < 4000, 8, f"seek to {ms}")+++# ── scenarios ─────────────────────────────────────────────────────────────────++def s_play_playlist(r, ctx):+ tracks = evaluate(f"""(async () => {{+ const p = await window.Myspoti.call(-1, 'service.call', {{service: 'PlaylistAPI', method: 'getContents', args: [{json.dumps(ctx['playlist'])}, {{limit: 12}}]}});+ return p.items.filter(i => i.isPlayable).map(i => i.uri);+ }})()""")+ ctx["tracks"] = tracks+ test("play", track=tracks[0] + "|", context=ctx["playlist"])+ r.healthy(tracks[0], "play playlist", settle=15)+++def s_next(r, ctx):+ p = probe()+ exp = p["next"]+ key(NEXT)+ r.healthy(exp, "next")+++def s_rapid_next(r, ctx):+ p = probe()+ exp = p["upcoming"][4] if len(p["upcoming"]) > 4 else None+ key([NEXT] * 5)+ r.healthy(exp, "rapid next x5", settle=15)+++def s_previous_start(r, ctx):+ p = probe()+ if not p.get("previous"):+ key(NEXT)+ r.healthy(p.get("next"), "next before previous")+ p = probe()+ exp = p["previous"]+ seek_to(r, 0)+ time.sleep(1.5)+ key(PREV)+ r.healthy(exp, "previous at 0:02")+++def s_previous_middle(r, ctx):+ p = probe()+ cur = p["track"]["uri"]+ seek_to(r, 60_000)+ key(PREV)+ b = r.healthy(cur, "previous at 1:00")+ if b["pos"] > 10_000:+ raise Fail(f"previous at 1:00 did not restart the song (at {b['pos']} ms)")+++def s_seek(r, ctx):+ cur = probe()["track"]["uri"]+ seek_to(r, 90_000)+ b = r.healthy(cur, "seek")+ if not 88_000 < b["pos"] < 100_000:+ raise Fail(f"seek: at {b['pos']} ms, expected ~90 s")+++def s_pause_resume(r, ctx):+ cur = probe()["track"]["uri"]+ key(PAUSE)+ p = wait_for(lambda p: p.get("paused"), 6, "pause")+ time.sleep(3)+ q = probe()+ if not q.get("paused") or abs((q["pos"] or 0) - (p["pos"] or 0)) > 1500:+ raise Fail(f"pause did not hold ({p['pos']} -> {q['pos']}, paused={q.get('paused')})")+ if isinstance(q.get("media"), dict) and not q["media"]["paused"]:+ raise Fail("pause: media element still playing")+ key(PLAY)+ r.healthy(cur, "resume")+++def s_song_end(r, ctx):+ p = probe()+ exp, cur = p["next"], p["track"]["uri"]+ seek_to(r, p["track"]["durationMs"] - 6000)+ wait_for(lambda q: q["track"] and q["track"]["uri"] != cur, 25, "song end into the next one")+ r.healthy(exp, "song end")+++def s_background(r, ctx):+ key(HOME)+ time.sleep(1)+ key(SLEEP)+ try:+ start = time.time()+ while time.time() - start < 180:+ time.sleep(30)+ r.healthy(None, f"screen off {int(time.time() - start)}s", allow_track_change=True)+ finally:+ key(WAKE)+++def s_cold_start(r, ctx):+ cur = probe()["track"]["uri"]+ adb("shell", "am", "force-stop", PKG)+ time.sleep(1)+ launch()+ # Tapped as soon as the mini player shows: before the page is ready.+ time.sleep(2.5)+ test("resume")+ r.healthy(cur, "cold start then play", settle=60)+++def s_reload(r, ctx):+ cur = probe()["track"]["uri"]+ fire("location.reload()")+ time.sleep(3)+ r.healthy(cur, "page reloaded mid-song", settle=45)+++def s_frozen(r, ctx):+ cur = probe()["track"]["uri"]+ # The page's main thread blocked for 30 s, as a frozen renderer.+ fire("(() => { const end = Date.now() + 30000; while (Date.now() < end) {} })()")+ time.sleep(32)+ r.healthy(cur, "frozen page recovered", settle=60)+++def s_mute(r, ctx):+ cur = probe()["track"]["uri"]+ n = bridge("media.mute", {"on": True})+ p = probe()+ 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).+ seek_to(r, 0)+ time.sleep(2.5)+ q = probe()+ if q.get("paused") or (isinstance(q.get("media"), dict) and q["media"]["paused"]):+ bridge("media.mute", {"on": False})+ raise Fail("silenced song paused after a restart")+ bridge("media.mute", {"on": False})+ r.healthy(cur, "unmute")+++def s_pull_back(r, ctx):+ devices = bridge("service.call", {"service": "ConnectDevicesAPI", "method": "getDevices", "args": []})+ remote = next((d for d in devices if not d.get("isLocal")), None)+ started = False+ if not remote:+ # The Spotify app on this phone, signed in to the same account, as the other device.+ adb("shell", "monkey", "-p", "com.spotify.music", "-c", "android.intent.category.LAUNCHER", "1", check=False)+ started = True+ end = time.time() + 25+ while not remote and time.time() < end:+ time.sleep(2)+ devices = bridge("service.call", {"service": "ConnectDevicesAPI", "method": "getDevices", "args": []})+ remote = next((d for d in devices if not d.get("isLocal")), None)+ try:+ if not remote:+ r.notes.append("pull back: no other device on the account, skipped")+ return+ pull_back_from(r, remote)+ finally:+ if started:+ adb("shell", "am", "force-stop", "com.spotify.music", check=False)+++def pull_back_from(r, remote):+ cur = probe()["track"]["uri"]+ bridge("service.call", {"service": "ConnectTransferAPI", "method": "transferPlayback", "args": [remote["id"], {"playOnTransfer": True}]}, timeout=20)+ # Play is tapped from the notification, the Spotify app still in front, as soon as it has+ # playback (the free app leaves Spotify Connect a few seconds later).+ end = time.time() + 6+ taken = False+ while not taken and time.time() < end:+ time.sleep(0.4)+ devices = bridge("service.call", {"service": "ConnectDevicesAPI", "method": "getDevices", "args": []})+ taken = any(d.get("isActive") and not d.get("isLocal") for d in devices)+ if not taken:+ r.notes.append(f"pull back: {remote['name']} did not take playback (offline?), skipped")+ test("resume")+ r.healthy(None, "pull back (no transfer)", settle=20, allow_track_change=True)+ return+ test("resume")+ r.healthy(None, f"pull back from {remote['name']}", settle=20, allow_track_change=True)+ devices = bridge("service.call", {"service": "ConnectDevicesAPI", "method": "getDevices", "args": []})+ if not any(d.get("isActive") and d.get("isLocal") for d in devices):+ raise Fail("pull back: this phone is not the active device")+ if not any("taken by" in l for l in r.log.lines[-400:]):+ raise Fail("pull back: the app did not see the other device")+++SCENARIOS = [+ ("play_playlist", s_play_playlist, ()),+ ("next", s_next, ()),+ ("rapid_next", s_rapid_next, ()),+ ("previous_start", s_previous_start, ()),+ ("previous_middle", s_previous_middle, ()),+ ("seek", s_seek, ()),+ ("pause_resume", s_pause_resume, ()),+ ("song_end", s_song_end, ()),+ ("mute", s_mute, ()),+ ("reload", s_reload, ()),+ ("frozen", s_frozen, ("call timeout", "page not answering", "command failed", "transport failed")),+ ("background", s_background, ()),+ ("cold_start", s_cold_start, ()),+ ("pull_back", s_pull_back, ()),+]+++def main():+ global SERIAL+ ap = argparse.ArgumentParser()+ ap.add_argument("--serial")+ ap.add_argument("--only", default="")+ ap.add_argument("--skip", default="")+ ap.add_argument("--playlist", default=PLAYLIST)+ a = ap.parse_args()+ SERIAL = a.serial+ for p in OTHERS:+ adb("shell", "am", "force-stop", p, check=False)+ adb("shell", "input", "keyevent", str(WAKE))+ log = Log()+ if not adb("shell", "pidof", PKG, check=False):+ launch()+ wait_ready()+ only = set(filter(None, a.only.split(",")))+ skip = set(filter(None, a.skip.split(",")))+ ctx = {"playlist": a.playlist}+ results = []+ r = Run(log)+ for n, fn, allowed in SCENARIOS:+ if (only and n not in only and n != "play_playlist") or n in skip:+ continue+ mark = log.mark()+ log.lines.append(f"===== scenario {n}")+ t0 = time.time()+ r.ads = 0+ try:+ fn(r, ctx)+ time.sleep(1)+ r.check_log(mark, allowed)+ results.append((n, True, ""))+ print(f"PASS {n} ({time.time() - t0:.0f}s){' ads=' + str(r.ads) if r.ads else ''}")+ except Exception as e:+ results.append((n, False, str(e)))+ print(f"FAIL {n} ({time.time() - t0:.0f}s): {e}")+ # Back to a known state for the next scenario.+ try:+ test("resume")+ time.sleep(4)+ except Exception:+ pass+ path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "captures", "playback_test.log")+ log.stop(path)+ print("log:", path)+ for note in r.notes:+ print("note:", note)+ failed = [n for n, ok, _ in results if not ok]+ print(f"{len(results) - len(failed)}/{len(results)} passed" + (f"; failed: {', '.join(failed)}" if failed else ""))+ sys.exit(1 if failed else 0)+++if __name__ == "__main__":+ main()