Native Android client for Spotify, built with Jetpack Compose
Kotlin ad-freeadblockandroidjetpack-composekotlinlyricsmusic-playermusic-videomyspotispotifyspotify-adblockerspotify-clientspotify-connectspotui
Playback: recovery after ads and skips on slow networks (port of #74), the chosen song in big playlists, no fragment of the previous song on a skip, Spotify crossfade fades that really fade
kota-zod95a1c6f3c4e
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 fb968460..adcbb25b 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@@ -58,6 +58,13 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopprivate val _adPlaying = MutableStateFlow(false)/** An ad is playing (the page plays it to its end). */val adPlaying: StateFlow<Boolean> = _adPlaying+ private val _stalled = MutableStateFlow(false)+ /**+ * The state says this phone plays, but its sound stands still: the media element waits for+ * data (a slow network) or is paused. The page's own state often goes on as playing then,+ * its clock running over the silence; the screens stop theirs on this instead.+ */+ val stalled: StateFlow<Boolean> = _stalled@Volatile private var adSince = 0L@Volatile private var adState: PlayerState? = null/**@@ -83,11 +90,13 @@ 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+ /** The place in its list [lastPlay]'s song was sent with (see SongPlayer.rowIndex), or null. */+ @Volatile private var lastIndex: Int? = null/*** A song the user picked: the list, the song (null: the list from its start), when, and the* order given with it (a sorted list or a smart shuffle plays as that order, not as the list).*/- private data class Pick(val context: Uri, val track: Uri?, val at: Long, val order: List<Uri>?, val positionMs: Long? = null)+ private data class Pick(val context: Uri, val track: Uri?, val at: Long, val order: List<Uri>?, val positionMs: Long? = null, val index: Int? = null)/*** The pick an ad came in place of, or one made during the ad (the page refuses every play* then): asked again when the ad is over (see [onState]).@@ -255,7 +264,7 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScoppickAfterReload = nullif (liveIntent() != null) return falsebridge.logger?.invoke("playing the song picked before the ad, on the new page: ${pick.track ?: pick.context}")- runCatching { playNow(pick.context, trackUri = pick.track, positionMs = pick.positionMs, order = pick.order, refusable = true) }+ runCatching { playNow(pick.context, trackUri = pick.track, index = pick.index, positionMs = pick.positionMs, order = pick.order, refusable = true) }return true}@@ -424,6 +433,9 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopvar tick = 0var lastMediaTime = -1.0var silentSince = 0L+ /** Since when the sound stands still, for [stalled]. */+ var stillSince = 0L+ fun notStalled() { stillSince = 0L; _stalled.value = false }while (true) {// A song plays (or an ad is on): the watcher looks every [WATCH_TICK_MS] to hear a// stall in seconds. Nothing plays: there is less to see, so it looks less often.@@ -434,12 +446,13 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScoptick++// Repairs held (a sign-in page open, playback limited): nothing is judged, not even a// silent page, which is what a sign-in page looks like from here.- if (!bridge.ready.value || ownReload || recoveryHeld()) { key = null; attempts = 0; silentSince = 0L; frozenMisses = 0; continue }+ if (!bridge.ready.value || ownReload || recoveryHeld()) { key = null; attempts = 0; silentSince = 0L; frozenMisses = 0; notStalled(); continue }val now = System.currentTimeMillis()// 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) {+ notStalled()// Paused: a page that does not answer is most often one Android froze with the// app in the background (seen: "freezing <renderer pid>" in the system log, then// a reload every minute that could not help). Nothing is lost while paused: the@@ -480,6 +493,8 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopif (localMuted && s?.item?.uri != hushedUri) { hushedUri = s?.item?.uri; applyHush() }if (tick % VOLUME_CHECK_TICKS == 0) guardVolume(s, media)if (_adPlaying.value) {+ // The screens show the break (or the song before it, waiting), not a stall.+ notStalled()val ad = adState// The break just started: the page's own ad managers are switched off once more// (the bridge also does it on every state push). This does not keep the server from@@ -511,6 +526,21 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopkey = null; silentSince = 0Lcontinue}+ // The page's state push that ends the break can be lost on the way (the events buffer+ // drops the oldest under a stalled main thread), leaving the screen on "Advertisement"+ // through the next song: the page is asked again when it has said nothing for a while.+ if (now - adStateAt > AD_STATE_RECHECK_MS) {+ val asked = runCatching { bridge.call("player.state", timeoutMs = MEDIA_TIMEOUT_MS, quiet = true) as? JsonObject }.getOrNull()+ // Only a state with an item counts: one read between the ad and the next song+ // ("nothing plays") would end the break and unmute the ad.+ val st = asked?.let { playerState(it) }+ if (st?.item != null) onState(st)+ if (!_adPlaying.value) {+ bridge.logger?.invoke("ad flag cleared: the page plays ${_state.value?.item?.name}")+ key = null; silentSince = 0L+ continue+ }+ }// A refused ad sits at 0:00, buffering; a real one plays to its end.val refused = ad != null && (ad.isBuffering || ad.speed == 0.0) && now - adSince > AD_STUCK_MS// A video ad reports neither a position nor a speed the way an audio one does: it@@ -553,14 +583,25 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopif (remoteActive) {if (key != null || attempts != 0) bridge.logger?.invoke("another device plays: nothing repaired from here")key = null; attempts = 0; silentSince = 0L+ notStalled()continue}// 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 heardHere = s != null && !s.isPaused && !s.isBuffering && media != null && media.active != false+ val playingHere = heardHere && !fadingval moved = media != null && !media.paused && kotlin.math.abs(media.time - lastMediaTime) > 0.25lastMediaTime = media?.time ?: -1.0silentSince = if (playingHere && !moved) (if (silentSince == 0L) now else silentSince) else 0L+ // Reported: the clock counted on while nothing was heard. Still over one tick and+ // waiting for data (or paused) is a stall at once; still over two, whatever the element+ // says. Not one still tick alone: a song resumed just before it has not moved yet.+ // Judged through a resume's rise too (a slow network holds the sound right there),+ // and not reset by a repair as [silentSince] is: the sound is not back yet.+ stillSince = if (heardHere && !moved) (if (stillSince == 0L) now else stillSince) else 0L+ // An unknown readyState (-1, an older page) is not taken for waiting.+ val waiting = media != null && (media.paused || media.readyState in 0 until HAVE_FUTURE_DATA)+ _stalled.value = stillSince != 0L && (waiting || now - stillSince >= WATCH_TICK_MS)val silent = silentSince != 0L && now - silentSince >= SILENT_MSval reason = s?.let { stallOf(it, now, pausedByUser) } ?: (if (silent) SILENT else null)if (recoveryHeld()) { key = null; attempts = 0; continue }@@ -628,7 +669,9 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop/*** 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);+ * 1. the list without picking the song (an account that may not choose a track); a song sent+ * with its place in the list is asked by that place alone instead, so the song picked+ * still plays (reported: a song picked far down a big list started another one);* 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);@@ -665,13 +708,18 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScoplastPlay = last.copy(third = now)// The list as it was picked: a sorted list or a smart shuffle keeps its order.val order = lastOrder?.takeIf { it.first == ctx }?.second- suspend fun playCtx(track: Uri?) = bridge.call("player.play", buildJsonObject {+ val index = lastIndex?.takeIf { last.second != null }+ suspend fun playCtx(track: Uri?, at: Int? = null) = bridge.call("player.play", buildJsonObject {put("contextUri", ctx)order?.let { uris -> putJsonArray("order") { uris.forEach { add(kotlinx.serialization.json.JsonPrimitive(it)) } } }track?.let { put("trackUri", it) }+ at?.let { put("index", it) }}, timeoutMs = PLAY_TIMEOUT_MS)when (step) {- 1 -> {+ 1 -> if (index != null) {+ bridge.logger?.invoke("play refused by Spotify: the song asked by its place in the list ($index)")+ scope.launch { runCatching { playCtx(null, index) } }+ } else {bridge.logger?.invoke("play refused by Spotify: playing the list without picking the song")scope.launch { runCatching { playCtx(null) } }}@@ -687,7 +735,7 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScoprefusalTransferring = false}lastPlay = last.copy(third = System.currentTimeMillis())- runCatching { playCtx(last.second) }+ runCatching { playCtx(last.second, index) }}}3 -> {@@ -715,7 +763,7 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopval pick = lastPlayval order = lastOrder?.takeIf { pick != null && it.first == pick.first }?.secondscope.launch {- if (reloadPage() && pick != null) runCatching { play(pick.first, trackUri = pick.second, order = order) }+ if (reloadPage() && pick != null) runCatching { play(pick.first, trackUri = pick.second, index = lastIndex?.takeIf { pick.second != null }, order = order) }}}@@ -894,7 +942,7 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScoppickBeforeAd?.takeIf { System.currentTimeMillis() - it.at < PICK_REPLAY_MS }?.let { pick ->pickBeforeAd = nullbridge.logger?.invoke("playing the song picked during the ad: ${pick.track ?: pick.context}")- playNow(pick.context, trackUri = pick.track, positionMs = pick.positionMs, order = pick.order, refusable = true)+ playNow(pick.context, trackUri = pick.track, index = pick.index, positionMs = pick.positionMs, order = pick.order, refusable = true)return}val ctx = s.contextUri@@ -953,8 +1001,9 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop// An ad takes the sound over (and is muted on its own): the fade is over.item?.kind == ItemKind.AD -> disarmCrossfade()item != null && item.uri != crossfadeUri -> {+ val from = crossfadeUridisarmCrossfade()- scope.launch { fadeInCrossfade() }+ riseWhenSongPlays(from, lastMedia?.own?.takeIf { it > 0.01 } ?: 1.0, CROSSFADE_IN_MS)}}}@@ -969,7 +1018,7 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopval p = lastPlayval came = p?.takeIf {adSince - it.third < PICK_AD_MS && it.second != null && lastTrackState?.item?.uri != it.second- }?.let { Pick(it.first, it.second, it.third, lastOrder?.takeIf { o -> o.first == it.first }?.second) }+ }?.let { Pick(it.first, it.second, it.third, lastOrder?.takeIf { o -> o.first == it.first }?.second, index = lastIndex) }// A pick held from an earlier break stays until it was played or went stale.pickBeforeAd = came ?: pickBeforeAd}@@ -1008,7 +1057,7 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop} else {bridge.logger?.invoke("song picked before the ad not played: asked again")// With the order it was picked in: a sorted list or a smart shuffle is not the list's own.- scope.launch { runCatching { play(pick.context, trackUri = pick.track, positionMs = pick.positionMs, order = pick.order) } }+ scope.launch { runCatching { play(pick.context, trackUri = pick.track, index = pick.index, positionMs = pick.positionMs, order = pick.order) } }}}}@@ -1039,6 +1088,8 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScoprefusalStep = 0if (s?.item != null) lastSong = selse if (lastTrackState?.item != null) lastSongUntil = System.currentTimeMillis()+ // Another song: the stall was the last one's (the watcher judges this one on its next tick).+ if (s?.item?.uri != lastTrackState?.item?.uri) _stalled.value = falsenoteTrackChange(lastTrackState, s, adJustEnded)lastTrackState = s_state.value = s@@ -1081,7 +1132,7 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop// ── Fades: a song cut off at full volume pops in the phone's speaker. Each skip or play- // lowers the sound over ~0.1 s first and brings it back once the next song plays. ──+ // lowers the sound over ~0.2 s first and brings it back once the next song's sound starts. ──/** The volume a fade comes back to, while one is under way. */@Volatile private var fadeBackTo: Double? = null@@ -1097,46 +1148,86 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop* does not wait for them (a call per step delayed the first sound by one round trip each).* [restore] ends on the page player's own volume, as [restoreLevel] does.*/- private suspend fun fade(levels: List<Double>, restore: Boolean = false, ms: Long = FADE_STEP_MS) {+ /**+ * [riseMs]: the page then holds the sound through the change of song and brings it up over that+ * long once the next song's own sound starts ('media.fade' rise, see riseOnSwitch), or after+ * [riseWaitMs] whatever happened.+ */+ private suspend fun fade(levels: List<Double>, restore: Boolean = false, ms: Long = FADE_STEP_MS, riseMs: Long? = null, riseWaitMs: Long = 0L) {bridge.call("media.fade", buildJsonObject {putJsonArray("steps") { levels.forEach { add(kotlinx.serialization.json.JsonPrimitive(it.coerceIn(0.0, 1.0))) } }put("ms", ms)put("restore", restore)+ riseMs?.let { r -> put("rise", buildJsonObject { put("ms", r); put("wait", riseWaitMs) }) }}, timeoutMs = LEVEL_TIMEOUT_MS, quiet = true)}+ /**+ * After a skip or the end of a crossfade: the page holds the sound until the next song's own+ * sound starts (see [fade]). This is the fall-back for a change it cannot see (the element+ * going on with the next song on the same clock): once the next song is reported playing, or+ * none was in [FADE_BACK_MAX_MS] (the skip was lost, the song before plays on), the level comes+ * up from wherever the page holds it. [from]: the song the change starts from.+ */+ private fun riseWhenSongPlays(from: String?, target: Double, riseMs: Long) {+ fadeBackTo = target+ fadeBack?.cancel()+ fadeBack = scope.launch {+ val moved = withTimeoutOrNull(FADE_BACK_MAX_MS) {+ _state.first { it != null && !it.isPaused && (it.item?.uri != from || it.positionMs < 1_500) }+ }+ if (moved != null) {+ // Buffering is nothing heard: waited for, bounded (a page that keeps saying+ // "buffering" while it plays must not leave the song's start down for long).+ withTimeoutOrNull(SWITCH_BUFFER_MAX_MS) { _state.first { it == null || !it.isBuffering } }+ delay(SWITCH_GRACE_MS)+ }+ // Ends on the page player's own volume: a volume change during the fade is kept.+ runCatching {+ 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() } }+ fadeBackTo = null+ }+ }+private suspend fun withFade(block: suspend () -> Unit) {- // A crossfade under way owns the level: ended here, so its ramp (or its up-ramp, when the- // song changes under it) cannot fight the fade below.- endCrossfade(restore = true)+ // A crossfade under way owns the level. Its ramp is ended without putting the level back:+ // a skip it is fading into (the song before an ad, played a second before the end) went up+ // to full volume for that second, which undid the crossfade.+ val crossfading = crossfadeArmed+ if (crossfading) disarmCrossfade()val s = _state.value// Nothing heard (paused, an ad muted): nothing to fade.- if (s == null || s.isPaused || _adPlaying.value || adMuted) { block(); return }+ if (s == null || s.isPaused || _adPlaying.value || adMuted) { if (crossfading) runCatching { restoreLevel() }; block(); return }// The level as the watcher last read it: no extra round trip before the skip.val seen = lastMedia- if (seen?.active == false) { block(); return }- val target = fadeBackTo ?: seen?.level?.takeIf { it > 0.01 } ?: 1.0+ 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.0val from = s.item?.urifadeBackTo = targetfadeBack?.cancel()- // The ramp runs in the page, so it goes down while the command is already on its way.- runCatching { fade(FADE_OUT_STEPS.map { it * target }, ms = FADE_OUT_STEP_MS) }+ // The ramp runs in the page, so it goes down while the command is already on its way; the+ // page then holds the sound until the next song's own sound starts. From a crossfade, the+ // sound goes on down from where it is (a ramp along the curve), and the next song rises as+ // after a crossfade.+ val riseMs = if (crossfading) CROSSFADE_IN_MS else SKIP_RISE_MS+ runCatching {+ if (crossfading) {+ bridge.call("media.ramp", buildJsonObject { put("to", 0); put("ms", FADE_OUT_STEP_MS * FADE_OUT_STEPS.size) }, timeoutMs = LEVEL_TIMEOUT_MS, quiet = true)+ bridge.call("media.rise", buildJsonObject { put("ms", riseMs); put("wait", SWITCH_HOLD_MAX_MS); put("switch", true) }, timeoutMs = LEVEL_TIMEOUT_MS, quiet = true)+ } else fade(FADE_OUT_STEPS.map { it * target }, ms = FADE_OUT_STEP_MS, riseMs = riseMs, riseWaitMs = SWITCH_HOLD_MAX_MS)+ }+ var sent = falsetry {block()+ sent = true} finally {- fadeBack = scope.launch {- delay(FADE_STEP_MS * 3)- // The next song is there (or give up waiting): the sound comes back. Buffering- // is not waited for: nothing is heard meanwhile, and a page that keeps saying- // "buffering" while it plays would leave the song's start muted.- withTimeoutOrNull(FADE_BACK_MAX_MS) {- _state.first { it != null && !it.isPaused && (it.item?.uri != from || it.positionMs < 1_500) }- }- val back = fadeBackTo ?: target- // Ends on the page player's own volume: a volume change during the fade is kept.- runCatching { fade(FADE_IN_STEPS.map { it * back }, restore = true) }- .onFailure { runCatching { restoreLevel() } }+ if (sent) riseWhenSongPlays(from, target, riseMs)+ else {+ // Not sent (refused, the page reloading): the song before plays on, heard again now.fadeBackTo = null+ withContext(NonCancellable) { runCatching { restoreLevel() } }}}}@@ -1312,29 +1403,14 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop}}bridge.logger?.invoke("crossfade: ${remainingMs / 1000.0}s out on ${_state.value?.item?.name}")- // One call: the page runs the whole ramp itself (see [fade]).- runCatching { fade(levels, ms = per) }+ // One call: the page runs the whole ramp itself (see [fade]), then holds the sound through+ // the change of song and brings the next one up once its sound starts. It was brought up+ // on the state's word before: the page sets its own level on a new song, so the next one+ // mostly started at full volume, no fade-in heard (reported: "crossfade does nothing").+ runCatching { fade(levels, ms = per, riseMs = CROSSFADE_IN_MS, riseWaitMs = remainingMs + CROSSFADE_FAILSAFE_MS) }.onFailure { endCrossfade(restore = true) }}- /** The next song is on: a short ramp back to the user's volume. */- private suspend fun fadeInCrossfade() {- // Read the element as it is now: the page may have reset its volume with the new track,- // and dipping it to the ramp's first step would be heard for nothing.- val m = runCatching { readMedia() }.getOrNull()- if (m == null || m.level >= m.own * 0.9) {- runCatching { restoreLevel() }- return- }- // From where the fade-out left it, up the ear's curve once the new song's sound really- // starts ('media.rise', keep): stepped on a timer it was spent while the song loaded, and- // the new song was first heard at 70-90 % (measured).- runCatching {- bridge.call("media.rise", buildJsonObject { put("ms", CROSSFADE_IN_MS); put("wait", RISE_WAIT_MS); put("keep", true) },- timeoutMs = LEVEL_TIMEOUT_MS, quiet = true)- }.onFailure { runCatching { restoreLevel() } }- }-/*** The user's play (a pick, a list started). The page refuses every play while an ad is on* ("ad_disallow", measured 20/10), and each refusal walks [onRefused]'s steps, which play the@@ -1347,11 +1423,12 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop// put-back of an earlier ad skip would queue that old song after the pick.adRestore?.cancel()app.myspoti.spotify.bridge.AdBlock.ahead.value = null- if (_adPlaying.value && index == null) {+ // Held whether or not the song comes with its place in the list (SongPlayer.rowIndex).+ if (_adPlaying.value) {if (trackUri == null || trackUri != liveIntent()?.item?.uri) intent = nulllastOrder = order?.let { contextUri to it }pausedByUser = false- pickBeforeAd = Pick(contextUri, trackUri, System.currentTimeMillis(), order, positionMs)+ pickBeforeAd = Pick(contextUri, trackUri, System.currentTimeMillis(), order, positionMs, index)bridge.logger?.invoke("pick during an ad: ${trackUri ?: contextUri} held until the ad is over")return}@@ -1366,6 +1443,7 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopif (trackUri == null || trackUri != liveIntent()?.item?.uri) intent = nulllastOrder = order?.let { contextUri to it }lastPlay = Triple(contextUri, trackUri, System.currentTimeMillis())+ lastIndex = indexlastPlayRefusable = refusablerefusalStep = 0pausedByUser = false@@ -1767,6 +1845,8 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop/** A song the page says it plays here while its media element stands still that long. */const val SILENT_MS = 6_000Lconst val SILENT = "silent"+ /** HTMLMediaElement.HAVE_FUTURE_DATA: below it, the element cannot play on. */+ const val HAVE_FUTURE_DATA = 3/** The next song is preloaded once the current one has played that long. */const val PRELOAD_AFTER_MS = 2_000L/** Longer than any ad break: the page is stuck in it. */@@ -1781,12 +1861,24 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop// "previous" that restarts the song stayed paused); the bridge keeps a floor.val FADE_OUT_STEPS: List<Double> = (1..13).map { Math.pow(10.0, -40.0 * it / 13 / 20) } + 0.002const val FADE_OUT_STEP_MS = 16L- /** The way back on the next song: only enough not to click, it is the song's start. */- val FADE_IN_STEPS = listOf(0.08, 0.35)+ /**+ * The way back on the next song, from its first sound: only enough not to click, it is+ * the song's start.+ */+ const val SKIP_RISE_MS = 80L/** All fade levels, for the floor check. */- val FADE_STEPS = FADE_OUT_STEPS + FADE_IN_STEPS+ val FADE_STEPS = FADE_OUT_STEPS+ /**+ * The page holds the sound through a change of song at most this long (see [fade]): a skip+ * the page never answers, a next song that never starts. [riseWhenSongPlays] brings it up sooner.+ */+ const val SWITCH_HOLD_MAX_MS = 12_000L+ /** A next song still buffering after this is brought up anyway (see [riseWhenSongPlays]). */+ const val SWITCH_BUFFER_MAX_MS = 8_000L+ /** The next song plays, and the page has not brought it up itself after this: brought up from here. */+ const val SWITCH_GRACE_MS = 1_000Lconst val FADE_STEP_MS = 12L- /** The sound always comes back after that long, whatever the page does. */+ /** A skip the page reports no next song for in that long was lost: the song before is heard again. */const val FADE_BACK_MAX_MS = 2_500L/** Crossfade: the setting's range (seconds, 0 = off). */const val CROSSFADE_MAX_SECONDS = 12@@ -1866,6 +1958,8 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopconst val BUFFERING_STALL_MS = 25_000L/** An ad still there after a reload: tries at playing on before the next reload. */const val AD_SKIPS_AFTER_RELOAD = 2+ /** An ad break the page has said nothing about for this long is read again (see [watchStalls]). */+ const val AD_STATE_RECHECK_MS = 4_000L/*** What the [attempt]-th try on a stuck ad does: "reload" first (the only lever a refuseddiff --git a/base/api-spotify/src/main/resources/bridge/player-bridge.js b/base/api-spotify/src/main/resources/bridge/player-bridge.jsindex 44e66fcf..6c45e847 100644--- a/base/api-spotify/src/main/resources/bridge/player-bridge.js+++ b/base/api-spotify/src/main/resources/bridge/player-bridge.js@@ -233,7 +233,9 @@// cancel the pending ones, or they would override it seconds later (the up-ramp of a// crossfade undone by the tail of its own down-ramp, a restored volume pulled down again).let fadeTimers = [];- const cancelFade = () => { fadeTimers.forEach(clearTimeout); fadeTimers = []; };+ // The watch of a change of song (riseOnSwitch): apart, as it outlives the fade-out it follows.+ let riseTimers = [];+ const cancelFade = () => { fadeTimers.forEach(clearTimeout); fadeTimers = []; riseTimers.forEach(clearTimeout); riseTimers = []; };// A ramp heard as even: the gain follows a cubic curve (the usual "audio taper", the one the// page applies to its own volume when _cubicVolume is set), so equal times give equal steps@@ -253,6 +255,47 @@};tick();};+ // The sound held down through a change of song, and up along the curve over {ms} once the next+ // song's own sound starts. Reported: a skip faded the old song out, and the level came back on+ // the state's word that the next song was there, while the element still played the old one's+ // last buffered moments (heard as a fragment of it, or a pop). The change is the element's own:+ // another element, another source, or its clock jumping (a new song starts from 0, or where it+ // was asked to). Until then the fade-out that came with it goes on; from then the element stays+ // at SILENT (the page sets its own level on a new song) until its clock moves. Never left down:+ // the level comes back after {wait} ms whatever happened. Any other fade or volume set ends it.+ const riseOnSwitch = (player, ms, wait) => {+ const first = player._player;+ const src = first.currentSrc;+ const now = () => (player._player instanceof HTMLMediaElement ? player._player : first);+ let el = first, switched = false, prev = first.currentTime, at = performance.now();+ const tick = () => {+ const cur = now();+ if (!switched) {+ const t = cur.currentTime, wall = performance.now();+ // What the clock should have done since the last look: anything else is a jump (a late+ // timer on a busy page is not one).+ const expected = cur.paused ? 0 : (wall - at) / 1000 * (cur.playbackRate || 1);+ if (cur !== first || cur.currentSrc !== src || Math.abs(t - prev - expected) > 1) {+ switched = true;+ el = cur;+ // The fade-out is over: its last steps would land on the new song.+ fadeTimers.forEach(clearTimeout); fadeTimers = [];+ el.volume = SILENT;+ prev = el.currentTime;+ } else { prev = t; at = wall; }+ riseTimers.push(setTimeout(tick, 16));+ return;+ }+ if (cur !== el) { el = cur; prev = el.currentTime; }+ if (el.volume > SILENT) el.volume = SILENT;+ const t = el.currentTime, step = t - prev;+ prev = t;+ if (!el.paused && step > 0.005 && step < 0.5) { ramp(el, player, 0, 1, Math.max(1, ms))(); return; }+ riseTimers.push(setTimeout(tick, 16));+ };+ riseTimers.push(setTimeout(() => { cancelFade(); now().volume = ownLevel(player); }, Math.max(500, Number(wait) || 3000)));+ tick();+ };// Where the element stands on that curve now.const curveAt = (el, player) => {const own = ownLevel(player);@@ -474,7 +517,8 @@// A whole fade in one call: the page applies the steps itself, so the host sends the play// command while the sound goes down instead of waiting for every step (a round trip each).- // {steps: [level, ...], ms, restore: true?} -> true. Levels are never 0: see 'media.mute'.+ // {steps: [level, ...], ms, restore: true?, rise: {ms, wait}?} -> true. Levels are never 0: see+ // 'media.mute'. rise: the sound is then held through the change of song (riseOnSwitch).'media.fade': async a => {const player = await localPlayer();const el = player && player._player;@@ -495,6 +539,7 @@fadeTimers.push(setTimeout(tick, per - ((performance.now() - t0) % per)));};tick();+ if (a.rise) riseOnSwitch(player, Number(a.rise.ms) || 80, Number(a.rise.wait));return true;},@@ -512,11 +557,13 @@// out. Not on the state saying "playing", nor on the element's own 'playing' event: after a// long pause both came 0.5 to 0.9 s before the first sound (measured), and the whole ramp// was spent on silence. Not playing within {wait} ms: the level comes back as it was.- // {ms, wait, keep?} -> true+ // {ms, wait, keep?, switch?} -> true. switch: held through the change of song first+ // (riseOnSwitch), the fade under way going on meanwhile.'media.rise': async a => {const player = await localPlayer();const el = player && player._player;if (!(el instanceof HTMLMediaElement)) return null;+ if (a.switch) { riseOnSwitch(player, Number(a.ms) || 80, Number(a.wait)); return true; }cancelFade();// keep: from where the element is now (the end of a crossfade), not from silence.const from = a.keep ? curveAt(el, player) : 0;diff --git a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/AdFlagTest.kt b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/AdFlagTest.ktnew file mode 100644index 00000000..10942b27--- /dev/null+++ b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/AdFlagTest.kt@@ -0,0 +1,95 @@+package app.myspoti.spotify++import app.myspoti.spotify.bridge.AdBlock+import app.myspoti.spotify.bridge.Bridge+import app.myspoti.spotify.bridge.BridgeHost+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.cancel+import kotlinx.coroutines.delay+import kotlinx.coroutines.flow.MutableSharedFlow+import kotlinx.coroutines.runBlocking+import org.junit.jupiter.api.AfterEach+import org.junit.jupiter.api.Assertions.assertEquals+import org.junit.jupiter.api.BeforeEach+import org.junit.jupiter.api.Test++/**+ * The page's state push that ends an ad break never arrives (dropped on the way): the screen must+ * not stay on "Advertisement" through the song that plays.+ */+class AdFlagTest {+ private class FakeHost : BridgeHost {+ override val messages = MutableSharedFlow<String>(extraBufferCapacity = 64)+ /** What the page answers to "player.state": the song it really plays. */+ @Volatile var pageState = "null"+ override suspend fun evaluate(script: String) {+ val m = Regex("""Myspoti\.call\((\d+), "([^"]+)", (.*)\)\.catch""", RegexOption.DOT_MATCHES_ALL).find(script) ?: return+ val value = if (m.groupValues[2] == "player.state") pageState else "null"+ messages.emit("""{"type":"result","id":${m.groupValues[1]},"ok":true,"value":$value}""")+ }+ suspend fun post(json: String) = messages.emit(json)+ }++ private lateinit var scope: CoroutineScope+ private lateinit var host: FakeHost+ private lateinit var bridge: Bridge+ private lateinit var player: SpotifyPlayer++ @BeforeEach fun up() {+ AdBlock.ahead.value = null+ scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)+ host = FakeHost()+ bridge = Bridge(host, scope)+ player = SpotifyPlayer(bridge, scope)+ // A message posted before the bridge listens is lost (a slow CI machine): wait for it.+ waitFor("bridge listening") { host.messages.subscriptionCount.value > 0 }+ }++ @AfterEach fun down() {+ AdBlock.ahead.value = null+ scope.cancel()+ }++ private fun track(name: String) =+ """{"kind":"track","uri":"spotify:track:$name","uid":"u$name","name":"$name","durationMs":200000}"""++ private fun stateOf(item: String) =+ """{"track":$item,"contextUri":"spotify:playlist:C","next":null,"isPaused":false,"isBuffering":false,+ |"positionMs":0,"timestamp":${System.currentTimeMillis()},"restrictions":{}}""".trimMargin()++ private val ad = """{"kind":"ad","uri":"spotify:ad:1","name":"ad","durationMs":30000}"""++ private fun waitFor(what: String, ms: Long = 4_000, cond: () -> Boolean) = runBlocking {+ val end = System.currentTimeMillis() + ms+ while (!cond()) {+ check(System.currentTimeMillis() < end) { "timed out: $what" }+ delay(20)+ }+ }++ @Test fun `a read that finds nothing playing does not end the break`() = runBlocking {+ host.post("""{"type":"ready"}""")+ waitFor("page ready") { bridge.ready.value }+ host.post("""{"type":"state","state":${stateOf(track("A"))}}""")+ host.post("""{"type":"state","state":${stateOf(ad)}}""")+ waitFor("ad flag") { player.adPlaying.value }+ // Between the ad and the next song the page can say "nothing plays": the ad stays muted.+ host.pageState = """{"track":null,"contextUri":null,"next":null,"isPaused":true,"isBuffering":false,"positionMs":0,"timestamp":0,"restrictions":{}}"""+ delay(8_000)+ assertEquals(true, player.adPlaying.value, "the break is still on")+ }++ @Test fun `an ad break whose end was never pushed is cleared once the page plays a song`() = runBlocking {+ host.post("""{"type":"ready"}""")+ waitFor("page ready") { bridge.ready.value }+ host.post("""{"type":"state","state":${stateOf(track("A"))}}""")+ host.post("""{"type":"state","state":${stateOf(ad)}}""")+ waitFor("ad flag") { player.adPlaying.value }+ // The break ends and B plays, but that push is lost: only a read of the page says so.+ host.pageState = stateOf(track("B"))+ waitFor("ad flag cleared", ms = 15_000) { !player.adPlaying.value }+ assertEquals("spotify:track:B", player.state.value?.item?.uri)+ }+}diff --git a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/ReloadTest.kt b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/ReloadTest.ktnew file mode 100644index 00000000..ec79c9cb--- /dev/null+++ b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/ReloadTest.kt@@ -0,0 +1,114 @@+package app.myspoti.spotify++import app.myspoti.spotify.bridge.AdBlock+import app.myspoti.spotify.bridge.Bridge+import app.myspoti.spotify.bridge.BridgeHost+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.cancel+import kotlinx.coroutines.delay+import kotlinx.coroutines.flow.MutableSharedFlow+import kotlinx.coroutines.launch+import kotlinx.coroutines.runBlocking+import org.junit.jupiter.api.AfterEach+import org.junit.jupiter.api.Assertions.assertTrue+import org.junit.jupiter.api.BeforeEach+import org.junit.jupiter.api.Test+import java.util.concurrent.CopyOnWriteArrayList++/**+ * A reload on a slow network: the old page keeps answering "ready" for seconds after the reload+ * was asked for, until the new page starts loading. What follows the reload must go to the new page.+ */+class ReloadTest {+ private class FakeHost : BridgeHost {+ override val messages = MutableSharedFlow<String>(extraBufferCapacity = 64)+ /** Every call the player made: method and when it was sent. */+ val calls = CopyOnWriteArrayList<Pair<String, Long>>()+ override suspend fun evaluate(script: String) {+ val m = Regex("""Myspoti\.call\((\d+), "([^"]+)", (.*)\)\.catch""", RegexOption.DOT_MATCHES_ALL).find(script) ?: return+ calls += m.groupValues[2] to System.currentTimeMillis()+ messages.emit("""{"type":"result","id":${m.groupValues[1]},"ok":true,"value":null}""")+ }+ suspend fun post(json: String) = messages.emit(json)+ }++ private lateinit var scope: CoroutineScope+ private lateinit var host: FakeHost+ private lateinit var bridge: Bridge+ private lateinit var player: SpotifyPlayer+ /** When the reloaded page said ready (0: not yet). */+ @Volatile private var newPageAt = 0L++ @BeforeEach fun up() {+ AdBlock.ahead.value = null+ scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)+ host = FakeHost()+ bridge = Bridge(host, scope)+ player = SpotifyPlayer(bridge, scope)+ // The new page starts loading only [SLOW_START_MS] after the reload (as the host does,+ // the old page is gone at that moment), then says ready.+ player.reloadHost = {+ scope.launch {+ delay(SLOW_START_MS)+ bridge.pageGone()+ delay(300)+ newPageAt = System.currentTimeMillis()+ host.post("""{"type":"ready"}""")+ }+ }+ // A message posted before the bridge listens is lost (a slow CI machine): wait for it.+ waitFor("bridge listening") { host.messages.subscriptionCount.value > 0 }+ }++ @AfterEach fun down() {+ AdBlock.ahead.value = null+ scope.cancel()+ }++ private fun track(name: String) =+ """{"kind":"track","uri":"spotify:track:$name","uid":"u$name","name":"$name","durationMs":200000}"""++ private fun state(item: String, next: String? = null, buffering: Boolean = false) =+ """{"type":"state","state":{"track":$item,"contextUri":"spotify:playlist:C","next":${next ?: "null"},"isPaused":false,+ |"isBuffering":$buffering,"positionMs":0,"timestamp":${System.currentTimeMillis()},"restrictions":{}}}""".trimMargin()++ /** An ad whose audio was refused: current, buffering at 0:00, until the page is reloaded. */+ private val ad = """{"kind":"ad","uri":"spotify:ad:1","name":"ad","durationMs":30000}"""++ private fun waitFor(what: String, ms: Long = 4_000, cond: () -> Boolean) = runBlocking {+ val end = System.currentTimeMillis() + ms+ while (!cond()) {+ check(System.currentTimeMillis() < end) { "timed out: $what" }+ delay(20)+ }+ }++ @Test fun `a reload waits for the new page, not for the old one's last ready`() = runBlocking {+ host.post("""{"type":"ready"}""")+ waitFor("old page ready") { bridge.ready.value }+ val asked = System.currentTimeMillis()+ assertTrue(player.reloadPage(), "the new page came")+ assertTrue(newPageAt > 0 && System.currentTimeMillis() >= newPageAt,+ "returned ${System.currentTimeMillis() - asked} ms after the reload, before the new page was ready")+ }++ @Test fun `the song after a stuck ad is played on the reloaded page`() = runBlocking {+ host.post("""{"type":"ready"}""")+ waitFor("old page ready") { bridge.ready.value }+ host.post(state(track("A"), track("B")))+ host.post(state(ad, buffering = true))+ waitFor("ad flag") { player.adPlaying.value }+ // The watcher reloads ~3 s after the ad started; the play comes once the new page is up.+ waitFor("play after the reload", ms = 20_000) { host.calls.any { it.first == "player.play" } }+ val playAt = host.calls.first { it.first == "player.play" }.second+ assertTrue(newPageAt > 0 && playAt >= newPageAt,+ "play sent ${if (newPageAt == 0L) "before the new page started" else "${newPageAt - playAt} ms before the new page was ready"}")+ }++ private companion object {+ /** Longer than the 1.5 s the reload once waited, as on a slow network. */+ const val SLOW_START_MS = 3_500L+ }+}diff --git a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/StalledFlagTest.kt b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/StalledFlagTest.ktnew file mode 100644index 00000000..7d79c2fe--- /dev/null+++ b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/StalledFlagTest.kt@@ -0,0 +1,115 @@+package app.myspoti.spotify++import app.myspoti.spotify.bridge.AdBlock+import app.myspoti.spotify.bridge.Bridge+import app.myspoti.spotify.bridge.BridgeHost+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.cancel+import kotlinx.coroutines.delay+import kotlinx.coroutines.flow.MutableSharedFlow+import kotlinx.coroutines.runBlocking+import org.junit.jupiter.api.AfterEach+import org.junit.jupiter.api.Assertions.assertEquals+import org.junit.jupiter.api.BeforeEach+import org.junit.jupiter.api.Test++/**+ * Reported: the time counted on while no song was heard. The page's state says it plays, its+ * media element stands still waiting for data: the player says so ([SpotifyPlayer.stalled]) so the+ * screens stop their clock.+ */+class StalledFlagTest {+ private class FakeHost : BridgeHost {+ override val messages = MutableSharedFlow<String>(extraBufferCapacity = 64)+ /** The media element's clock (s); it moves on each read while [moving]. */+ @Volatile var time = 10.0+ @Volatile var moving = false+ @Volatile var readyState = 2+ override suspend fun evaluate(script: String) {+ val m = Regex("""Myspoti\.call\((\d+), "([^"]+)", (.*)\)\.catch""", RegexOption.DOT_MATCHES_ALL).find(script) ?: return+ val value = when (m.groupValues[2]) {+ "media.state" -> {+ if (moving) time += 2.0+ """{"paused":false,"muted":false,"volume":1,"level":1,"own":1,"time":$time,"readyState":$readyState,"ended":false,"playerVolume":1,"active":true}"""+ }+ else -> "null"+ }+ messages.emit("""{"type":"result","id":${m.groupValues[1]},"ok":true,"value":$value}""")+ }+ suspend fun post(json: String) = messages.emit(json)+ }++ private lateinit var scope: CoroutineScope+ private lateinit var host: FakeHost+ private lateinit var bridge: Bridge+ private lateinit var player: SpotifyPlayer++ @BeforeEach fun up() {+ AdBlock.ahead.value = null+ scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)+ host = FakeHost()+ bridge = Bridge(host, scope)+ player = SpotifyPlayer(bridge, scope)+ waitFor("bridge listening") { host.messages.subscriptionCount.value > 0 }+ }++ @AfterEach fun down() {+ AdBlock.ahead.value = null+ scope.cancel()+ }++ private fun track(name: String) =+ """{"kind":"track","uri":"spotify:track:$name","uid":"u$name","name":"$name","durationMs":200000}"""++ private fun stateOf(item: String, paused: Boolean = false) =+ """{"track":$item,"contextUri":"spotify:playlist:C","next":null,"isPaused":$paused,"isBuffering":false,+ |"positionMs":10000,"timestamp":${System.currentTimeMillis()},"restrictions":{}}""".trimMargin()++ private fun waitFor(what: String, ms: Long = 4_000, cond: () -> Boolean) = runBlocking {+ val end = System.currentTimeMillis() + ms+ while (!cond()) {+ check(System.currentTimeMillis() < end) { "timed out: $what" }+ delay(20)+ }+ }++ private suspend fun playing(name: String) {+ host.post("""{"type":"ready"}""")+ waitFor("page ready") { bridge.ready.value }+ host.post("""{"type":"state","state":${stateOf(track(name))}}""")+ waitFor("state") { player.state.value?.item?.name == name }+ }++ @Test fun `a song whose sound stands still waiting for data is stalled`() = runBlocking {+ playing("A")+ waitFor("stalled", ms = 9_000) { player.stalled.value }+ // The sound comes back: the clock goes on.+ host.moving = true+ host.readyState = 4+ waitFor("stall over", ms = 6_000) { !player.stalled.value }+ }++ @Test fun `a song that plays is never stalled`() = runBlocking {+ host.moving = true+ host.readyState = 4+ playing("A")+ delay(7_000)+ assertEquals(false, player.stalled.value)+ }++ @Test fun `another song clears the stall at once`() = runBlocking {+ playing("A")+ waitFor("stalled", ms = 9_000) { player.stalled.value }+ host.post("""{"type":"state","state":${stateOf(track("B"))}}""")+ waitFor("stall cleared with the new song", ms = 500) { !player.stalled.value }+ }++ @Test fun `a paused song is not stalled`() = runBlocking {+ playing("A")+ waitFor("stalled", ms = 9_000) { player.stalled.value }+ host.post("""{"type":"state","state":${stateOf(track("A"), paused = true)}}""")+ waitFor("stall over on pause", ms = 6_000) { !player.stalled.value }+ }+}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 8208b0be..99ddeb95 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@@ -46,6 +46,23 @@ object SongPlayer {private const val SONG_END_GRACE_MS = 1_500L/** A transport command that has not answered by then is given up (the next one runs). */private const val TRANSPORT_TIMEOUT_MS = 15_000L+ /**+ * A transport command still running this long when a newer one comes is stuck (a dead+ * connection, a page that does not answer): it is given up at once rather than holding the+ * newer one for the rest of [TRANSPORT_TIMEOUT_MS]. A skip normally answers well within it.+ */+ private const val TRANSPORT_STUCK_MS = 3_000L+ /**+ * The longest a skip is shown ahead of the page: its burst gap, its turn behind a stuck command+ * and its own timeout. Once it is answered, the page has [SKIP_ANSWERED_MS] (see [skipDone]).+ */+ private const val SKIP_PENDING_MAX_MS = TRANSPORT_TIMEOUT_MS + 5_000L+ /**+ * An answered skip whose song has not come by then: the old song is heard again (the engine+ * brings its sound back 2.5 s after the skip, SpotifyPlayer.FADE_BACK_MAX_MS), so the screen+ * shows it again too. Reported: the next song's cover on screen, the old song playing on.+ */+ private const val SKIP_ANSWERED_MS = 3_000L/** How long a play has to show up in the page's state before it is sent again. */private const val PLAY_CHECK_MS = 4_000L/** A resume of an episode that the page did not take is asked for again after that. */@@ -58,8 +75,24 @@ object SongPlayer {private const val AD_SHOW_AFTER_MS = 2_000L/** After a local file starts, engine states this recent still predate the pause. */private const val LOCAL_GRACE_MS = 2500L+ /** An answered command's state reaches the app within this (see [reconcile]). */+ private const val COMMAND_SETTLE_MS = 1_500L+ /** A hold's end is checked this long after it, so the hold is over by then (see [reconcile]). */+ private const val RECONCILE_MARGIN_MS = 100L+ /** The page's state is read again that long at most before the screen is put right. */+ private const val RECONCILE_READ_MS = 3_000L+ /** A seek is sent within this, or given up for this try (see [seekTo]). */+ private const val SEEK_SEND_MS = 5_000L+ /** How long a seek has to show up in the page's state before it is sent again. */+ private const val SEEK_CHECK_MS = 3_000L+ /** The longest a seek holds the clock against the page (both tries and their sends). */+ private const val SEEK_HOLD_MS = 2 * (SEEK_SEND_MS + SEEK_CHECK_MS)+ /** A page position this close to a seek's target (or past it by the time played) is the seek. */+ private const val SEEK_NEAR_MS = 2_000Lprivate const val TAG = "MspPlayer"private const val LIKED_CONTEXT = "spotify:collection:tracks"+ /** A picked song from this row on is also sent by its place in the list (see [rowIndex]). */+ private const val INDEXED_ROW_FROM = 100private val api: MyspotiApi get() = MyspotiRuntime.apiprivate val scope get() = MyspotiRuntime.scope@@ -79,6 +112,8 @@ object SongPlayer {@Volatile private var durationMs = 0L@Volatile private var positionMs = 0L@Volatile private var positionAt = 0L+ /** The page says it plays, but nothing is heard (see [onSoundStalled]): the clock waits. */+ @Volatile private var soundStalled = false@Volatile var currentTrackId: String = ""private set@Volatile var currentContextUri: String = ""@@ -95,8 +130,50 @@ object SongPlayer {@Volatile private var wantPlayingUntil = 0L@Volatile private var wantPausedUntil = 0L- private fun intendPlaying() { wantPlayingUntil = SystemClock.elapsedRealtime() + 4000; wantPausedUntil = 0 }- private fun intendPaused() { wantPausedUntil = SystemClock.elapsedRealtime() + 1500; wantPlayingUntil = 0 }+ private fun intendPlaying() { wantPlayingUntil = SystemClock.elapsedRealtime() + 4000; wantPausedUntil = 0; reconcileAfter(intentEnded, 4000) }+ private fun intendPaused() { wantPausedUntil = SystemClock.elapsedRealtime() + 1500; wantPlayingUntil = 0; reconcileAfter(intentEnded, 1500) }++ /**+ * Puts the screen back on what the page last said once a hold is over (a play or pause+ * wanted, a song shown before it plays). The page pushes changes only, and a state read again+ * that did not change is no news either: a play the page never took left the clock counting+ * over silence, and a skip that never landed left the next song on screen while the old one+ * played on (reported).+ */+ private fun reconcile() {+ // A command still on its way: its own end puts the screen right (see [transport]).+ fun leftAlone() = !acceptsSessionUpdates() || LocalPlayer.active.value || transportsInFlight.get() > 0+ if (leftAlone()) return+ scope.launch {+ // Read again first: the page's last push can be lost on the way (its events buffer+ // drops the oldest when its main thread stalls), and the screen must not go back to+ // "paused" over a song that plays.+ kotlinx.coroutines.withTimeoutOrNull(RECONCILE_READ_MS) { runCatching { MyspotiRuntime.spotify.player.refresh() } }+ if (leftAlone()) return@launch+ val s = api.player.state.value+ if (s != null) { applyState(s); return@launch }+ // The page never reported anything (it did not load): nothing plays, whatever was tapped.+ if (playing) {+ playing = false+ bufferingState.value = false+ boundState?.updatePlayingState(false)+ pushNotification(null, boundState?.likeState?.value ?: false)+ }+ }+ }+ private val intentEnded = Runnable { reconcile() }+ private val pendingEnded = Runnable { reconcile() }+ private val commandSettled = Runnable { reconcile() }+ private fun reconcileAfter(check: Runnable, ms: Long) {+ main.removeCallbacks(check)+ main.postDelayed(check, ms.coerceAtLeast(0L) + RECONCILE_MARGIN_MS)+ }++ /**+ * Not heard yet: the page buffers, its sound stands still, or a play is wanted that the page+ * has not started. The clock waits and the screens show the song loading.+ */+ private fun waiting(s: PlayerState) = s.isBuffering || soundStalled || (playing && s.isPaused)/** Myspoti itself asked the engine to play lately (a pick, a play, a skip): not another device's doing. */fun engineIntended(): Boolean =@@ -187,6 +264,7 @@ object SongPlayer {}}scope.launch { api.player.queue.collect { q -> if (acceptsSessionUpdates()) applyQueue(q) } }+ scope.launch { MyspotiRuntime.spotify.player.stalled.collect { on -> onSoundStalled(on) } }// Smart shuffle plays a mixed order as the list and leaves Spotify's own shuffle off, so// turning it off sends no shuffle command at all (the button finds shuffle already off):// the list's own order comes back here.@@ -349,10 +427,12 @@ object SongPlayer {pendingUntil = 0LintentUri = ""; intentUntil = 0LwantPlayingUntil = 0L; wantPausedUntil = 0L+ // Its own end puts nothing back on screen: the seq it ends with is no longer the last.+ seekSeq++; seekJob?.cancel(); seekUntil = 0L; seekUri = ""stateSeen = falseplaying = false; bufferingState.value = false; adState.value = false; durationMs = 0L; positionMs = 0LcurrentTrackId = ""; currentContextUri = ""- contextRegistry.clear(); contextNames.clear(); library.clear()+ contextRegistry.clear(); contextRows.clear(); contextNames.clear(); library.clear()synchronized(wantedSaved) { wantedSaved.clear() }_queue.value = EngineQueue(); apiQueue = null; _nowPlaying.value = NowPlaying()lastTrackPrefs().edit().clear().apply(); savedLast = ""; resumeWhenReady = false@@ -388,6 +468,25 @@ object SongPlayer {)}+ /**+ * The page says it plays but its sound stands still (a slow network), or plays again. The page's+ * own clock goes on over the silence (reported: "the time was counting, the song not playing"):+ * the screen's clock stops where it is and goes on from there once the sound does.+ */+ private fun onSoundStalled(on: Boolean) {+ if (on == soundStalled) return+ // Read before the flag changes: the running clock as it stands, or the held one.+ positionMs = getCurrentPosition()+ positionAt = SystemClock.elapsedRealtime()+ soundStalled = on+ // A song shown before the page plays it is waiting already (see [markPending]).+ if (LocalPlayer.active.value || pendingTrackId != null) return+ val s = api.player.state.value ?: return+ bufferingState.value = waiting(s)+ pushNotification(null, boundState?.likeState?.value ?: false)+ com.music.spotui.video.MusicVideoController.onAudioBuffering(isBuffering, currentTrackId)+ }+/** An ad break starts or ends: the notification, the widget and the screens follow (T4). */private fun onAdPlaying(on: Boolean) {if (adState.value == on) return@@ -456,13 +555,16 @@ object SongPlayer {val wasPlaying = playingval wasBuffering = isBufferingval predicted = getCurrentPosition()- bufferingState.value = s.isBufferingplaying = resolvePlaying(s.isPaused)+ bufferingState.value = waiting(s)SpeakerKeepAlive.set(playing && _activeDevice.value == null)durationMs = item?.durationMs ?: 0Lval reported = s.positionAt(System.currentTimeMillis())+ // A seek on its way: the page's old position does not take the clock back (see [seekTo]).+ if (seekHeld(uri) && seekLanded(s)) seekUntil = 0L+ val seeking = seekHeld(uri)// Keep the running clock when the player only nudges it (< 1 s).- if (!(wasPlaying && playing && !wasBuffering && !isBuffering && kotlin.math.abs(reported - predicted) < 1000)) {+ if (!seeking && !(wasPlaying && playing && !wasBuffering && !isBuffering && kotlin.math.abs(reported - predicted) < 1000)) {positionMs = reportedpositionAt = SystemClock.elapsedRealtime()}@@ -654,38 +756,92 @@ object SongPlayer {* then is pulled back as before; with another device known to be active, the check still* comes first, since the pull-back has to happen before the command.*/- private fun transport(pullBack: Boolean = true, waitReady: Boolean = true, checkAfter: Boolean = false, block: suspend (isLatest: () -> Boolean) -> Unit) {+ /**+ * [done]: told once, on the main thread, whether the command was answered (true) or not+ * (failed, timed out, dropped for a newer one or for a page that never loaded).+ */+ private fun transport(+ pullBack: Boolean = true,+ waitReady: Boolean = true,+ checkAfter: Boolean = false,+ done: ((ok: Boolean) -> Unit)? = null,+ block: suspend (isLatest: () -> Boolean) -> Unit,+ ) {val gen = transportGen.incrementAndGet()+ runningTransport?.let { job ->+ val held = SystemClock.elapsedRealtime() - runningSince+ if (job.isActive && held >= TRANSPORT_STUCK_MS) {+ Log.w(TAG, "transport stuck for $held ms: given up for the newer one")+ job.cancel()+ }+ }scope.launch {- transportLock.withLock {- if (gen != transportGen.get()) return@withLock- // A tap while the page loads (cold start, a reload): sent once it is there,- // instead of failing at once with "not ready".- if (waitReady && !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+ val self = coroutineContext[kotlinx.coroutines.Job]+ var told = false+ fun tell(ok: Boolean) {+ if (told) return+ told = true+ done?.invoke(ok)+ }+ var answered = false+ // Counted from inside: a coroutine cancelled before it starts never runs its finally.+ transportsInFlight.incrementAndGet()+ try {+ transportLock.withLock {+ if (gen != transportGen.get()) return@withLock+ runningTransport = self+ runningSince = SystemClock.elapsedRealtime()+ // A tap while the page loads (cold start, a reload): sent once it is there,+ // instead of failing at once with "not ready".+ if (waitReady && !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+ // A Connect mirror just ended: the page is heard again before this command reaches it.+ ConnectMirror.awaitEnded()+ val checkLater = pullBack && checkAfter && _activeDevice.value == null+ if (pullBack && !checkLater && api.ready.value) takeBackPlayback()+ // A cancellation of the caller is never swallowed (it must unwind); only the+ // transport's own timeout and a real failure are logged here.+ try {+ kotlinx.coroutines.withTimeout(TRANSPORT_TIMEOUT_MS) { block { gen == transportGen.get() } }+ answered = true+ tell(true)+ } catch (e: kotlinx.coroutines.TimeoutCancellationException) {+ Log.w(TAG, "transport timed out after ${TRANSPORT_TIMEOUT_MS} ms")+ } catch (e: kotlinx.coroutines.CancellationException) {+ throw e+ } catch (e: Exception) {+ Log.w(TAG, "transport failed: ${e.message}")+ }+ if (checkLater && gen == transportGen.get() && api.ready.value) takeBackPlayback()}- if (gen != transportGen.get()) return@withLock- // A Connect mirror just ended: the page is heard again before this command reaches it.- ConnectMirror.awaitEnded()- val checkLater = pullBack && checkAfter && _activeDevice.value == null- if (pullBack && !checkLater && api.ready.value) takeBackPlayback()- // A cancellation of the caller is never swallowed (it must unwind); only the- // transport's own timeout and a real failure are logged here.- try {- kotlinx.coroutines.withTimeout(TRANSPORT_TIMEOUT_MS) { block { gen == transportGen.get() } }- } catch (e: kotlinx.coroutines.TimeoutCancellationException) {- Log.w(TAG, "transport timed out after ${TRANSPORT_TIMEOUT_MS} ms")- } catch (e: kotlinx.coroutines.CancellationException) {- throw e- } catch (e: Exception) {- Log.w(TAG, "transport failed: ${e.message}")+ } finally {+ // A newer transport may hold the lock already: only this one's own mark is cleared.+ if (runningTransport === self) runningTransport = null+ tell(false)+ transportsInFlight.decrementAndGet()+ // An answered play or pause: the page gets a moment to say so before the screen+ // is put back on what it says (a slow network answers late, its state later).+ // One that failed is put right then too, whatever was wanted.+ if (answered) {+ val until = SystemClock.elapsedRealtime() + COMMAND_SETTLE_MS+ if (wantPlayingUntil != 0L) wantPlayingUntil = maxOf(wantPlayingUntil, until)+ if (wantPausedUntil != 0L) wantPausedUntil = maxOf(wantPausedUntil, until)}- if (checkLater && gen == transportGen.get() && api.ready.value) takeBackPlayback()+ reconcileAfter(commandSettled, COMMAND_SETTLE_MS)}}}+ /** Transports started and not over yet: [reconcile] leaves the screen to them meanwhile. */+ private val transportsInFlight = java.util.concurrent.atomic.AtomicInteger()++ /** The transport holding [transportLock], and since when (see [TRANSPORT_STUCK_MS]). */+ @Volatile private var runningTransport: kotlinx.coroutines.Job? = null+ @Volatile private var runningSince = 0L+/*** Plays [itemUri], then checks that the page really moved to it; a play the page lost* (busy, reloading) is sent once more instead of leaving the old song playing.@@ -704,6 +860,27 @@ object SongPlayer {/** Remember the Spotify context the given play keys belong to. */fun registerContext(urls: List<String>, contextUri: String) {urls.forEach { contextRegistry[it] = contextUri }+ contextRows[contextUri] = urls+ }++ /**+ * Each list's play keys in its own order, as last registered: where a picked song sits in it+ * (see [rowIndex]). The app's rows map one to one onto the list's items, in Spotify's order.+ */+ private val contextRows = ConcurrentHashMap<String, List<String>>()++ /**+ * The place of [song] in the list [ctx], sent with its uri as the official player sends a row's+ * index with its uri. Reported (900+ songs, Liked Songs): a song picked far down a big list+ * started another song. The uri alone is looked up in the list's first pages only (lists of a+ * hundred songs played the song picked); the index says where it is. Only past that first+ * stretch, so the plays that worked go out exactly as before. A given [order] is played as one+ * page of those songs (see player-bridge.js), where the uri is always found: no index then.+ */+ private fun rowIndex(song: String, ctx: String, order: List<String>?): Int? {+ if (order != null) return null+ val at = contextRows[ctx]?.indexOf(song) ?: return null+ return at.takeIf { it >= INDEXED_ROW_FROM }}// Names of the lists playback started from, as the app's own pages name them. Spotify's@@ -723,13 +900,20 @@ object SongPlayer {/** Liked Songs plays as its own context: Spotify maps it to the account's liked list. */fun registerLikedSongs(urls: List<String>) = registerContext(urls, LIKED_CONTEXT)- private fun markPending(trackId: String, itemUri: String? = trackId.takeIf { it.isNotBlank() }?.let { SPOTIFY_TRACK_PREFIX + it }) {+ /** [holdMs]: how long states of another song are ignored, at most, while this one comes. */+ private fun markPending(+ trackId: String,+ itemUri: String? = trackId.takeIf { it.isNotBlank() }?.let { SPOTIFY_TRACK_PREFIX + it },+ holdMs: Long = PENDING_MS,+ ) {+ pendingSkip = 0pendingItemUri = itemUribufferingState.value = trueitemUri?.let { boundState?.likeState?.value = library[it] ?: false }intendPlaying()pendingTrackId = trackId- pendingUntil = SystemClock.elapsedRealtime() + PENDING_MS+ pendingUntil = SystemClock.elapsedRealtime() + holdMs+ reconcileAfter(pendingEnded, holdMs)playing = truepositionMs = 0positionAt = SystemClock.elapsedRealtime()@@ -789,7 +973,10 @@ object SongPlayer {transport { isLatest ->playChecked(itemUri, isLatest) {Log.d(TAG, "playing $itemUri in ${ctx ?: "no context"}: ${queueTag()}")- if (ctx != null) api.player.play(ctx, trackUri = itemUri, positionMs = positionMs, order = order?.takeIf { ctx == contextUri })+ if (ctx != null) {+ val sent = order?.takeIf { ctx == contextUri }+ api.player.play(ctx, trackUri = itemUri, index = rowIndex(song, ctx, sent), positionMs = positionMs, order = sent)+ }else api.player.play(itemUri)}}@@ -1011,6 +1198,9 @@ object SongPlayer {// Smart shuffle was turned off while paused: the list's order comes back as it plays on.plainOrderDue?.let { if (restorePlainOrder(it)) return }Haptics.click(); intendPlaying(); playing = true; positionAt = SystemClock.elapsedRealtime()+ // Loading until the page plays: the clock ran from the tap before, over silence when the+ // resume came late or never (reported on a slow network).+ if (api.player.state.value?.isPaused != false) bufferingState.value = true// Tapped on the restored mini player while the Web Player is still loading.if (!stateSeen) resumeWhenReady = trueval uri = _nowPlaying.value.uri@@ -1045,6 +1235,14 @@ object SongPlayer {}fun stop() = pause()++ /**+ * Next, from any control: the player, the mini player, the notification, headphones, the car,+ * the widget. The song it lands on is shown at once ([showSkipTarget]) and stays shown until the+ * page plays it or the skip fails. Only the in-app buttons showed it before, for [PENDING_MS] at+ * most: on a slow network the skip took longer and the screen went back to the old song+ * (reported: "Next does not move").+ */fun next(by: String = "user") {Log.d(TAG, "next tapped")app.myspoti.host.android.Logbook.log("next asked by $by")@@ -1080,7 +1278,10 @@ object SongPlayer {// the old song's position and restart instead of going back.positionMs = 0LpositionAt = now- transport(waitReady = !stateSeen) { api.player.next() }+ val shown = showSkipTarget()+ // The device check after the skip, as for a resume: before it, a slow network held+ // every skip for the device list's round trip (up to DEVICES_WAIT_MS).+ transport(waitReady = !stateSeen, checkAfter = true, done = { ok -> skipDone(shown, ok) }) { api.player.next() }return}burstAt = now@@ -1092,10 +1293,63 @@ object SongPlayer {}burstTaps++pendingSkips+++ showSkipTarget()main.removeCallbacks(sendSkips)main.postDelayed(sendSkips, maxOf(SKIP_BURST_MS, MIN_SKIP_GAP_MS - sinceSent))}+ /** Hands out the tokens of [showSkipTarget]; 0 is never one. */+ private var skipShownSeq = 0+ /** The skip whose song is pending on screen; 0 when the pending song is not a skip's (a pick). */+ private var pendingSkip = 0++ /**+ * Shows the song the taps so far land on, before the page plays it: the song after the one+ * playing at the first tap, or [burstTaps] songs after it. -> the token [skipDone] is told+ * with, 0 when the target is unknown (the page's own states then show where it lands).+ */+ private fun showSkipTarget(): Int {+ val token = ++skipShownSeq+ // Reported (beta.9): each fast tap showed `nowPlaying.next` — the same second song every+ // time, held as pending, so the screen stayed on it for seconds while the page went on to+ // the fifth. A burst shows the song its taps add up to.+ val n = if (burstTaps <= 1) _nowPlaying.value.next+ else burstUpcoming.getOrNull(burstTaps - 1)?.let(::songOf)+ if (n == null) {+ pendingTrackId = null+ pendingItemUri = null+ pendingSkip = 0+ return 0+ }+ markPending(n.spotifyTrackId, holdMs = SKIP_PENDING_MAX_MS)+ pendingSkip = token+ boundState?.updateSongState(n.coverUri, n.title, n.singer, true, n.id, 0, n.album)+ durationMs = n.durationMs.toLong()+ pushNotification(n, false)+ return token+ }++ /**+ * The skip shown as [token] was answered ([ok]): the page now has [SKIP_ANSWERED_MS] to report the+ * song. Not answered (failed, timed out, dropped): the screen goes back at once to what the+ * page really plays, instead of showing a song nothing is going to play. A newer skip or a+ * pick shown since owns the screen, and is left alone.+ */+ private fun skipDone(token: Int, ok: Boolean) {+ if (token == 0 || token != pendingSkip || pendingTrackId == null) return+ if (ok) {+ val now = SystemClock.elapsedRealtime()+ pendingUntil = minOf(pendingUntil, now + SKIP_ANSWERED_MS)+ reconcileAfter(pendingEnded, pendingUntil - now)+ return+ }+ Log.w(TAG, "skip not taken by the page: the screen shows what it plays")+ pendingSkip = 0+ pendingTrackId = null+ pendingItemUri = null+ applyState(api.player.state.value)+ }+/** When the last skip command left (see [next]). */private var skipSentAt = 0L@@ -1111,7 +1365,10 @@ object SongPlayer {// The song [burstTaps] after the one playing at the first tap.val target = burstUpcoming.getOrNull(burstTaps - 1)app.myspoti.host.android.Logbook.log("next taps merged: $burstTaps skips${if (target != null) " in one jump to ${target.name}" else ", sent as a plain next"}")- transport(waitReady = !stateSeen) { if (target == null) api.player.next() else api.player.skipTo(target) }+ val shown = pendingSkip+ transport(waitReady = !stateSeen, checkAfter = true, done = { ok -> skipDone(shown, ok) }) {+ if (target == null) api.player.next() else api.player.skipTo(target)+ }if (target != null) {burstTarget = targetburstContext = _nowPlaying.value.contextUri@@ -1206,7 +1463,7 @@ object SongPlayer {// position stays until Spotify reports, and a quick second previous would restart again.positionMs = 0LpositionAt = SystemClock.elapsedRealtime()- transport(waitReady = !stateSeen) { api.player.previous() }+ transport(waitReady = !stateSeen, checkAfter = true) { api.player.previous() }}/** Tracks shufflePlay plays without a context: the first one, plus up to 49 queued. */@@ -1451,33 +1708,68 @@ object SongPlayer {if (wantedSaved.add(uri)) { main.removeCallbacks(flushSaved); main.postDelayed(flushSaved, 32) }}- /** Swipe to the next track: show it right away, then skip. */- fun swipeNext() {- if (LocalPlayer.active.value) { next(); return }- next()- // The song this tap lands on, the one [next]'s burst will skip to. Reported (beta.9): each- // fast tap showed `nowPlaying.next` — the same second song every time, held as pending,- // so the screen stayed on it for seconds while the page went on to the fifth.- val n = if (burstTaps <= 1) _nowPlaying.value.next- else burstUpcoming.getOrNull(burstTaps - 1)?.let(::songOf)- if (n == null) {- // Unknown target: the page's own states show where it lands.- pendingTrackId = null- pendingItemUri = null- return- }- markPending(n.spotifyTrackId)- boundState?.updateSongState(n.coverUri, n.title, n.singer, true, n.id, 0, n.album)- durationMs = n.durationMs.toLong()- pushNotification(n, false)+ /** The in-app swipe and button: [next], which shows the song it lands on at once. */+ fun swipeNext() = next()++ /**+ * A seek the page has not shown yet: the song, the position asked for, when it was asked and+ * until when it holds. States of that song from before the seek (the old position) do not move+ * the clock back meanwhile. Reported: the bar dragged to a new place jumped back, the song+ * playing on from where it was — a state still on the old position, taken over the seek.+ */+ @Volatile private var seekUri = ""+ @Volatile private var seekTarget = 0L+ @Volatile private var seekAt = 0L+ @Volatile private var seekUntil = 0L+ private var seekJob: kotlinx.coroutines.Job? = null+ private var seekSeq = 0+ private val seekEnded = Runnable { reconcile() }++ /** [s] is the song a seek was asked on, somewhere it can have got to since. */+ private fun seekLanded(s: PlayerState): Boolean {+ if (s.item?.uri != seekUri) return false+ val at = s.positionAt(System.currentTimeMillis())+ val played = SystemClock.elapsedRealtime() - seekAt+ return at >= seekTarget - SEEK_NEAR_MS && at <= seekTarget + played + SEEK_NEAR_MS}+ private fun seekHeld(uri: String) = uri == seekUri && SystemClock.elapsedRealtime() < seekUntil+fun seekTo(ms: Long) {if (LocalPlayer.active.value) { LocalPlayer.seekTo(ms); return }cancelBurst()+ val now = SystemClock.elapsedRealtime()positionMs = ms- positionAt = SystemClock.elapsedRealtime()- command { api.player.seek(ms) }+ positionAt = now+ seekUri = _nowPlaying.value.uri+ seekTarget = ms+ seekAt = now+ seekUntil = now + SEEK_HOLD_MS+ reconcileAfter(seekEnded, SEEK_HOLD_MS)+ // The newest seek only: a drag that ends while the last one is still on its way replaces it.+ val seq = ++seekSeq+ seekJob?.cancel()+ seekJob = scope.launch {+ try {+ // Sent once more when the page does not show it (busy, a slow network); after that+ // the page's word stands, wherever it is.+ repeat(2) { attempt ->+ runCatching { kotlinx.coroutines.withTimeoutOrNull(SEEK_SEND_MS) { api.player.seek(ms) } }+ .onFailure { if (it is kotlinx.coroutines.CancellationException) throw it; Log.w(TAG, "seek failed: ${it.message}") }+ val landed = kotlinx.coroutines.withTimeoutOrNull(SEEK_CHECK_MS) {+ api.player.state.first { it != null && (it.item?.uri != seekUri || seekLanded(it)) }+ }+ if (landed != null) return@launch+ Log.w(TAG, "seek to $ms not taken by the page${if (attempt == 0) ": sent again" else ""}")+ }+ } finally {+ if (seq == seekSeq) {+ seekUntil = 0L+ main.removeCallbacks(seekEnded)+ main.post { reconcile() }+ }+ }+ }}/** Which of [uris] are saved in the user's library (Liked Songs / saved albums…). */diff --git a/base/host-android/src/main/AndroidManifest.xml b/base/host-android/src/main/AndroidManifest.xmlindex 164cd6a4..3e49c4c5 100644--- a/base/host-android/src/main/AndroidManifest.xml+++ b/base/host-android/src/main/AndroidManifest.xml@@ -1,6 +1,8 @@<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"><uses-permission android:name="android.permission.INTERNET" />+ <!-- WebPlayerHost.watchNetwork: the relay's connections are dropped when the network changes. -->+ <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /><uses-permission android:name="android.permission.FOREGROUND_SERVICE" /><uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" /><uses-permission android:name="android.permission.WAKE_LOCK" />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 e143e35e..a743bead 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@@ -43,22 +43,7 @@ internal class ControlRelay(private val view: WebView, private val fingerprint:@Volatile var onDeviceRegistered: (() -> Unit)? = nullprivate val main = Handler(Looper.getMainLooper())- /**- * No cookie jar: the real Web Player's requests to spclient carry no cookie (its `fetch` is- * cross-origin with the default `credentials: same-origin`; 02-playback capture). The WebView's- * cookies the relay sent from 2.0.2-beta.9 on (sp_dc, sp_t, sp_key...) were a shape no- * browser's command has.- *- * Chrome's Accept-Encoding ([ACCEPT_ENCODING]) comes from [DECODING], which also decodes the- * answer (Spotify answers track-playback in zstd, connect-state in gzip or br).- */- private val http = OkHttpClient.Builder()- .connectTimeout(15, TimeUnit.SECONDS)- .readTimeout(30, TimeUnit.SECONDS)- .addInterceptor(DECODING)- .eventListener(RelayEvents)- .build()- /** The same client, pinned to one address family (see RelayRoutes). */+ /** The same client ([http]), pinned to one address family (see RelayRoutes); same pool. */private val v4Client by lazy { http.newBuilder().dns(FamilyDns(IpFamily.V4)).build() }private val v6Client by lazy { http.newBuilder().dns(FamilyDns(IpFamily.V6)).build() }private val routes get() = ROUTES@@ -386,16 +371,16 @@ internal class ControlRelay(private val view: WebView, private val fingerprint:private fun reply(id: Int, status: Int, headersJson: String, body: String) {val posted = android.os.SystemClock.uptimeMillis()- main.post { replyNow(id, status, headersJson, body, posted) }+ // Quoted here, on the network thread: a large reply (a track-playback state machine) was+ // quoted on the main thread, which also draws the app and runs every tap behind it.+ val script = "window.__mspNetDone && window.__mspNetDone($id, $status, ${JSONObject.quote(headersJson)}, ${JSONObject.quote(body)})"+ main.post { replyNow(id, script, posted) }}- private fun replyNow(id: Int, status: Int, headersJson: String, body: String, posted: Long) {+ private fun replyNow(id: Int, script: String, posted: Long) {val waited = android.os.SystemClock.uptimeMillis() - postedif (waited > 30) Logbook.log("relay reply #$id waited $waited ms for the main thread")- view.evaluateJavascript(- "window.__mspNetDone && window.__mspNetDone($id, $status, ${JSONObject.quote(headersJson)}, ${JSONObject.quote(body)})",- null,- )+ view.evaluateJavascript(script, null)}/** The last page's playback device, kept across starts (see [PlayerDeviceRecord]). */@@ -492,6 +477,39 @@ internal class ControlRelay(private val view: WebView, private val fingerprint:}companion object {+ /**+ * No cookie jar: the real Web Player's requests to spclient carry no cookie (its `fetch` is+ * cross-origin with the default `credentials: same-origin`; 02-playback capture). The WebView's+ * cookies the relay sent from 2.0.2-beta.9 on (sp_dc, sp_t, sp_key...) were a shape no+ * browser's command has.+ *+ * Chrome's Accept-Encoding ([ACCEPT_ENCODING]) comes from [DECODING], which also decodes the+ * answer (Spotify answers track-playback in zstd, connect-state in gzip or br).+ *+ * One client for every relay (a page rebuilt after a renderer crash gets a new relay, not a+ * new pool), so that [resetConnections] reaches the one in use. A dead connection fails in+ * seconds: with a 30 s read timeout, a command sent on one (the phone moving between Wi-Fi+ * and mobile data, a connection the mobile network dropped while idle) waited that long+ * before anything tried again. Spotify answers these requests in well under a second, so+ * 10 s without a byte is a dead connection; the ping finds one before a command does.+ */+ private val http: OkHttpClient by lazy {+ OkHttpClient.Builder()+ .connectTimeout(10, TimeUnit.SECONDS)+ .readTimeout(10, TimeUnit.SECONDS)+ .pingInterval(15, TimeUnit.SECONDS)+ .addInterceptor(DECODING)+ .eventListener(RelayEvents)+ .build()+ }++ /**+ * The phone moved to another network: the idle connections belong to the old one, and the+ * next request opens a fresh one instead of waiting on them. Not from the main thread+ * (closing a socket can write to it).+ */+ fun resetConnections() = http.connectionPool.evictAll()+/*** The page's own API calls. Every request the WebView makes carries* "X-Requested-With: <our package>" — no browser does that, and it was measured on the wirediff --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 9ebbf3af..eae17e22 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@@ -101,6 +101,32 @@ class WebPlayerHost(private val context: Context) : BridgeHost {init {// Debug builds only: lets desktop tools (chrome://inspect, CDP) look at the page.if (debuggable) WebView.setWebContentsDebuggingEnabled(true)+ watchNetwork()+ }++ /**+ * The phone moves to another network (Wi-Fi to mobile data, or back): the relay's pooled+ * connections still go through the old one, and a command sent on one of them only waited for+ * its timeout. The idle ones are dropped, so the next command opens a connection on the new+ * network; one already waiting fails within the relay's read timeout. The callback runs on the+ * system's network thread, which is where the sockets may be closed.+ */+ private fun watchNetwork() {+ val connectivity = context.getSystemService(android.net.ConnectivityManager::class.java) ?: return+ runCatching {+ connectivity.registerDefaultNetworkCallback(object : android.net.ConnectivityManager.NetworkCallback() {+ private var current: android.net.Network? = null++ override fun onAvailable(network: android.net.Network) {+ val was = current+ current = network+ // The first call names the network the app started on: nothing to drop.+ if (was == null || was == network) return+ Logbook.log("network changed: the relay's idle connections dropped")+ ControlRelay.resetConnections()+ }+ })+ }.onFailure { Logbook.log("network changes not watched: ${it.message}") }}private lateinit var relay: ControlRelay