Native Android client for Spotify, built with Jetpack Compose
Kotlin ad-freeadblockandroidjetpack-composekotlinlyricsmusic-playermusic-videomyspotispotifyspotify-adblockerspotify-clientspotify-connectspotui
Skips about three times faster (tap to sound ~2.5 s -> ~0.8 s): next song preloaded, first tap sent at once, shorter fade, hidden page parked on the settings page; ad breaks reload the page after 1 s instead of after two refused skips
kota-zo40bc0ba36543
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9e5c8aad..d7aa61fc 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,8 @@ Each release on GitHub shows its section below. The app shows it too when it off- **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.+- **Shorter silence on ad breaks** (free accounts): about 4 s less.+- **Skips are about three times faster**: the next song is heard ~0.8 s after the tap instead of ~2.5 s (the next song is loaded ahead, the first tap is sent at once, a shorter fade, and the hidden Spotify page no longer redraws its home screen at every song).- **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/SpotifyPlayer.kt b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyPlayer.ktindex 34082008..b3877a99 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@@ -31,9 +31,10 @@ import kotlinx.serialization.json.putJsonArray** Ads: hosts refuse the ad audio they know. Such an ad then stays current, buffering at* 0:00, and the page never moves on by itself: after [AD_STUCK_MS] the song after the last- * one is played. An ad that gets through (other markets serve ads from other places) is- * muted at once and skipped the same way after [AD_PLAYING_SKIP_MS]; if the page still- * holds on to it after one reload, it stays muted until it ends. [adPlaying] says an ad is+ * one is played. An ad that "plays" (it came without a file, or from another market's ad+ * server) is muted at once and, as it refuses skips, the page is reloaded after+ * [AD_PLAYING_SKIP_MS]; if the page still holds on to it after that reload, it stays muted+ * until it ends. [adPlaying] says an ad is* on; ads are never exposed in [state] (the last song stays there, buffering).** Stalls: on some phones the page stops between two songs (stuck past the end, paused at@@ -203,6 +204,29 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopbridge.logger?.invoke("page back after a reload: ${item.name} did not start again")}+ /** The media element as the watcher last read it. */+ @Volatile private var lastMedia: Media? = null++ /** Loads the song after the current one in advance (see "player.preloadNext"); on by default. */+ @Volatile var preloadNext = true+ /** "current|next" already preloaded. */+ private var preloadedFor: String? = null++ /**+ * Once a song has played a couple of seconds here, the next one is loaded: a skip then+ * starts ~0.3 s sooner. The page does it itself only 10 s before the end, so the bytes are+ * the same when the song plays out; again when the next song changes (queue edits).+ */+ private suspend fun preloadNextSong(s: PlayerState?, media: Media?) {+ if (!preloadNext || s == null || s.isPaused || s.isBuffering || _adPlaying.value || media == null || media.active == false) return+ val next = s.next?.takeIf { it.kind == ItemKind.TRACK || it.kind == ItemKind.EPISODE } ?: return+ if (s.positionAt(System.currentTimeMillis()) < PRELOAD_AFTER_MS) return+ val key = "${s.item?.uri}|${next.uri}"+ if (key == preloadedFor) return+ preloadedFor = key+ runCatching { bridge.call("player.preloadNext", timeoutMs = 5_000, quiet = true) }+ }+/** 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?)@@ -253,7 +277,9 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopcontinue}val media = read.getOrNull()+ lastMedia = mediaval s = _state.value+ preloadNextSong(s, media)if (tick % VOLUME_CHECK_TICKS == 0) guardVolume(s, media)if (_adPlaying.value) {val ad = adState@@ -264,7 +290,10 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopadAttempts++val last = lastTrackState// Playing on can land on the same refused ad again: after a few tries the- // page itself is reloaded, which drops the ad break.+ // page itself is reloaded, which drops the ad break. An ad that "plays" (it+ // has no file: silence on the page's clock) refuses every skip ("Skipping is+ // not allowed with current content"): straight to the reload.+ if (playing) adAttempts = AD_SKIPS_BEFORE_RELOAD + 1if (adRecovery(adAttempts) == "next") {bridge.logger?.invoke("ad stuck on ${ad?.item?.name}: playing the next song (attempt $adAttempts)")last?.let { runCatching { playOn(it) } }@@ -402,7 +431,10 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopval 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 { readMedia() }.getOrNull()?.takeIf { it.active != false }?.level?.takeIf { it > 0.0 } ?: run { 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.0val from = s.item?.urifadeBackTo = targetfadeBack?.cancel()@@ -592,13 +624,15 @@ 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"+ /** 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. */const val AD_BREAK_MAX_MS = 4 * 60_000L/** Volume steps of a fade (down; reversed to come back). */// 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+ val FADE_STEPS = listOf(0.35, 0.08, 0.002)+ const val FADE_STEP_MS = 12L/** The sound always comes back after that long, whatever the page does. */const val FADE_BACK_MAX_MS = 2_500L/** Play commands: the page answers within a few seconds or not at all. */@@ -609,8 +643,8 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopconst val FROZEN_RELOAD_GAP_MS = 60_000L/** The volume is checked every that many ticks. */const val VOLUME_CHECK_TICKS = 3- /** An ad that really plays (muted) is skipped after that long. */- const val AD_PLAYING_SKIP_MS = 1_500L+ /** An ad that plays (silent, muted) is got past after that long. */+ const val AD_PLAYING_SKIP_MS = 1_000Lconst val STUCK_MS = 8_000L/** A song over with nothing after it: where an ad was left out. Next song quickly. */const val END_STUCK_MS = 1_000Ldiff --git a/base/api-spotify/src/main/resources/bridge/player-bridge.js b/base/api-spotify/src/main/resources/bridge/player-bridge.jsindex 3ac580a8..ef36f975 100644--- a/base/api-spotify/src/main/resources/bridge/player-bridge.js+++ b/base/api-spotify/src/main/resources/bridge/player-bridge.js@@ -273,6 +273,14 @@if (!target) throw new Error('no audio quality setting');return !!(await target.setMediaPlaybackQuality({ audio: a.level }));},+ // Loads the song after this one now (its file, first segment and license), as the page+ // itself does only 10 s before the end: a skip then starts that much sooner. -> the result.+ 'player.preloadNext': async () => {+ const sdk = need().resolve('PlayerSDK');+ const lp = sdk && sdk.harmony && sdk.harmony._streamer && sdk.harmony._streamer._listPlayer;+ if (!lp || typeof lp._preloadUpcomingTrack !== 'function') return null;+ return String(await lp._preloadUpcomingTrack());+ },'queue.add': a => need().player.addToQueue(a.uris.map(uri => ({ uri }))),'queue.remove': a => need().player.removeFromQueue(a.items),'queue.clear': () => need().player.clearQueue(),@@ -451,6 +459,19 @@window.Myspoti = { version: VERSION, call, announce, methods: Object.keys(commands) };+ // The page's own UI is never seen. On the home page a song change redraws ~7000 nodes and+ // ~190 images, which held the main thread for ~1 s and delayed the next song's sound; the+ // settings page has ~260 nodes and one image. It must be a real page of the Web Player: a+ // reload (by the page, the WebView or a test) loads the current URL, and an unknown one is+ // served without the player.+ const IDLE_ROUTE = '/preferences';+ const park = () => {+ try {+ const history = services.platform.getHistory && services.platform.getHistory();+ if (history && typeof history.replace === 'function' && location.pathname !== IDLE_ROUTE) history.replace(IDLE_ROUTE);+ } catch (e) { /* the page keeps its route */ }+ };+const started = Date.now();const boot = () => {try {@@ -460,6 +481,7 @@}if (services) {attach();+ park();post({ type: 'ready', version: VERSION });pushState();return;diff --git a/base/app/src/main/java/com/music/spotui/di/SongPlayer.kt b/base/app/src/main/java/com/music/spotui/di/SongPlayer.ktindex e47c858a..1f18146c 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@@ -549,24 +549,40 @@ object SongPlayer {fun stop() = pause()fun next() {+ Log.d(TAG, "next tapped")Haptics.click()if (LocalPlayer.active.value) { LocalPlayer.next(); return }intendPlaying()- // Taps in a row become one jump: a burst of "next" commands left the Web Player- // out of step (state conflicts, then a player stuck until reloaded).+ // The first tap skips at once. Taps that follow it within SKIP_BURST_MS become one+ // jump to the song they add up to: a burst of "next" commands left the Web Player out+ // of step (state conflicts, then a player stuck until reloaded).+ val now = SystemClock.elapsedRealtime()+ if (now - burstAt > SKIP_BURST_MS) {+ burstAt = now+ burstUpcoming = apiQueue?.let { it.queued + it.nextUp }.orEmpty()+ burstTaps = 1+ pendingSkips = 0+ transport { api.player.next() }+ return+ }+ burstAt = now+ burstTaps++pendingSkips++main.removeCallbacks(sendSkips)main.postDelayed(sendSkips, SKIP_BURST_MS)}+ /** When the last "next" tap came, the queue as it was at the first one, and the taps since. */+ private var burstAt = 0L+ private var burstUpcoming: List<app.myspoti.api.NowPlaying> = emptyList()+ private var burstTaps = 0private var pendingSkips = 0private val sendSkips = Runnable {- val n = pendingSkips+ if (pendingSkips <= 0) return@RunnablependingSkips = 0- if (n <= 0) return@Runnable- val upcoming = apiQueue?.let { it.queued + it.nextUp }.orEmpty()- val target = upcoming.getOrNull(n - 1)- transport { if (n == 1 || target == null) api.player.next() else api.player.skipTo(target) }+ // The song [burstTaps] after the one playing at the first tap.+ val target = burstUpcoming.getOrNull(burstTaps - 1)+ transport { if (target == null) api.player.next() else api.player.skipTo(target) }}fun previous() { Haptics.click(); if (LocalPlayer.active.value) { LocalPlayer.previous(); return }; intendPlaying(); transport { api.player.previous() } }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 ca11c2b6..f9049194 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@@ -73,6 +73,7 @@ internal class ControlRelay(private val view: WebView) {// Bytes, not a String body: OkHttp would append "; charset=utf-8" to the content type.val payload = if (method == "GET" || method == "HEAD") null else (sent ?: "").toByteArray().toRequestBody(null)val request = Request.Builder().url(url).headers(built).method(method, payload).build()+ val asked = android.os.SystemClock.uptimeMillis()http.newCall(request).enqueue(object : Callback {override fun onFailure(call: Call, e: IOException) {android.util.Log.d(WebPlayerHost.LOG, "relay $method ${shortPath(url)} failed: ${e.message}")@@ -84,7 +85,8 @@ internal class ControlRelay(private val view: WebView) {val out = JSONObject()it.headers.names().forEach { name -> out.put(name, it.header(name)) }val text = it.body.string()- android.util.Log.d(WebPlayerHost.LOG, "relay $method ${shortPath(url)} -> ${it.code}")+ val net = android.os.SystemClock.uptimeMillis() - asked+ android.util.Log.d(WebPlayerHost.LOG, "relay $method ${shortPath(url)} -> ${it.code} in $net ms")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)@@ -93,7 +95,14 @@ internal class ControlRelay(private val view: WebView) {})}- private fun reply(id: Int, status: Int, headersJson: String, body: String) = main.post {+ 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) }+ }++ private fun replyNow(id: Int, status: Int, headersJson: String, body: String, posted: Long) {+ val waited = android.os.SystemClock.uptimeMillis() - posted+ if (waited > 30) android.util.Log.d(WebPlayerHost.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,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 0717bde0..2ee71a4e 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@@ -192,7 +192,8 @@ class WebPlayerHost(context: Context) : BridgeHost {}, LOAD_WATCH_MS * attempt)}- fun reload() = main.post { view.reload() }+ /** The player's own URL, not the page's current one: the bridge parks the page on an empty route. */+ fun reload() = main.post { view.loadUrl(PLAYER_URL) }fun openLogin() = main.post { view.loadUrl(LOGIN_URL) }diff --git a/docs/CHANGELOG-full.md b/docs/CHANGELOG-full.mdindex 5c0d3d37..ee37e2c6 100644--- a/docs/CHANGELOG-full.md+++ b/docs/CHANGELOG-full.md@@ -12,6 +12,12 @@ Every change, release by release. The short version is in [CHANGELOG.md](../CHAN- **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.+- **Ad breaks are shorter**: an ad the page "plays" without a file refuses every skip, so the page is reloaded after 1 s instead of after two refused skips (~4 s less silence per ad break).+- **Skip latency** (tap to sound, measured on the phone with `tools/skip_latency.py`): median 2.5 s → 0.8 s.+ - The next song is preloaded 2 s into each song (`player.preloadNext`, the page's own `_preloadUpcomingTrack`, which it otherwise runs only 10 s before the end): its file, first segment and manifest are cached.+ - The first "next" tap is sent at once; only taps that follow within 350 ms are gathered into one jump (the first one used to wait 350 ms).+ - The skip fade is 3 short steps without a read before them (~0.2 s → ~0.07 s).+ - The hidden page is parked on the settings page (`/preferences`, ~260 nodes): on the home page each song change redrew ~7000 nodes and ~190 images and held the main thread ~1 s. A real Web Player page, so that any reload still boots the player; the host's own reloads load the player's URL.- **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/skip_latency.py b/tools/skip_latency.pynew file mode 100644index 00000000..492db5d4--- /dev/null+++ b/tools/skip_latency.py@@ -0,0 +1,58 @@+#!/usr/bin/env python3+"""Time from a "next" media key to the next song's sound on the phone (debug build).++usage: tools/skip_latency.py [--n 5] [--wait 6]+The key press and the page's first audio frame are both timed on the phone's clock.+"""+import argparse, json, os, sys, time+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+import playback_test as t++WATCH = """(() => {+ const sdk = (() => { const r = __mspPlat().getRegistry(); for (const k of r._map.keys()) if (k && k.description === 'PlayerSDK') return r.resolve(k); })();+ window.__mspLat = null;+ const pl = sdk.harmony._streamer._playerPromise;+ pl.then(p => {+ const from = window.Myspoti && p._currentContent && p._currentContent._track && p._currentContent._track.uri;+ const started = Date.now();+ const tick = () => {+ const el = p._player;+ if (el && !el.paused && el.currentTime > 0.05 && el.currentTime < 2.5 && el.__mspMark !== undefined && el.currentTime !== el.__mspMark) { window.__mspLat = Date.now(); return; }+ if (el) el.__mspMark = el.currentTime < 2.5 ? el.currentTime : undefined;+ if (Date.now() - started < 8000) setTimeout(tick, 15);+ };+ // Wait for the current song to go away first (its element empties).+ const wait = () => { const el = p._player; if (el && el.currentTime < 0.05) tick(); else if (Date.now() - started < 8000) setTimeout(wait, 10); };+ wait();+ });+ return true;+})()"""++PLAT = """window.__mspPlat = () => { const host = document.getElementById('main') || document.body;+ for (const el of [host, ...host.querySelectorAll('*')]) { const key = Object.keys(el).find(k => k.startsWith('__reactContainer$')); if (!key) continue;+ const stack = [el[key]]; while (stack.length) { const f = stack.pop(); const v = f.memoizedProps && f.memoizedProps.value;+ if (v && typeof v === 'object' && typeof v.getRegistry === 'function') return v; if (f.sibling) stack.push(f.sibling); if (f.child) stack.push(f.child); } } }; true"""+++def main():+ ap = argparse.ArgumentParser()+ ap.add_argument("--n", type=int, default=5)+ ap.add_argument("--wait", type=float, default=6)+ a = ap.parse_args()+ t.evaluate(PLAT)+ out = []+ for _ in range(a.n):+ t.evaluate(WATCH)+ pressed = int(t.adb("shell", "date +%s%3N; input keyevent 87").splitlines()[0])+ time.sleep(a.wait)+ heard = t.evaluate("window.__mspLat")+ ms = heard - pressed if heard else None+ out.append(ms)+ print("next ->", f"{ms} ms" if ms is not None else "no sound seen")+ ok = [m for m in out if m is not None]+ if ok:+ print(f"median {sorted(ok)[len(ok) // 2]} ms, min {min(ok)}, max {max(ok)}")+++if __name__ == "__main__":+ main()