Native Android client for Spotify, built with Jetpack Compose
Kotlin ad-freeadblockandroidjetpack-composekotlinlyricsmusic-playermusic-videomyspotispotifyspotify-adblockerspotify-clientspotify-connectspotui
Fades along the ear's curve that start with the sound, an artist picker, per-network quality, faster big playlists, a fading title bar on list pages
kota-zo7b0422979363
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 b59ea7e0..cf6ca1e1 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@@ -844,6 +844,8 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop@Volatile private var crossfadeUntil = 0L/** The fail-safe that puts the level back if the page never moved on. */private var crossfadeJob: kotlinx.coroutines.Job? = null+ /** Arms the fade-out on the dot when its window opens between two watcher ticks. */+ private var crossfadeTimer: kotlinx.coroutines.Job? = nullprivate fun disarmCrossfade() {crossfadeArmed = false@@ -882,6 +884,17 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopif (item.uri != crossfadeUri || remaining > window) endCrossfade(restore = true)return}+ // The watcher ticks every WATCH_TICK_MS: a window that opens before the next tick is armed+ // on time by a timer, not up to a tick late (a 6 s crossfade lasted 4.3-4.5 s, measured).+ if (remaining > window && remaining <= window + WATCH_TICK_MS) {+ if (crossfadeTimer?.isActive != true) crossfadeTimer = scope.launch {+ delay(remaining - window)+ val st = _state.value ?: return@launch+ if (crossfadeArmed || st.isPaused || st.item?.uri != item.uri) return@launch+ tickCrossfade(st, lastMedia, System.currentTimeMillis())+ }+ return+ }if (remaining <= 0 || remaining > window) return// Nothing after it: a fade-out into silence is not a crossfade.if (s.next == null && upcoming().isEmpty()) return@@ -894,10 +907,13 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopprivate suspend fun armCrossfade(uri: String, remainingMs: Long, own: Double) {val steps = (remainingMs / CROSSFADE_STEP_MS).toInt().coerceIn(2, CROSSFADE_MAX_STEPS)val per = (remainingMs / steps).coerceAtLeast(1L)- // A linear ramp in amplitude, ending on CROSSFADE_FLOOR of the page's own level: the last- // step lands on the song's end, so the fade is over exactly when the song is.+ // Down the ear's curve (the cubic taper of the resume and pause ramps: even steps to the+ // ear; linear in amplitude it stayed loud, then fell away in the last second), ending on+ // CROSSFADE_FLOOR of the page's own level: the last step lands on the song's end.+ val floor = Math.cbrt(CROSSFADE_FLOOR)val levels = (1..steps).map { i ->- (own * (1.0 - (1.0 - CROSSFADE_FLOOR) * i / steps)).coerceAtLeast(CROSSFADE_SILENT)+ val p = 1.0 - (1.0 - floor) * i / steps+ (own * p * p * p).coerceAtLeast(CROSSFADE_SILENT)}crossfadeArmed = truecrossfadeUri = uri@@ -928,10 +944,13 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScoprunCatching { restoreLevel() }return}- val own = m.own.coerceAtLeast(CROSSFADE_SILENT)- // Ends on the page player's own volume, so a volume change during the fade is kept.- runCatching { fade(CROSSFADE_IN.map { it * own }, restore = true, ms = CROSSFADE_IN_STEP_MS) }- .onFailure { runCatching { restoreLevel() } }+ // 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() } }}override suspend fun play(contextUri: Uri, trackUri: Uri?, index: Int?, positionMs: Long?, order: List<Uri>?) {@@ -988,8 +1007,10 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopval fadeOut = level != null && !_adPlaying.value && !adMuted && lastMedia?.active != falseif (fadeOut) {fadeBack?.cancel()- runCatching { fade(PAUSE_STEPS.map { it * level!! }, ms = PAUSE_STEP_MS) }- delay(PAUSE_STEPS.size * PAUSE_STEP_MS)+ runCatching {+ bridge.call("media.ramp", buildJsonObject { put("to", 0); put("ms", PAUSE_MS) }, timeoutMs = LEVEL_TIMEOUT_MS, quiet = true)+ }+ delay(PAUSE_MS)}try {command("player.pause")@@ -1001,10 +1022,11 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop}/** The owner's call: a song coming back after a pause (or after another app had the sound)- * rises in under half a second instead of starting at full level, and a pause fades out in- * an eighth of one, as the official app does. The rise runs in the page and starts on the- * media element's own 'playing' event (see 'media.rise'); [fadeBackTo]/[fadeBack] mark it as- * a fade meanwhile, so the silence watchdog and the volume guard leave it be.+ * rises from silence in half a second, and a pause fades out in a sixth of one, both along+ * the ear's curve, as the official app does. The ramps run in the page on its media element+ * ('media.rise', 'media.ramp'); the rise starts when the element's clock moves, and+ * [fadeBackTo]/[fadeBack] mark it as a fade meanwhile, so the silence watchdog and the volume+ * guard leave it be.*/override suspend fun resume() {pausedByUser = false@@ -1012,8 +1034,9 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopif (quiet) { command("player.resume"); return }fadeBackTo = lastMedia?.own?.takeIf { it > 0.01 } ?: 1.0fadeBack?.cancel()+ bridge.logger?.invoke("resume: rising from silence over $RISE_MS ms once the sound starts")runCatching {- bridge.call("media.rise", buildJsonObject { put("from", RISE_FROM); put("ms", RISE_MS); put("wait", RISE_WAIT_MS) },+ bridge.call("media.rise", buildJsonObject { put("ms", RISE_MS); put("wait", RISE_WAIT_MS) },timeoutMs = LEVEL_TIMEOUT_MS, quiet = true)}try {@@ -1244,8 +1267,8 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop*/const val CROSSFADE_FAILSAFE_MS = 6_000L/** The next song's ramp up: short, it is already playing. Ends on the own level. */- val CROSSFADE_IN = listOf(0.2, 0.45, 0.7, 0.9)- const val CROSSFADE_IN_STEP_MS = 100L+ /** The song after a crossfade rises back to its level in this long. */+ const val CROSSFADE_IN_MS = 600L/** Play commands: the page answers within a few seconds or not at all. */const val PLAY_TIMEOUT_MS = 10_000L/** A refusal that long after a play belongs to it. */@@ -1254,15 +1277,12 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopconst val PICK_AD_MS = 8_000L/** After this the user has moved on: a pick is no longer replayed after its ad. */const val PICK_REPLAY_MS = 120_000L- /** A resumed song starts at this share of its level (-26 dB) ... */- const val RISE_FROM = 0.05- /** ... and rises to it in this long. */- const val RISE_MS = 450L+ /** A resumed song rises from silence to its level in this long, along the ear's curve. */+ const val RISE_MS = 500L/** How long the rise waits for sound before the level simply comes back. */const val RISE_WAIT_MS = 4_000L- /** Pause ramp: ~0.12 s down before the pause itself. */- val PAUSE_STEPS = listOf(0.6, 0.32, 0.12, 0.03)- const val PAUSE_STEP_MS = 30L+ /** A pause first lowers the sound to silence in this long, along the same curve. */+ const val PAUSE_MS = 160L/** A plain skip still on its song after this: the page lost it. */const val NEXT_LOST_MS = 2_500L/** After the refusal fallback's transfer, before the song is asked again. */diff --git a/base/api-spotify/src/main/resources/bridge/player-bridge.js b/base/api-spotify/src/main/resources/bridge/player-bridge.jsindex d7f11449..1e739646 100644--- a/base/api-spotify/src/main/resources/bridge/player-bridge.js+++ b/base/api-spotify/src/main/resources/bridge/player-bridge.js@@ -220,6 +220,30 @@let fadeTimers = [];const cancelFade = () => { fadeTimers.forEach(clearTimeout); fadeTimers = []; };+ // 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+ // to the ear. A linear or stepped ramp was heard as a jump: most of it in the first moments.+ // Ticks every 16 ms; each sets the level the clock is at (a late tick never stretches it).+ // fromK/toK: positions on that curve (0 = silent, 1 = the player's own level, read at every+ // tick so a volume change meanwhile is kept). -> a function that starts it.+ const ramp = (el, player, fromK, toK, ms, done) => () => {+ cancelFade();+ const t0 = performance.now();+ const tick = () => {+ const k = Math.min(1, (performance.now() - t0) / ms);+ const p = fromK + (toK - fromK) * k;+ el.volume = Math.min(1, Math.max(SILENT, ownLevel(player) * p * p * p));+ if (k < 1) fadeTimers.push(setTimeout(tick, 16));+ else if (done) done();+ };+ tick();+ };+ // Where the element stands on that curve now.+ const curveAt = (el, player) => {+ const own = ownLevel(player);+ return own > 0 ? Math.min(1, Math.cbrt(Math.max(0, el.volume) / own)) : 1;+ };+// "Is this page Spotify Connect's active device": a full device-list round trip, so it is// read at most once every ACTIVE_CACHE_MS and reused (a transfer happens minutes apart).const ACTIVE_CACHE_MS = 6000;@@ -438,36 +462,37 @@return true;},- // The sound rising back when a paused song plays again, as the official app does. The- // element goes down to {from} (a share of the player's own level) now; the rise starts when- // the element's clock really moves, the moment sound comes 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. It ends- // on the player's own level, read on every step (a volume change during it is kept). Not- // playing within {wait} ms: the level comes back as it was. {from, ms, wait} -> true+ // The sound going down (a pause) or up, as one smooth ramp. {to: 0..1, ms} -> true+ 'media.ramp': async a => {+ const player = await localPlayer();+ const el = player && player._player;+ if (!(el instanceof HTMLMediaElement)) return null;+ ramp(el, player, curveAt(el, player), Math.min(1, Math.max(0, Number(a.to) || 0)), Math.max(1, Number(a.ms) || 150))();+ return true;+ },++ // The sound rising back when a paused song plays again, as the official app does: silent+ // now, then up along the curve once the element's clock really moves, the moment sound comes+ // 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'media.rise': async a => {const player = await localPlayer();const el = player && player._player;if (!(el instanceof HTMLMediaElement)) return null;cancelFade();- const from = Math.min(1, Math.max(0.01, Number(a.from) || 0.05));- const ms = Math.max(1, Number(a.ms) || 300);- el.volume = Math.max(SILENT, from * ownLevel(player));- const rise = () => {- cancelFade();- const t0 = performance.now();- // Even steps in loudness (dB), not in amplitude: a linear amplitude ramp is heard as a jump.- const tick = () => {- const k = Math.min(1, (performance.now() - t0) / ms);- const own = ownLevel(player);- el.volume = Math.min(1, Math.max(SILENT, own * Math.pow(from, 1 - k)));- if (k < 1) fadeTimers.push(setTimeout(tick, 16));- };- tick();- };- const at = el.currentTime;+ // keep: from where the element is now (the end of a crossfade), not from silence.+ const from = a.keep ? curveAt(el, player) : 0;+ if (!a.keep) el.volume = SILENT;+ const rise = ramp(el, player, from, 1, Math.max(1, Number(a.ms) || 500));+ // Moving: ahead of the last look by a little (a new song's clock starting again from 0 is+ // a jump back, not sound; a seek is a jump, not sound either).+ let prev = el.currentTime;const waitSound = () => {- if (!el.paused && el.currentTime > at + 0.01) rise();+ const t = el.currentTime, step = t - prev;+ prev = t;+ if (!el.paused && step > 0.005 && step < 0.5) rise();else fadeTimers.push(setTimeout(waitSound, 16));};fadeTimers.push(setTimeout(() => { cancelFade(); el.volume = ownLevel(player); }, Math.max(500, Number(a.wait) || 3000)));diff --git a/base/app/src/debug/java/com/music/spotui/di/TestControlReceiver.kt b/base/app/src/debug/java/com/music/spotui/di/TestControlReceiver.ktindex 40572c56..e5c7778c 100644--- a/base/app/src/debug/java/com/music/spotui/di/TestControlReceiver.kt+++ b/base/app/src/debug/java/com/music/spotui/di/TestControlReceiver.kt@@ -17,6 +17,7 @@ import kotlinx.serialization.json.jsonObject* cmd: uitrace (--ei secs <n>, default 30) logs, 5 times a second under the tag MspTrace, what the* app shows (position, duration, playing, title, cover) next to what the page plays, so a run* can tell a jumping bar or a stale title/cover from the engine's own state (tools/qa.py --ui).+ * cmd: crossfade (--ei secs <0..12>) sets the crossfade between songs, as the Settings slider does.* cmd: gql (--es op <operation> --es vars <json>) runs a persisted operation through the app's own* Gql layer and logs the raw response: learning a server shape from the phone's real account beats* guessing one from a bundle.@@ -46,6 +47,7 @@ class TestControlReceiver : BroadcastReceiver() {// The player's own "next" button and the mini player's swipe."swipenext" -> SongPlayer.swipeNext()"previous" -> SongPlayer.previous()+ "crossfade" -> com.music.spotui.data.preferences.CrossfadePref.set(context, intent.getIntExtra("secs", 0))"uitrace" -> {val secs = intent.getIntExtra("secs", 30).coerceIn(1, 600)app.myspoti.host.android.MyspotiRuntime.scope.launch(kotlinx.coroutines.Dispatchers.Main) {diff --git a/base/app/src/main/java/com/music/spotui/data/DataSaver.kt b/base/app/src/main/java/com/music/spotui/data/DataSaver.ktindex 05f19af0..aaa08ef4 100644--- a/base/app/src/main/java/com/music/spotui/data/DataSaver.kt+++ b/base/app/src/main/java/com/music/spotui/data/DataSaver.kt@@ -68,10 +68,14 @@ object DataSaver {val was = meteredmetered = !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)if (was && !metered) com.music.spotui.data.offline.OfflineCollections.onUnmetered(app)+ // Wi-Fi and mobile data each have their own streaming level.+ if (was != metered) com.music.spotui.data.preferences.applyStreamingQuality(app)changed()}override fun onLost(network: Network) {+ val was = meteredmetered = cm.isActiveNetworkMetered+ if (was != metered) com.music.spotui.data.preferences.applyStreamingQuality(app)changed()}})diff --git a/base/app/src/main/java/com/music/spotui/data/api/Api.kt b/base/app/src/main/java/com/music/spotui/data/api/Api.ktindex 5a0af27c..f5c81665 100644--- a/base/app/src/main/java/com/music/spotui/data/api/Api.kt+++ b/base/app/src/main/java/com/music/spotui/data/api/Api.kt@@ -32,6 +32,7 @@ import com.music.spotui.data.entity.SongsModelimport com.music.spotui.di.Graphimport com.music.spotui.di.SongPlayerimport kotlinx.coroutines.async+import kotlinx.coroutines.sync.withPermitimport kotlinx.coroutines.coroutineScopeimport kotlinx.coroutines.flow.Flowimport kotlinx.coroutines.flow.first@@ -822,19 +823,41 @@ class Api constructor(ownerUri = pl.ownerUri.orEmpty(),metaLine = saves,)+ // The first page gives the total: the rest is asked for PLAYLIST_PARALLEL pages at a time+ // and shown in order as it lands, at most every PLAYLIST_EMIT_MS. One page after the+ // other, each followed by the whole list shown and registered again, a 6000-song+ // playlist took about two minutes (tester report).val songs = ArrayList<SongsModel>()- var offset = 0var failed = false- while (true) {- val result = if (offset == 0) firstPage.await() else runCatching { api.playlists.tracks(uri, offset, 100) }- val page = result.getOrElse { failed = true; null } ?: break- songs += page.items.map(::songOf)+ val first = firstPage.await().getOrElse { failed = true; null }+ fun publish(done: Boolean): Response<ContextPageModel> {SongPlayer.registerContext(songs.map { it.url }, uri)val total = songs.sumOf { it.durationMs.toLong() }val meta = listOf(saves, if (total > 0) durationLabel(total) else "").filter { it.isNotBlank() }.joinToString(" • ")- val done = page.nextOffset == null- emit(Response.Success(header.copy(metaLine = meta, tracks = songs.toList(), complete = done)))- offset = page.nextOffset ?: break+ return Response.Success(header.copy(metaLine = meta, tracks = songs.toList(), complete = done))+ }+ if (first != null) {+ songs += first.items.map(::songOf)+ val offsets = generateSequence(first.nextOffset) { (it + PLAYLIST_PAGE).takeIf { n -> n < first.total } }.toList()+ emit(publish(done = offsets.isEmpty()))+ if (offsets.isNotEmpty()) {+ val gate = kotlinx.coroutines.sync.Semaphore(PLAYLIST_PARALLEL)+ coroutineScope {+ val jobs = offsets.map { o -> async(Dispatchers.IO) { gate.withPermit { runCatching { api.playlists.tracks(uri, o, PLAYLIST_PAGE) }.getOrNull() } } }+ var lastEmit = System.currentTimeMillis()+ for ((i, job) in jobs.withIndex()) {+ val page = job.await()+ if (page == null) { failed = true; jobs.drop(i + 1).forEach { it.cancel() }; break }+ songs += page.items.map(::songOf)+ val last = i == jobs.lastIndex+ if (last || System.currentTimeMillis() - lastEmit >= PLAYLIST_EMIT_MS) {+ emit(publish(done = last)); lastEmit = System.currentTimeMillis()+ }+ }+ }+ // A page that failed: what came before it stays, marked complete so nothing waits.+ if (failed && songs.isNotEmpty()) emit(publish(done = true))+ }}if (failed && songs.isEmpty()) emit(Response.Error(context.getString(R.string.couldnt_load, pl.name)))}@@ -1018,3 +1041,8 @@ class Api constructor(return nameMatches.firstOrNull(::artistMatches) ?: candidates.firstOrNull(::artistMatches) ?: nameMatches.firstOrNull() ?: candidates.first()}}++/** Songs per playlist page, pages asked for at once, and the most often a growing list is shown again. */+private const val PLAYLIST_PAGE = 100+private const val PLAYLIST_PARALLEL = 4+private const val PLAYLIST_EMIT_MS = 350Ldiff --git a/base/app/src/main/java/com/music/spotui/data/local/LocalMusic.kt b/base/app/src/main/java/com/music/spotui/data/local/LocalMusic.ktindex 822e71f7..ac36b945 100644--- a/base/app/src/main/java/com/music/spotui/data/local/LocalMusic.kt+++ b/base/app/src/main/java/com/music/spotui/data/local/LocalMusic.kt@@ -106,7 +106,17 @@ object LocalFolders {private const val PREFS = "local_folders"private const val KEY_OUT = "excluded"private const val KEY_SEEN = "seen"- private val defaultOut = Regex("""(?i)whatsapp|telegram|signal|messenger|recordings?|enregistrements|voice|notifications|ringtones|alarms|call""")+ private const val KEY_RULES = "rules"+ /**+ * Messaging, recorder and system-sound folders, matched on a whole folder name: matched+ * anywhere in the path, "call", "voice" or "signal" also hid music folders ("Calling You",+ * "Voices", "Signal Fire" — tester report after beta.9).+ */+ private val defaultOut = Regex("""(?i)whatsapp.*|telegram.*|signal|messenger|recordings?|enregistrements|voice ?(notes|recorder|memos|recordings?)?|notifications|ringtones|alarms|call ?(recordings?|recorder)?|callrecord(ing|ings)?""")+ /** The earlier rule, kept only to take back what it hid on its own. */+ private val oldDefaultOut = Regex("""(?i)whatsapp|telegram|signal|messenger|recordings?|enregistrements|voice|notifications|ringtones|alarms|call""")++ private fun autoOut(folder: String) = folder.split('/').any { defaultOut.matches(it.trim()) }private fun prefs(context: Context) = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)@@ -114,10 +124,15 @@ object LocalFolders {fun excluded(context: Context, known: Set<String>): Set<String> {val p = prefs(context)val out = p.getStringSet(KEY_OUT, emptySet()).orEmpty().toMutableSet()+ // Once: the folders the old rule hid on its own and the new one would not are shown again.+ if (p.getInt(KEY_RULES, 1) < 2) {+ out.removeAll { oldDefaultOut.containsMatchIn(it) && !autoOut(it) }+ p.edit().putStringSet(KEY_OUT, out).putInt(KEY_RULES, 2).apply()+ }val seen = p.getStringSet(KEY_SEEN, emptySet()).orEmpty()val fresh = known - seenif (fresh.isNotEmpty()) {- out += fresh.filter { defaultOut.containsMatchIn(it) }+ out += fresh.filter { autoOut(it) }p.edit().putStringSet(KEY_OUT, out).putStringSet(KEY_SEEN, seen + fresh).apply()}return outdiff --git a/base/app/src/main/java/com/music/spotui/data/preferences/QualityPref.kt b/base/app/src/main/java/com/music/spotui/data/preferences/QualityPref.ktindex a2b06387..94009df4 100644--- a/base/app/src/main/java/com/music/spotui/data/preferences/QualityPref.kt+++ b/base/app/src/main/java/com/music/spotui/data/preferences/QualityPref.kt@@ -10,6 +10,8 @@ import kotlinx.coroutines.launchprivate const val PREF = "settings_prefs"private const val KEY_STREAMING = "streaming_quality"private const val KEY_CHOSEN = "quality_chosen"+private const val KEY_STREAMING_CELL = "streaming_quality_cellular"+private const val KEY_CANVAS_WIFI = "canvas_wifi_only"/*** The Web Player's own streaming levels (its "Streaming quality" setting): 24, 96 and@@ -38,22 +40,33 @@ enum class DownloadQuality {}}-fun getStreamingQuality(c: Context): StreamingQuality =- StreamingQuality.of(prefs(c).getString(KEY_STREAMING, null))+/**+ * The level for Wi-Fi, or for mobile data ([cellular]), as the official app's two settings.+ * Mobile data follows the Wi-Fi level until it is set on its own.+ */+fun getStreamingQuality(c: Context, cellular: Boolean = false): StreamingQuality {+ val wifi = prefs(c).getString(KEY_STREAMING, null)+ return StreamingQuality.of(if (cellular) prefs(c).getString(KEY_STREAMING_CELL, null) ?: wifi else wifi)+}-/** Saves the level and hands it to the player (now, and on every later page load). */-fun setStreamingQuality(c: Context, q: StreamingQuality) {- prefs(c).edit().putString(KEY_STREAMING, q.level).apply()- applyStreamingQuality(q)+/** Saves the level for that network and hands the one for the current network to the player. */+fun setStreamingQuality(c: Context, q: StreamingQuality, cellular: Boolean = false) {+ prefs(c).edit().putString(if (cellular) KEY_STREAMING_CELL else KEY_STREAMING, q.level).apply()+ applyStreamingQuality(c)}-/** Gives the saved level to the Web Player; harmless before it is up (it keeps the level). */-fun applyStreamingQuality(q: StreamingQuality) {+/** Gives the current network's level to the Web Player (at start and when the network changes); harmless before it is up. */+fun applyStreamingQuality(c: Context) {val runtime = app.myspoti.host.android.MyspotiRuntimeif (!runtime.isStarted) return+ val q = getStreamingQuality(c, cellular = com.music.spotui.data.DataSaver.metered)runtime.scope.launch { runtime.spotify.player.setAudioQuality(q.level) }}+/** Canvas (the looping videos) only on Wi-Fi: they cost data on every song. */+fun isCanvasWifiOnly(c: Context): Boolean = prefs(c).getBoolean(KEY_CANVAS_WIFI, false)+fun setCanvasWifiOnly(c: Context, on: Boolean) = prefs(c).edit().putBoolean(KEY_CANVAS_WIFI, on).apply()+fun getDownloadQuality(c: Context): DownloadQuality = when {!isLosslessEnabled(c) -> DownloadQuality.OFFisAskDownloadQuality(c) -> DownloadQuality.ASKdiff --git a/base/app/src/main/java/com/music/spotui/di/Graph.kt b/base/app/src/main/java/com/music/spotui/di/Graph.ktindex 4e2e04f5..4c7469d4 100644--- a/base/app/src/main/java/com/music/spotui/di/Graph.kt+++ b/base/app/src/main/java/com/music/spotui/di/Graph.kt@@ -17,7 +17,7 @@ object Graph {// The Spotify session: hidden Web Player + API (operation hashes refresh themselves).MyspotiRuntime.start(application, loadPage = !com.music.spotui.data.DataSaver.active)// The streaming quality the user chose, set on the player at every page load.- com.music.spotui.data.preferences.applyStreamingQuality(com.music.spotui.data.preferences.getStreamingQuality(application))+ com.music.spotui.data.preferences.applyStreamingQuality(application)// The crossfade length (0 = off), in the player from the first song on.com.music.spotui.data.preferences.applyCrossfade(com.music.spotui.data.preferences.getCrossfadeSeconds(application))com.music.spotui.data.local.ListenHistory.init(application)diff --git a/base/app/src/main/java/com/music/spotui/ui/components/ArtistChooser.kt b/base/app/src/main/java/com/music/spotui/ui/components/ArtistChooser.ktnew file mode 100644index 00000000..9b395bc5--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/components/ArtistChooser.kt@@ -0,0 +1,125 @@+package com.music.spotui.ui.components++import androidx.compose.foundation.background+import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.navigationBarsPadding+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.material3.ExperimentalMaterial3Api+import androidx.compose.material3.ModalBottomSheet+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.produceState+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import androidx.navigation.NavHostController+import app.myspoti.api.ArtistRef+import app.myspoti.host.android.MyspotiRuntime+import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi+import com.bumptech.glide.integration.compose.GlideImage+import app.myspoti.engine.R+import com.music.spotui.ui.navigation.artistRoute+import kotlinx.coroutines.launch++/**+ * "Go to artist" on a song by several artists, as in the official app: a sheet lists each of+ * them, and a tap on one opens that artist's page. A song by one artist opens it at once.+ * Shared by the player's artist line and the song menu (one sheet, at the navigation root, so+ * it outlives the menu that asked for it).+ */+object ArtistChooser {+ internal var artists by mutableStateOf<List<ArtistRef>>(emptyList())+ internal var open: (String) -> Unit = {}++ /** Songs whose artists are known: the player looks the playing one up ahead ([prefetch]), so a tap opens at once. */+ private val known = object : LinkedHashMap<String, List<ArtistRef>>(32, 0.75f, true) {+ override fun removeEldestEntry(eldest: MutableMap.MutableEntry<String, List<ArtistRef>>) = size > 32+ }++ /** The song's artists, from its catalog entry; the displayed names (no ids) when it is out of reach. */+ suspend fun artistsOf(trackId: String, fallbackNames: String): List<ArtistRef> {+ synchronized(known) { known[trackId] }?.let { return it }+ val found = if (trackId.isBlank()) null else runCatching {+ MyspotiRuntime.api.catalog.track("spotify:track:$trackId").artists+ }.getOrNull()?.filter { it.name.isNotBlank() }?.takeIf { it.isNotEmpty() }+ if (found != null) synchronized(known) { known[trackId] = found }+ return found ?: fallbackNames.split(",").map { it.trim() }.filter { it.isNotEmpty() }.map { ArtistRef("", it) }+ }++ /** Looks a song's artists up before anyone asks (the playing song). */+ fun prefetch(trackId: String) {+ if (trackId.isBlank() || synchronized(known) { trackId in known }) return+ MyspotiRuntime.scope.launch { artistsOf(trackId, "") }+ }++ /** Opens the one artist, or the sheet to pick among several. */+ fun go(artists: List<ArtistRef>, navigate: (String) -> Unit) {+ when (artists.size) {+ 0 -> return+ 1 -> navigate(routeOf(artists[0]))+ else -> { open = navigate; this.artists = artists }+ }+ }++ /** [go] for a song, its artists looked up first. */+ fun goForTrack(trackId: String, fallbackNames: String, navigate: (String) -> Unit) {+ MyspotiRuntime.scope.launch(kotlinx.coroutines.Dispatchers.Main) {+ go(artistsOf(trackId, fallbackNames), navigate)+ }+ }++ internal fun routeOf(a: ArtistRef) = artistRoute(a.name, a.uri.substringAfterLast(':'))+}++@OptIn(ExperimentalMaterial3Api::class, ExperimentalGlideComposeApi::class)+@Composable+fun ArtistChooserHost(navController: NavHostController) {+ val artists = ArtistChooser.artists+ if (artists.isEmpty()) return+ val dismiss = { ArtistChooser.artists = emptyList() }+ ModalBottomSheet(onDismissRequest = dismiss, containerColor = Color(0xFF282828)) {+ Column(Modifier.navigationBarsPadding().padding(bottom = 12.dp)) {+ Text(stringResource(R.string.choose_artist), color = Color.White, fontSize = 18.sp, fontWeight = FontWeight.Bold,+ modifier = Modifier.padding(20.dp, 0.dp, 20.dp, 12.dp))+ artists.forEach { a ->+ // The picture comes in after the name: the sheet opens at once.+ val picture by produceState<String?>(null, a.uri) {+ value = if (a.uri.isBlank()) null+ else runCatching { MyspotiRuntime.api.catalog.artist(a.uri).images.minByOrNull { it.width ?: Int.MAX_VALUE }?.url }.getOrNull()+ }+ Row(+ verticalAlignment = Alignment.CenterVertically,+ modifier = Modifier.fillMaxWidth().clickable {+ val go = ArtistChooser.open+ dismiss()+ go(ArtistChooser.routeOf(a))+ }.padding(horizontal = 20.dp, vertical = 8.dp),+ ) {+ Box(Modifier.size(48.dp).clip(CircleShape).background(Color(0xFF3E3E3E))) {+ if (picture != null) GlideImage(model = picture, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.size(48.dp))+ }+ Spacer(Modifier.width(14.dp))+ Text(a.name, color = Color.White, fontSize = 16.sp, maxLines = 1, overflow = TextOverflow.Ellipsis)+ }+ }+ }+ }+}diff --git a/base/app/src/main/java/com/music/spotui/ui/components/PlayerSheets.kt b/base/app/src/main/java/com/music/spotui/ui/components/PlayerSheets.ktindex 32772e60..c8b7d470 100644--- a/base/app/src/main/java/com/music/spotui/ui/components/PlayerSheets.kt+++ b/base/app/src/main/java/com/music/spotui/ui/components/PlayerSheets.kt@@ -144,7 +144,7 @@ fun DevicesSheet(onDismiss: () -> Unit) {Text(activeDeviceLabel(), color = Color.White, fontSize = 20.sp, fontWeight = FontWeight.Bold,maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false))if (remote == null) Text(- stringResource(streamingLabel(com.music.spotui.data.preferences.getStreamingQuality(context))),+ stringResource(streamingLabel(com.music.spotui.data.preferences.getStreamingQuality(context, com.music.spotui.data.DataSaver.metered))),color = Color(0xFFDDDDDD), fontSize = 12.sp, fontWeight = FontWeight.Medium,modifier = Modifier.padding(start = 8.dp).clip(RoundedCornerShape(6.dp)).background(Color(0xFF4A4A4A)).clickable { quality = true }.padding(horizontal = 6.dp, vertical = 2.dp),@@ -260,7 +260,9 @@ private fun QualitySheet(onDismiss: () -> Unit) {},color = Green, fontSize = 15.sp, modifier = Modifier.padding(horizontal = 20.dp, vertical = 4.dp),)- if (!local) StreamingQualityPicker(Modifier.padding(top = 12.dp))+ // The level of the network in use now (Wi-Fi and mobile data each keep their own).+ if (!local) StreamingQualityPicker(Modifier.padding(top = 12.dp), cellular = com.music.spotui.data.DataSaver.metered,+ title = if (com.music.spotui.data.DataSaver.metered) R.string.quality_streaming_cell_title else R.string.quality_streaming_wifi_title)}}}diff --git a/base/app/src/main/java/com/music/spotui/ui/components/QualityPickers.kt b/base/app/src/main/java/com/music/spotui/ui/components/QualityPickers.ktindex 23dc9f88..a216f2a5 100644--- a/base/app/src/main/java/com/music/spotui/ui/components/QualityPickers.kt+++ b/base/app/src/main/java/com/music/spotui/ui/components/QualityPickers.kt@@ -34,11 +34,11 @@ import com.music.spotui.data.preferences.setStreamingQuality/** The streaming levels of the Web Player, one choice; saved and applied at once. */@Composable-fun StreamingQualityPicker(modifier: Modifier = Modifier) {+fun StreamingQualityPicker(modifier: Modifier = Modifier, cellular: Boolean = false, title: Int = R.string.quality_streaming_title) {val ctx = LocalContext.current- var current by remember { mutableStateOf(getStreamingQuality(ctx)) }+ var current by remember(cellular) { mutableStateOf(getStreamingQuality(ctx, cellular)) }QualityGroup(- title = stringResource(R.string.quality_streaming_title),+ title = stringResource(title),detail = stringResource(R.string.quality_streaming_detail),options = listOf(Option(StreamingQuality.AUTO, R.string.quality_streaming_auto, R.string.quality_streaming_auto_detail),@@ -47,7 +47,7 @@ fun StreamingQualityPicker(modifier: Modifier = Modifier) {Option(StreamingQuality.HIGH, R.string.quality_streaming_high, R.string.quality_streaming_high_detail),),selected = current,- onSelect = { current = it; setStreamingQuality(ctx, it) },+ onSelect = { current = it; setStreamingQuality(ctx, it, cellular) },modifier = modifier,)}diff --git a/base/app/src/main/java/com/music/spotui/ui/navigation/MyNavHost.kt b/base/app/src/main/java/com/music/spotui/ui/navigation/MyNavHost.ktindex adc015d0..f96f62ce 100644--- a/base/app/src/main/java/com/music/spotui/ui/navigation/MyNavHost.kt+++ b/base/app/src/main/java/com/music/spotui/ui/navigation/MyNavHost.kt@@ -69,12 +69,13 @@ fun MyNavHost(if (navHostController.currentDestination?.route != Routes.Spotiflac.route) navHostController.navigate(Routes.Spotiflac.route)}}+ com.music.spotui.ui.components.ArtistChooserHost(navHostController)NavHost(navController = navHostController,startDestination = startDestination,- // Same motion as the official app: tabs switch instantly, pages slide in from- // the right over a slight parallax, the player and queue rise from the bottom.- // Slides only (no alpha): a fade puts the whole page in an offscreen layer.+ // Pages: a short shift with a fade-through, tabs fade in, the player and queue rise+ // from the bottom (see navEnter). The fades put a page in an offscreen layer for+ // their 0.1-0.2 s: the owner's call, a page change read as a hard block without them.enterTransition = { navEnter(initialState, targetState) },exitTransition = { navExit(initialState, targetState) },popEnterTransition = { navPopEnter(initialState, targetState) },diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/ContextScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/ContextScreen.ktindex 1ee32ccb..103bd8ea 100644--- a/base/app/src/main/java/com/music/spotui/ui/screens/ContextScreen.kt+++ b/base/app/src/main/java/com/music/spotui/ui/screens/ContextScreen.kt@@ -47,6 +47,7 @@ import androidx.compose.runtime.setValueimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.draw.alpha+import androidx.compose.ui.graphics.graphicsLayerimport androidx.compose.ui.draw.clipimport androidx.compose.ui.draw.drawWithContentimport androidx.compose.ui.draw.shadow@@ -667,6 +668,37 @@ private fun ContextContent(navController: NavController, vm: ContextViewModel, pitem { Spacer(Modifier.height(com.music.spotui.ui.components.bottomBarsSpace())) }}com.music.spotui.ui.components.FastScrollbar(listState, Modifier.align(Alignment.CenterEnd))+ // As in the official app: once the header has mostly scrolled away, a bar in the page's colour+ // fades in at the top with the back arrow and the name; the list no longer runs bare under the+ // status bar. Its opacity follows the scroll in the draw phase (no recomposition per frame).+ val barAlpha = remember(listState) {+ androidx.compose.runtime.derivedStateOf {+ if (listState.firstVisibleItemIndex > 0) 1f else {+ val h = listState.layoutInfo.visibleItemsInfo.firstOrNull()?.size?.toFloat() ?: return@derivedStateOf 0f+ ((listState.firstVisibleItemScrollOffset - h * 0.6f) / (h * 0.2f)).coerceIn(0f, 1f)+ }+ }+ }+ val barShown by remember(listState) { androidx.compose.runtime.derivedStateOf { barAlpha.value > 0f } }+ if (barShown) Row(+ verticalAlignment = Alignment.CenterVertically,+ modifier = Modifier+ .fillMaxWidth()+ .graphicsLayer { alpha = barAlpha.value }+ .background(lerp(tint, Color.Black, 0.45f))+ .statusBarsPadding()+ .height(56.dp),+ ) {+ Box(+ contentAlignment = Alignment.Center,+ modifier = Modifier.padding(horizontal = 8.dp).size(40.dp).clip(CircleShape).clickable { navController.navigateUp() },+ ) {+ Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.accessibility_navigate_back), tint = Color.White)+ }+ // Centred, as on the artist page.+ Text(p.name, color = Color.White, fontSize = 18.sp, fontWeight = FontWeight.Bold, maxLines = 1, overflow = TextOverflow.Ellipsis,+ textAlign = androidx.compose.ui.text.style.TextAlign.Center, modifier = Modifier.weight(1f).padding(end = 56.dp))+ }androidx.compose.material3.SnackbarHost(hostState = snackbar,modifier = Modifier.align(Alignment.BottomCenter).padding(bottom = com.music.spotui.ui.components.bottomBarsSpace()),diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/PlayerScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/PlayerScreen.ktindex 694871c9..82bb8b46 100644--- a/base/app/src/main/java/com/music/spotui/ui/screens/PlayerScreen.kt+++ b/base/app/src/main/java/com/music/spotui/ui/screens/PlayerScreen.kt@@ -225,6 +225,8 @@ fun PlayerScreen(navController: NavController) {val currentTrack = queueSongs.firstOrNull { it.id == songId }val actualTrackId = confirmedTrackIdFromUri(np.uri)val displayedTrackId = confirmedTrackIdForDisplay(np.uri, songId)+ // The artists are looked up ahead: a tap on the artist line opens the page (or the choice) at once.+ LaunchedEffect(displayedTrackId) { com.music.spotui.ui.components.ArtistChooser.prefetch(displayedTrackId) }// Smooth progress: redrawn every frame from the engine clock (see SpotifySeekBar).// As many ticks as the knob has pixels to move: ~5 a second on a 3-minute song, up to 15 on@@ -257,7 +259,8 @@ fun PlayerScreen(navController: NavController) {// Hide a stale result in this composition, before the loading effect runs.LaunchedEffect(displayedTrackId, energy.policy.allowCanvas, audioBuffering) {playerViewModel.loadCanvas(- if (energy.policy.allowCanvas && !com.music.spotui.data.DataSaver.active) displayedTrackId else "",+ if (energy.policy.allowCanvas && !com.music.spotui.data.DataSaver.active &&+ !(com.music.spotui.data.DataSaver.metered && com.music.spotui.data.preferences.isCanvasWifiOnly(context))) displayedTrackId else "",allowFetch = !audioBuffering,)}@@ -266,7 +269,8 @@ fun PlayerScreen(navController: NavController) {// only follows one frame later): the screen then opens on the Canvas, not on the cover.val knownCanvas = remember(displayedTrackId) { com.music.spotui.di.Graph.api.knownCanvas(displayedTrackId)?.getOrNull() }val canvasUrl = (if (canvas.trackId == displayedTrackId) canvas.url else knownCanvas).takeIf {- energy.policy.allowCanvas && !com.music.spotui.data.DataSaver.active && displayedTrackId.isNotBlank()+ energy.policy.allowCanvas && !com.music.spotui.data.DataSaver.active &&+ !(com.music.spotui.data.DataSaver.metered && com.music.spotui.data.preferences.isCanvasWifiOnly(context)) && displayedTrackId.isNotBlank()}// The cover stays until the Canvas has drawn its first frame: hiding it earlier showed// the bare background for a moment (a flash) between the cover and the clip.@@ -275,6 +279,8 @@ fun PlayerScreen(navController: NavController) {// Cover to Canvas as one cross-fade: the clip (full screen) fades in while the cover fades// out and grows a little into it, instead of the background switching at once.val canvasOn = canvasUrl != null && canvasShown+ // The immersive view is the Canvas's: a song without one leaves it.+ LaunchedEffect(canvasOn) { if (!canvasOn) immersive = false }// A clip already loaded shows at once; one still loading fades in over the cover.val readyAtOnce = remember(canvasUrl) { canvasUrl != null && com.music.spotui.ui.components.CanvasPlayer.isReady(canvasUrl) }val canvasProgress = remember { androidx.compose.animation.core.Animatable(if (readyAtOnce) 1f else 0f) }@@ -408,11 +414,12 @@ fun PlayerScreen(navController: NavController) {// screens): otherwise play / pause ends up under the lyrics card.// A clear upward drag on the artwork opens the lyrics (observed on the initial pass,// never consumed, so the pager and the pull-to-close keep working).- Box(modifier = Modifier.size(artSide).pointerInput(immersive, videoOn) {+ Box(modifier = Modifier.size(artSide).pointerInput(immersive, videoOn, canvasOn) {detectTapGestures(onTap = {- // Plain tap on the artwork: the immersive toggle, with or without a Canvas- // (it used to depend on the Canvas being there, and only ever turned on).- if (!videoOn) immersive = !immersive+ // A tap on a Canvas hides the rest to show the whole clip. A plain cover has+ // nothing more to show: blown up to the screen's height it was only cropped+ // on both sides (reported: the tap "broke" the image), so it does nothing.+ if (!videoOn && canvasOn) immersive = !immersive})}.pointerInput(Unit) {val threshold = 80.dp.toPx()diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/SettingsScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/SettingsScreen.ktindex e3442e6d..744d5704 100644--- a/base/app/src/main/java/com/music/spotui/ui/screens/SettingsScreen.kt+++ b/base/app/src/main/java/com/music/spotui/ui/screens/SettingsScreen.kt@@ -33,6 +33,7 @@ import androidx.compose.material3.Textimport androidx.compose.runtime.Composableimport androidx.compose.runtime.getValueimport androidx.compose.runtime.remember+import androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.setValueimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifier@@ -67,7 +68,15 @@ fun SettingsScreen(navController: NavController) {}Column(Modifier.fillMaxWidth().weight(1f).verticalScroll(rememberScrollState()).navigationBarsPadding()) {Section(R.string.settings_section_playback)- StreamingQualityPicker()+ StreamingQualityPicker(title = R.string.quality_streaming_wifi_title)+ StreamingQualityPicker(cellular = true, title = R.string.quality_streaming_cell_title)+ var canvasWifiOnly by remember { mutableStateOf(com.music.spotui.data.preferences.isCanvasWifiOnly(ctx)) }+ OptionRow(+ label = stringResource(R.string.canvas_wifi_only),+ detail = stringResource(R.string.canvas_wifi_only_detail),+ checked = canvasWifiOnly,+ onChecked = { canvasWifiOnly = it; com.music.spotui.data.preferences.setCanvasWifiOnly(ctx, it) },+ )OptionRow(label = stringResource(R.string.settings_autoplay_title),detail = stringResource(R.string.settings_autoplay_detail),@@ -184,7 +193,9 @@ fun SettingsScreen(navController: NavController) {Text(stringResource(R.string.diagnostic_export_title), color = Color.White, fontSize = 16.sp)Text(stringResource(R.string.diagnostic_export_detail), color = Color(0xFFB3B3B3), fontSize = 12.sp)}- Spacer(Modifier.height(96.dp))+ // Clear of the mini player and the navigation bar, as every other page (96 dp left the+ // last rows, "Restart the player" among them, under the mini player).+ Spacer(Modifier.height(com.music.spotui.ui.components.bottomBarsSpace()))}}}diff --git a/base/app/src/main/java/com/music/spotui/ui/viewmodel/PlayerViewModel.kt b/base/app/src/main/java/com/music/spotui/ui/viewmodel/PlayerViewModel.ktindex 7db7fe9f..cb32820d 100644--- a/base/app/src/main/java/com/music/spotui/ui/viewmodel/PlayerViewModel.kt+++ b/base/app/src/main/java/com/music/spotui/ui/viewmodel/PlayerViewModel.kt@@ -125,20 +125,9 @@ class PlayerViewModel constructor(private val currentSongState: CurrentSongState}}- fun goToArtist(trackId: String, fallbackName: String, navigate: (route: String) -> Unit) {- viewModelScope.launch {- val route = withContext(Dispatchers.IO) {- val artist = if (trackId.isNotBlank())- runCatching { app.myspoti.host.android.MyspotiRuntime.api.catalog.track("spotify:track:$trackId") }.getOrNull()?.artists?.firstOrNull()- else null- artistRoute(- artist?.name?.ifBlank { null } ?: fallbackName.substringBefore(",").trim(),- artist?.uri?.substringAfterLast(':').orEmpty(),- )- }- navigate(route)- }- }+ /** The song's artist page; a song by several artists asks which one first (see ArtistChooser). */+ fun goToArtist(trackId: String, fallbackName: String, navigate: (route: String) -> Unit) =+ com.music.spotui.ui.components.ArtistChooser.goForTrack(trackId, fallbackName, navigate)/*** Play the track at an absolute [index] in [queueSongs]. Used by the now-playingdiff --git a/base/app/src/main/res/values-de/myspoti_strings.xml b/base/app/src/main/res/values-de/myspoti_strings.xmlindex 5a9ae76f..e9d4c71f 100644--- a/base/app/src/main/res/values-de/myspoti_strings.xml+++ b/base/app/src/main/res/values-de/myspoti_strings.xml@@ -273,6 +273,11 @@<string name="playlist_access_collaborative_detail">Alle mit dem Link können Songs hinzufügen und entfernen</string><string name="playlist_on_profile">Auf deinem Profil</string><string name="playlist_on_profile_detail">Auf deinem Profil für andere sichtbar</string>+ <string name="choose_artist">Künstler auswählen</string>+ <string name="quality_streaming_wifi_title">Streaming über WLAN</string>+ <string name="quality_streaming_cell_title">Streaming über mobile Daten</string>+ <string name="canvas_wifi_only">Canvas nur im WLAN</string>+ <string name="canvas_wifi_only_detail">Die Loop-Videos laufen im WLAN, nie über mobile Daten</string><string name="playlist_delete_confirm">"%1$s" löschen? Sie kann innerhalb von 90 Tagen aus deinem Spotify-Konto wiederhergestellt werden.</string><string name="playlist_saved">Playlist aktualisiert</string><string name="go_to_profile">Zum Profil</string>diff --git a/base/app/src/main/res/values-el/myspoti_strings.xml b/base/app/src/main/res/values-el/myspoti_strings.xmlindex 564536c3..aee9b18d 100644--- a/base/app/src/main/res/values-el/myspoti_strings.xml+++ b/base/app/src/main/res/values-el/myspoti_strings.xml@@ -273,6 +273,11 @@<string name="playlist_access_collaborative_detail">Όποιος έχει τον σύνδεσμο μπορεί να προσθέτει και να αφαιρεί τραγούδια</string><string name="playlist_on_profile">Στο προφίλ σου</string><string name="playlist_on_profile_detail">Εμφανίζεται στο προφίλ σου για τους άλλους</string>+ <string name="choose_artist">Επίλεξε καλλιτέχνη</string>+ <string name="quality_streaming_wifi_title">Ροή μέσω Wi-Fi</string>+ <string name="quality_streaming_cell_title">Ροή με δεδομένα κινητής</string>+ <string name="canvas_wifi_only">Canvas μόνο σε Wi-Fi</string>+ <string name="canvas_wifi_only_detail">Τα βίντεο σε επανάληψη παίζουν μόνο σε Wi-Fi, ποτέ με δεδομένα κινητής</string><string name="playlist_delete_confirm">Να διαγραφεί η «%1$s»; Μπορεί να επαναφερθεί από τον λογαριασμό σου στο Spotify για 90 ημέρες.</string><string name="playlist_saved">Η playlist ενημερώθηκε</string><string name="go_to_profile">Μετάβαση στο προφίλ</string>diff --git a/base/app/src/main/res/values-es/myspoti_strings.xml b/base/app/src/main/res/values-es/myspoti_strings.xmlindex 62616b40..b6a545ab 100644--- a/base/app/src/main/res/values-es/myspoti_strings.xml+++ b/base/app/src/main/res/values-es/myspoti_strings.xml@@ -273,6 +273,11 @@<string name="playlist_access_collaborative_detail">Cualquiera con el enlace puede añadir y quitar canciones</string><string name="playlist_on_profile">En tu perfil</string><string name="playlist_on_profile_detail">Aparece en tu perfil para que otros la vean</string>+ <string name="choose_artist">Elige un artista</string>+ <string name="quality_streaming_wifi_title">Streaming por Wi-Fi</string>+ <string name="quality_streaming_cell_title">Streaming con datos móviles</string>+ <string name="canvas_wifi_only">Canvas solo con Wi-Fi</string>+ <string name="canvas_wifi_only_detail">Los vídeos en bucle se reproducen con Wi-Fi, nunca con datos móviles</string><string name="playlist_delete_confirm">¿Eliminar «%1$s»? Se puede restaurar desde tu cuenta de Spotify durante 90 días.</string><string name="playlist_saved">Playlist actualizada</string><string name="go_to_profile">Ir al perfil</string>diff --git a/base/app/src/main/res/values-fr/myspoti_strings.xml b/base/app/src/main/res/values-fr/myspoti_strings.xmlindex 7c67e7bc..eb88db20 100644--- a/base/app/src/main/res/values-fr/myspoti_strings.xml+++ b/base/app/src/main/res/values-fr/myspoti_strings.xml@@ -313,6 +313,11 @@<string name="playlist_access_collaborative_detail">Toute personne avec le lien peut ajouter et retirer des titres</string><string name="playlist_on_profile">Sur votre profil</string><string name="playlist_on_profile_detail">Affichée sur votre profil, visible par les autres</string>+ <string name="choose_artist">Choisir un artiste</string>+ <string name="quality_streaming_wifi_title">Streaming en Wi-Fi</string>+ <string name="quality_streaming_cell_title">Streaming en données mobiles</string>+ <string name="canvas_wifi_only">Canvas en Wi-Fi uniquement</string>+ <string name="canvas_wifi_only_detail">Les vidéos en boucle passent en Wi-Fi, jamais en données mobiles</string><string name="playlist_delete_confirm">Supprimer « %1$s » ? Elle peut être restaurée depuis votre compte Spotify pendant 90 jours.</string><string name="playlist_saved">Playlist mise à jour</string><string name="go_to_profile">Voir le profil</string>diff --git a/base/app/src/main/res/values-it/myspoti_strings.xml b/base/app/src/main/res/values-it/myspoti_strings.xmlindex c687cc2b..007c0466 100644--- a/base/app/src/main/res/values-it/myspoti_strings.xml+++ b/base/app/src/main/res/values-it/myspoti_strings.xml@@ -273,6 +273,11 @@<string name="playlist_access_collaborative_detail">Chiunque abbia il link può aggiungere e rimuovere brani</string><string name="playlist_on_profile">Sul tuo profilo</string><string name="playlist_on_profile_detail">Mostrata sul tuo profilo, visibile agli altri</string>+ <string name="choose_artist">Scegli un artista</string>+ <string name="quality_streaming_wifi_title">Streaming in Wi-Fi</string>+ <string name="quality_streaming_cell_title">Streaming con dati mobili</string>+ <string name="canvas_wifi_only">Canvas solo in Wi-Fi</string>+ <string name="canvas_wifi_only_detail">I video in loop partono in Wi-Fi, mai con i dati mobili</string><string name="playlist_delete_confirm">Eliminare «%1$s»? Si può ripristinare dal tuo account Spotify per 90 giorni.</string><string name="playlist_saved">Playlist aggiornata</string><string name="go_to_profile">Vai al profilo</string>diff --git a/base/app/src/main/res/values-pt/myspoti_strings.xml b/base/app/src/main/res/values-pt/myspoti_strings.xmlindex ec0cc440..08258e94 100644--- a/base/app/src/main/res/values-pt/myspoti_strings.xml+++ b/base/app/src/main/res/values-pt/myspoti_strings.xml@@ -273,6 +273,11 @@<string name="playlist_access_collaborative_detail">Quem tiver a ligação pode adicionar e remover músicas</string><string name="playlist_on_profile">No seu perfil</string><string name="playlist_on_profile_detail">Aparece no seu perfil para outras pessoas</string>+ <string name="choose_artist">Escolha um artista</string>+ <string name="quality_streaming_wifi_title">Streaming por Wi-Fi</string>+ <string name="quality_streaming_cell_title">Streaming com dados móveis</string>+ <string name="canvas_wifi_only">Canvas só no Wi-Fi</string>+ <string name="canvas_wifi_only_detail">Os vídeos em loop tocam no Wi-Fi, nunca com dados móveis</string><string name="playlist_delete_confirm">Eliminar «%1$s»? Pode ser restaurada na tua conta Spotify durante 90 dias.</string><string name="playlist_saved">Playlist atualizada</string><string name="go_to_profile">Ir para o perfil</string>diff --git a/base/app/src/main/res/values/myspoti_strings.xml b/base/app/src/main/res/values/myspoti_strings.xmlindex ccdd3dfd..3c175684 100644--- a/base/app/src/main/res/values/myspoti_strings.xml+++ b/base/app/src/main/res/values/myspoti_strings.xml@@ -313,6 +313,11 @@<string name="playlist_access_collaborative_detail">Anyone with the link can add and remove songs</string><string name="playlist_on_profile">On your profile</string><string name="playlist_on_profile_detail">Listed on your profile for others to see</string>+ <string name="choose_artist">Choose an artist</string>+ <string name="quality_streaming_wifi_title">Wi-Fi streaming</string>+ <string name="quality_streaming_cell_title">Mobile data streaming</string>+ <string name="canvas_wifi_only">Canvas on Wi-Fi only</string>+ <string name="canvas_wifi_only_detail">The looping videos play on Wi-Fi, never on mobile data</string><string name="playlist_delete_confirm">Delete "%1$s"? It can be restored from your Spotify account for 90 days.</string><string name="playlist_saved">Playlist updated</string><string name="go_to_profile">Go to profile</string>diff --git a/tools/pilot.py b/tools/pilot.pyindex e87962f8..aeaa6d58 100644--- a/tools/pilot.py+++ b/tools/pilot.py@@ -11,7 +11,10 @@ DIR/<scenario>.log / .media.jsonl, analysed by tools/uitrace_check.py into .analB end of a song (seek to duration - 8 s): the next one within ~3 s at full volumeC 4 minutes of continuous play across a song boundaryD 10 pause/resume cycles with random gaps, next/previous, swipenext bursts, seeks+ X crossfade 6 s over 2 natural song ends, then crossfade 0 and a third end (element volume timeline per end)+ H headless robustness: pause, 3 min, `resume` broadcast (does the process survive, how long to playing)F tools/qa.py --battery all (PT_SAFE=1: no screen key, no force-stop of other apps)+PT_HEADLESS=1: nothing is started in front and no `input` is sent (see tools/playback_test.py); the user is not waited for.Rules: only play/pause/skip/seek; never touches the screen; waits 2 min while the user is on the phone;stops on 6+ licence 429 lines. Results: DIR/results.json (+ REPORT.md draft via --report DIR)."""@@ -36,7 +39,10 @@ class Stop(Exception):# ── the phone is the user's ───────────────────────────────────────────────────def user_active():- """True when the screen is on and something else than the app is in front."""+ """True when the screen is on and something else than the app is in front.+ PT_HEADLESS=1: never (the pilot touches neither screen nor foreground; it does not wait for the user)."""+ if pt.HEADLESS:+ return Falsep = L.adb("shell", "dumpsys", "power", timeout=20)awake = "mWakefulness=Awake" in pif not awake:@@ -134,6 +140,43 @@ def pct(v):return None if v is None else round(v, 3)+def fade_failures(an, fname):+ """The resume rise and the pause ramp (build 2009): see tools/uitrace_check.py fade_metrics."""+ f = []+ for r in an.get("rises", []):+ where = dict(file=fname + ".log", line=r["line"], ms=r["ms"])+ if r["t_move_ms"] is None:+ f.append(dict(kind="rise_no_audio", detail=f"resume at {r['ms']}: the element's clock never moved", **where))+ continue+ if r.get("vol_max_before_move") is not None and r["vol_max_before_move"] > 0.01:+ f.append(dict(kind="rise_not_silent", detail=f"element volume {r['vol_max_before_move']} before the clock moved (expected ~0.001)", **where))+ st = r.get("fit_start_after_move_ms")+ if st is not None and abs(st) > 100:+ f.append(dict(kind="rise_start_offset", detail=f"cubic rise starts {st} ms from the clock moving (expected within ~50 ms), fit rms {r.get('fit_rms')}", **where))+ if r.get("to_full_after_move_ms") is None or r["to_full_after_move_ms"] > 750:+ f.append(dict(kind="rise_slow", detail=f"full level {r.get('to_full_after_move_ms')} ms after the clock moved (expected ~500)", **where))+ if r.get("level_ratio_to_own") is not None and r["level_ratio_to_own"] < 0.98:+ f.append(dict(kind="rise_low_end", detail=f"level {r['level_after_median']} 2.5-6 s after = {r['level_ratio_to_own']} of the pre-pause level {r['own']}", **where))+ if r.get("vol_min_after_full") is not None and r["vol_min_after_full"] < 0.9 * r["own"]:+ f.append(dict(kind="rise_dip_after_full", detail=f"volume dipped to {r['vol_min_after_full']} after reaching the level", **where))+ for p in an.get("pause_fades", []):+ where = dict(file=fname + ".log", line=p["line"], ms=p["ms"])+ if p["to_pause_event_ms"] is None:+ f.append(dict(kind="pause_no_event", detail="no element pause event within 3 s", **where))+ continue+ if p["vol_at_pause_event"] is not None and p["vol_at_pause_event"] > 0.05:+ f.append(dict(kind="pause_not_silent", detail=f"element volume {p['vol_at_pause_event']} when the pause event fired", **where))+ if not 100 <= p["to_pause_event_ms"] <= 350:+ f.append(dict(kind="pause_latency", detail=f"pause event {p['to_pause_event_ms']} ms after the command (expected ~160 + call)", **where))+ if not p["monotonic_down"]:+ f.append(dict(kind="pause_not_monotonic", detail=f"ramp {p['ramp']}", **where))+ return f+++def pidof():+ return L.adb("shell", "pidof", PKG).strip()++# ── scenarios ─────────────────────────────────────────────────────────────────def sc_A1(out, T):@@ -151,7 +194,7 @@ def sc_A1(out, T):stop_check(cap)finally:an = finish(cap, "A1", ref=ref)- f = failures(an)+ f = failures(an) + fade_failures(an, "A1_short_pause")rr = resume_rows(an)if not (ms1 and ms1["volume"] >= 0.98 * ms0["own"] and not ms1["paused"]):f.append(dict(kind="final_volume", detail=f"final media.state {ms1}", file="A1_short_pause.log"))@@ -214,7 +257,7 @@ def sc_A2(out, T, long_s, name="A2_long_pause", idx=0):stop_check(cap)finally:an = finish(cap, "A2", ref=ref)- f = failures(an)+ f = failures(an) + fade_failures(an, name)t = notes.get("timers", {})for lab, c in t.items():if "error" in c:@@ -316,7 +359,7 @@ def sc_D(out, T, seed=20261020):final = media_state()finally:an = finish(cap, "D", ref=1.0)- f = failures(an)+ f = failures(an) + fade_failures(an, "D_commands")if not (final["volume"] >= 0.98 * final["own"] and not final["paused"]):f.append(dict(kind="final_volume", detail=f"final media.state {final}", file="D_commands.log"))cm = an["cmd_metrics"]@@ -329,6 +372,147 @@ def sc_D(out, T, seed=20261020):seek_eng_pos_after=g("seek", "eng_pos_after")), analysis=an)+def wait_song_change(uri, timeout):+ """Polls the page until the current song is not [uri]; -> the probe or None."""+ end = time.time() + timeout+ while time.time() < end:+ try:+ p = pt.probe(patience=3)+ if p["track"]["uri"] != uri and p["track"]["uri"]:+ return p+ except Exception:+ pass+ time.sleep(1.0)+ return None+++def xfade_failures(an, own=1.0):+ """The crossfade scenario: the 3 natural ends (2 with crossfade, 1 without) of X_crossfade."""+ # the ramp itself is not a "low volume" anomaly: those inside a crossfade window (log line -> switch) are expected+ f = [x for x in failures(an) if not (x["kind"] == "low_volume" and any(c["log"] and c["log"][0][0] - 500 <= x["ms"] <= c["switch_ms"] + 500 for c in an["crossfades"]))]+ xf = an["crossfades"]+ if len(xf) < 3:+ f.append(dict(kind="boundaries_missing", detail=f"{len(xf)} natural song changes seen, 3 expected", file="X_crossfade.log"))+ for i, x in enumerate(xf):+ tag = "crossfade" if i < 2 else "crossfade 0"+ gap = x.get("audio_gap_ms")+ if gap is not None and gap > 1000 and i < 2:+ f.append(dict(kind="xfade_gap", ms=x["switch_ms"], detail=f"{tag}: {gap} ms with no audio progress at the switch", file="X_crossfade.log", line=x["line"]))+ if x["level_3_6s_after_min"] is not None and x["level_3_6s_after_min"] < 0.9 * own:+ f.append(dict(kind="xfade_stuck_low", ms=x["switch_ms"], detail=f"{tag}: level {x['level_3_6s_after_min']} 3-6 s after the new song started", file="X_crossfade.log", line=x["line"]))+ if i < 2 and x["longest_below_0_1_ms"] > 1500:+ f.append(dict(kind="xfade_long_low", ms=x["switch_ms"], detail=f"{tag}: {x['longest_below_0_1_ms']} ms below volume 0.1", file="X_crossfade.log", line=x["line"]))+ if i >= 2 and x["vol_min_overall"] < 0.9 * own:+ f.append(dict(kind="xfade_off_still_fading", ms=x["switch_ms"], detail=f"crossfade 0: volume fell to {x['vol_min_overall']} around the switch", file="X_crossfade.log", line=x["line"]))+ return f+++def sc_X(out, T, secs=6):+ """Crossfade: [secs] s set, 2 natural song ends (seek to duration - 15 s), then crossfade 0 and a third end."""+ cap = L.Capture(out, "X_crossfade")+ notes = {}+ try:+ L.adb("shell", "am", "broadcast", "-a", "app.myspoti.TEST", "-p", PKG, "--es", "cmd", "crossfade", "--ei", "secs", str(secs))+ time.sleep(1)+ p = start_song(T[8], 5)+ uitrace(190)+ notes["own"] = media_state()["own"]+ ends = []+ for i in range(2):+ d = p["track"]["durationMs"]+ cur = p["track"]["uri"]+ L.cmd("seek", ms=d - 15000)+ nxt = wait_song_change(cur, 40)+ ends.append(dict(i=i, ok=bool(nxt), media_after=(nxt or {}).get("media")))+ if not nxt:+ break+ time.sleep(8)+ p = pt.probe()+ stop_check(cap)+ notes["crossfade_on_ends"] = ends+ notes["state_after_2"] = media_state()+ L.adb("shell", "am", "broadcast", "-a", "app.myspoti.TEST", "-p", PKG, "--es", "cmd", "crossfade", "--ei", "secs", "0")+ time.sleep(2)+ d = p["track"]["durationMs"]+ cur = p["track"]["uri"]+ L.cmd("seek", ms=d - 10000)+ nxt = wait_song_change(cur, 30)+ notes["crossfade_0_end_ok"] = bool(nxt)+ time.sleep(8)+ notes["final_state"] = media_state()+ stop_check(cap)+ finally:+ try:+ L.adb("shell", "am", "broadcast", "-a", "app.myspoti.TEST", "-p", PKG, "--es", "cmd", "crossfade", "--ei", "secs", "0")+ except Exception:+ pass+ an = finish(cap, "X")+ f = xfade_failures(an, notes.get("own") or 1)+ xf = an["crossfades"]+ return dict(name="X crossfade 6 s, 2 natural ends, then 0", fail=f, key=dict(notes=notes, crossfades=[{k: v for k, v in x.items() if k != "timeline"} for x in xf],+ timelines=[x["timeline"] for x in xf]), analysis=an)+++def sc_H(out, T, wait=180):+ """Headless robustness: pause, wait [wait] s (the service leaves the foreground 60 s after a pause), then a `resume` broadcast."""+ cap = L.Capture(out, "H_headless", sampler=False)+ notes = {"timeline": []}+ try:+ start_song(T[9], 6)+ notes["pid_at_pause"] = pidof()+ L.cmd("pause")+ t0 = time.time()+ time.sleep(3)+ while time.time() - t0 < wait:+ sv = L.adb("shell", "dumpsys", "activity", "services", PKG, timeout=30)+ fg = re.findall(r"isForeground=(\w+)", sv)+ notes["timeline"].append(dict(after_s=round(time.time() - t0), pid=pidof(), isForeground=fg[:2]))+ time.sleep(max(0, 15 - 0.5))+ notes["pid_before_resume"] = pidof()+ t1 = time.time()+ phone_ms = L.phone_now_ms()+ L.cmd("resume")+ notes["resume_sent_phone_ms"] = phone_ms+ notes["probe_timeline"] = []+ played = None+ last_pos = None+ while time.time() - t1 < 60:+ try:+ p = pt.evaluate(pt.PROBE, timeout=6)+ pos = p.get("pos")+ row = dict(dt=round(time.time() - t1, 1), paused=p.get("paused"), buffering=p.get("buffering"), pos=None if pos is None else int(pos), pid=pidof())+ except Exception as e:+ row = dict(dt=round(time.time() - t1, 1), err=str(e)[:60], pid=pidof())+ p = None+ notes["probe_timeline"].append(row)+ if p and p.get("paused") is False and not p.get("buffering") and (p.get("media") or {}).get("paused") is False:+ if last_pos is not None and (p.get("pos") or 0) > last_pos + 400:+ played = row["dt"]+ break+ last_pos = p.get("pos") or 0+ time.sleep(0.4)+ notes["resume_to_playing_s"] = played+ notes["pid_after_resume"] = pidof()+ if played is None:+ # the process had gone, or the engine is not running: the service started again, as the harness does+ notes["fallback"] = "headless service start + resume"+ pt.launch()+ time.sleep(20)+ pt.wait_ready(60)+ L.cmd("resume")+ time.sleep(10)+ notes["after_fallback"] = pt.probe()+ stop_check(cap)+ finally:+ cap.stop()+ f = []+ if notes.get("resume_to_playing_s") is None:+ f.append(dict(kind="headless_resume_failed", detail=f"no playback within 60 s of the resume broadcast; pid before {notes.get('pid_before_resume')!r}, after {notes.get('pid_after_resume')!r}", file="H_headless.log"))+ if not notes.get("pid_before_resume"):+ f.append(dict(kind="process_died", detail=f"process gone after {wait} s of pause (pid at pause {notes.get('pid_at_pause')})", file="H_headless.log"))+ return dict(name="H headless: pause 3 min then resume", fail=f, key=notes)++def sc_F(out):log = os.path.join(out, "F_qa_battery_all.txt")env = dict(os.environ, PT_SAFE="1")@@ -362,7 +546,7 @@ def sc_F(out):def main():ap = argparse.ArgumentParser()ap.add_argument("--out")- ap.add_argument("--only", default="A1,A2,B,C,D,F")+ ap.add_argument("--only", default="A1,A2,B,C,D,F") # X (crossfade) and H (headless robustness) on requestap.add_argument("--long-pause", type=int, default=400)a = ap.parse_args()out = a.out or os.path.join(ROOT, "tools/qa-results", "pilot-" + time.strftime("%Y%m%d-%H%M"))@@ -374,7 +558,7 @@ def main():T = tracks()print("tracks:", len(T), flush=True)jobs = {"A1": lambda: sc_A1(out, T), "A2": lambda: sc_A2(out, T, a.long_pause), "B": lambda: sc_B(out, T), "B2": lambda: sc_B(out, T, "B2_end_of_track", 4), "B3": lambda: sc_B(out, T, "B3_end_of_track", 6), "A2b": lambda: sc_A2(out, T, a.long_pause, "A2b_long_pause", 5), "C": lambda: sc_C(out, T),- "D": lambda: sc_D(out, T), "F": lambda: sc_F(out)}+ "D": lambda: sc_D(out, T), "F": lambda: sc_F(out), "X": lambda: sc_X(out, T), "H": lambda: sc_H(out, T)}for name in [x for x in a.only.split(",") if x]:courtesy()t0 = time.time()diff --git a/tools/pilot_report.py b/tools/pilot_report.pyindex 957e285f..1f32400a 100644--- a/tools/pilot_report.py+++ b/tools/pilot_report.py@@ -43,6 +43,12 @@ def telling(base, f, n=6):def scenario_failures(name, base, an, res):f = pilot.failures(an)+ if name == "H":+ return list(res.get("fail", [])) # no media sampler in H: the scenario's own verdict+ if name == "X":+ f = pilot.xfade_failures(an, (res.get("key", {}).get("notes") or {}).get("own") or 1)+ if name in ("A1", "A2", "A2b", "D"):+ f += pilot.fade_failures(an, os.path.basename(base))if name in ("B", "B2", "B3", "C", "A2", "A2b"):f += pilot.boundary_failures(an)if name in ("A2", "A2b"):@@ -71,7 +77,9 @@ SCEN = [("A1", "A1_short_pause", "A1 short pause (5 s) x3, resume rise + latency("B2", "B2_end_of_track", "B2 end of track, second song"),("B3", "B3_end_of_track", "B3 end of track, third song"),("C", "C_long_play", "C 4 min continuous play across a boundary"),- ("D", "D_commands", "D pause/resume x10, next/previous, swipenext bursts, seeks")]+ ("D", "D_commands", "D pause/resume x10, next/previous, swipenext bursts, seeks"),+ ("X", "X_crossfade", "X crossfade 6 s over 2 natural song ends, then crossfade 0 and a third end"),+ ("H", "H_headless", "H headless: pause 3 min, process / foreground service, then a resume broadcast")]def fmt(v):@@ -121,6 +129,21 @@ def main(d):md.append(f"- {n_}: ms to engine song change {g(n_, 'to_eng_uri_change_ms')}, to app song change {g(n_, 'to_ui_uri_change_ms')}, to first audio {g(n_, 'to_audio_ms')}"+ (f", to restart {g(n_, 'to_eng_restart_ms')}" if n_ == "previous" else ""))md.append(f"- seek: engine positions after each seek (sampled) {g('seek', 'eng_pos_after')}")+ if key in ("A1", "A2", "A2b", "D"):+ for i_, x in enumerate(an.get("rises", [])):+ md.append(f"- rise {i_ + 1} (log:{x['line']}): rise-set +{x.get('t_rise_set_ms')} ms, clock moved +{x['t_move_ms']} ms, vol max before move {x.get('vol_max_before_move')}, vol at move {x.get('vol_at_move')}, "+ f"cubic start {x.get('fit_start_after_move_ms')} ms from the move (fit rms {x.get('fit_rms')}), events: silence set +{x.get('ev_silence_set_ms')} ms with the clock {x.get('ev_silence_set_clock_ahead_s')} s ahead of the pause point, first rise step +{x.get('ev_rise_first_ms')} ms with the clock {x.get('ev_rise_first_clock_ahead_s')} s ahead, full {x.get('to_full_after_move_ms')} ms after the move, "+ f"level {x.get('level_after_median')} / pre-pause {x['own']}, min after full {x.get('vol_min_after_full')}")+ for i_, x in enumerate(an.get("pause_fades", [])):+ md.append(f"- pause {i_ + 1} (log:{x['line']}): element pause event +{x['to_pause_event_ms']} ms, volume then {x['vol_at_pause_event']}, ramp (ms, vol) {x['ramp']}, cubic start {x.get('fit_start_after_cmd_ms')} ms (rms {x.get('fit_rms')})")+ if key == "X":+ for i_, x in enumerate(an.get("crossfades", [])):+ md.append(f"- end {i_ + 1} ({'crossfade 6 s' if i_ < 2 else 'crossfade 0'}) `{x['from_title']}` -> `{x['to_title']}` (log:{x['line']}): silence at the switch {x['audio_gap_ms']} ms, "+ f"longest < 0.1: {x['longest_below_0_1_ms']} ms, < 0.02: {x['longest_below_0_02_ms']} ms, min {x['vol_min_overall']}, 3-6 s after min {x['level_3_6s_after_min']}; log {[l[2] for l in x['log']]}")+ md.append(" - element volume vs time from the engine's song switch (ms:vol): " + " ".join(f"{t}:{v}" for t, v, _, _ in x["timeline"] if -6500 <= t <= 2500))+ if key == "H":+ md.append(f"- {fmt({x: v for x, v in k.items() if x != 'timeline'})}")+ md.append(f"- process / foreground flag while paused: {fmt(k.get('timeline'))}")for b in an["boundaries"]:md.append(f"- natural song change `{b['from_title']}` -> `{b['to_title']}`: audio gap {b.get('audio_gap_ms')} ms, engine switch {b.get('switch_after_audio_end_ms')} ms after old audio end, "f"new song min volume 1.5-4 s after start {b.get('new_vol_min_1.5s_to_4s')} (log:{b['line']})")diff --git a/tools/playback_test.py b/tools/playback_test.pyindex 6653ff0e..d076120f 100644--- a/tools/playback_test.py+++ b/tools/playback_test.py@@ -38,6 +38,13 @@ SERIAL = None# no force-stop of other apps, no pull_back scenario (launches the Spotify app, transfers playback to# another device). The screen stays as the user left it.SAFE = bool(os.environ.get("PT_SAFE"))+# PT_HEADLESS=1 (default off): the owner is on the phone, so nothing may reach the foreground or the+# input system. The app is started as a foreground service only (no activity), and the media keys+# of key() are sent as the debug receiver's commands (next, previous, resume, pause) instead of+# `input keyevent`; every other key is dropped. Implies PT_SAFE.+HEADLESS = bool(os.environ.get("PT_HEADLESS"))+if HEADLESS:+ SAFE = Truedef adb(*args, check=True, timeout=60):@@ -271,7 +278,15 @@ class Run:raise Fail("log: " + " | ".join(bad[:4]))+KEY_COMMANDS = {87: "next", 88: "previous", 126: "resume", 127: "pause"}++def key(code):+ if HEADLESS:+ for c in (code if isinstance(code, list) else [code]):+ if c in KEY_COMMANDS:+ test(KEY_COMMANDS[c])+ returnif SAFE:code = [c for c in (code if isinstance(code, list) else [code]) if c not in (3, 26, 223, 224)] # HOME wakes the screen tooif not code:@@ -290,6 +305,10 @@ NEXT, PREV, PLAY, PAUSE, HOME, SLEEP, WAKE = 87, 88, 126, 127, 3, 223, 224def launch():+ if HEADLESS:+ # The playback service alone (no activity, nothing in front): the engine runs without a screen.+ adb("shell", "am", "start-foreground-service", "-n", PKG + "/app.myspoti.host.android.PlaybackService")+ returnadb("shell", "monkey", "-p", PKG, "-c", "android.intent.category.LAUNCHER", "1")diff --git a/tools/qa.py b/tools/qa.pyindex 6b979ea0..d42c9b6c 100644--- a/tools/qa.py+++ b/tools/qa.py@@ -19,6 +19,8 @@ usage: tools/qa.py [--build] [--unit] [--battery all|light|name,name] [--perf] [Every phone step also counts Spotify's HTTP 429 on audio licences: a run that triggers themis stopped, since more runs would only make Spotify's limit on the test account last.Debug build only; one driver at a time on the phone.+PT_HEADLESS=1: no activity, no input (the app starts as its service, media keys become the test receiver's+commands): see tools/playback_test.py. --perf and --anim need the screen and are refused then."""import argparse, glob, json, os, re, subprocess, sys, time@@ -69,6 +71,13 @@ def step_unit(out):def ensure_app():+ if pt.HEADLESS:+ # PT_HEADLESS=1: the service alone, only when the app is not running (see tools/playback_test.py)+ if not adb("shell", "pidof", PKG).strip():+ pt.launch()+ time.sleep(18)+ pt.wait_ready(60)+ returnadb("shell", "monkey", "-p", PKG, "-c", "android.intent.category.LAUNCHER", "1")time.sleep(2)pt.wait_ready(60)@@ -230,6 +239,8 @@ def main():a = ap.parse_args()pt.SERIAL = a.serial or next((l.split()[0] for l in sh(pt.ADB, "devices").splitlines()[1:] if l.endswith("device")), None)out = {}+ if pt.HEADLESS and (a.perf or a.anim):+ sys.exit("PT_HEADLESS=1: --perf and --anim tap the screen; refused")if a.unit:step_unit(out)if a.build and not step_build(out):diff --git a/tools/uitrace_check.py b/tools/uitrace_check.pyindex 651af4b8..179b17fd 100644--- a/tools/uitrace_check.py+++ b/tools/uitrace_check.py@@ -60,7 +60,7 @@ def check_ui(traces, cmds):for i in range(1, len(traces)):a, b = traces[i - 1], traces[i]dt = b["t"] - a["t"]- if dt > 1000:+ if 1000 < dt <= 20000: # a longer hole is a new uitrace session (the trace is requested for a number of seconds)E.append(ev("trace_gap", b["ms"], cmds, f"{dt} ms without a trace line", b["no"]))if a["ui_uri"] == b["ui_uri"] and a["ui_play"] and b["ui_play"] and a["ui_uri"] not in ("", "null"):d = b["ui_pos"] - a["ui_pos"]@@ -301,6 +301,124 @@ def natural_boundaries(traces, merged, samples, cmds):return out+# ── fades: the resume rise, the pause ramp, the crossfade ─────────────────────++def _fit_cubic(rows, t_lo, t_hi, own, model):+ """Best start time t0 (ms) of [model](t - t0) -> 0..1, vol = own * k^3, over the samples in [t_lo, t_hi]. -> (t0, rms)"""+ pts = [(r[0], r[4]) for r in rows if t_lo <= r[0] <= t_hi]+ if len(pts) < 4:+ return None, None+ best = None+ for t0 in range(int(t_lo) - 300, int(t_hi) + 1, 4):+ e = sum((v - max(0.001, own * model(t - t0) ** 3)) ** 2 for t, v in pts)+ if best is None or e < best[0]:+ best = (e, t0)+ return best[1], round((best[0] / len(pts)) ** 0.5, 4)+++def fade_metrics(samples, events, cmds, rise_ms=500, pause_ms=160):+ """Per resume: when the element is silent, when its clock moves, when the volume starts to rise (cubic fit),+ how long to the full level, the level reached. Per pause: the ramp down (cubic fit) and the pause event."""+ S = [s for s in samples if not s[7]]+ rises, pauses = [], []+ for idx, (ms, name, no) in enumerate(cmds):+ nxt = cmds[idx + 1][0] if idx + 1 < len(cmds) else ms + 20000+ before = [s for s in S if s[0] <= ms]+ if not before:+ continue+ last = before[-1]+ el, ct0 = last[1], last[2]+ E = [s for s in S if s[1] == el]+ if name == "pause" and not last[3]:+ pe = next((e for e in events if e[2] == el and ms <= e[0] <= ms + 3000 and e[1] == "pause"), None)+ lvl = max(s[4] for s in E if ms - 600 <= s[0] <= ms) or last[4]+ ramp = [(s[0] - ms, s[4]) for s in E if ms - 60 <= s[0] <= (pe[0] if pe else ms + 400)]+ d = dict(cmd="pause", ms=ms, line=no, level_before=lvl, to_pause_event_ms=(pe[0] - ms) if pe else None,+ vol_at_pause_event=pe[4] if pe else None, ramp=ramp[::max(1, len(ramp) // 10)])+ t0, rms = _fit_cubic(E, ms - 50, (pe[0] if pe else ms + 300), lvl, lambda dt: max(0.0, 1 - dt / pause_ms))+ d["fit_start_after_cmd_ms"] = None if t0 is None else t0 - ms+ d["fit_rms"] = rms+ vols = [v for _, v in ramp]+ d["monotonic_down"] = all(b <= a + 0.02 for a, b in zip(vols, vols[1:]))+ pauses.append(d)+ elif name == "resume":+ pre = [s for s in before if s[1] == el and s[3]]+ own = max([s[4] for s in E if ms - 12000 <= s[0] <= ms] or [1.0]) # the level the element is brought back to while paused+ horizon = min(nxt, ms + 12000)+ win = [s for s in E if ms <= s[0] <= horizon]+ tm = next((s for i, s in enumerate(win) if not s[3] and s[2] > ct0 + 0.03), None)+ d = dict(cmd="resume", ms=ms, line=no, el=el, own=own, ct_before=ct0, t_move_ms=(tm[0] - ms) if tm else None)+ if tm:+ silent = [s for s in win if s[4] <= 0.0015]+ d["t_silent_ms"] = (silent[0][0] - ms) if silent else None+ # media.rise sets the silence ~20-100 ms after the command; until then the element still has the level it+ # was restored to while paused (not heard: paused). From the first sample below half of it, up to the clock+ # moving, it must stay silent.+ setp = next((s for s in win if s[4] < 0.5 * own), None)+ d["t_rise_set_ms"] = (setp[0] - ms) if setp else None+ gate = [s for s in win if setp and setp[0] <= s[0] < tm[0] - 60]+ d["vol_max_before_move"] = max((s[4] for s in gate), default=None)+ d["vol_at_move"] = tm[4]+ # exact (event-stamped) view: volumechange events carry the element's own currentTime at the moment+ vc = [e for e in events if e[2] == el and e[1] == "volumechange" and ms <= e[0] <= horizon]+ sil = next((e for e in vc if e[4] <= 0.0015), None)+ up = next((e for e in vc if sil and e[0] > sil[0] and e[4] > 0.002), None)+ d["ev_silence_set_ms"] = (sil[0] - ms) if sil else None+ d["ev_silence_set_clock_ahead_s"] = round(sil[3] - ct0, 3) if sil else None+ d["ev_rise_first_ms"] = (up[0] - ms) if up else None+ d["ev_rise_first_clock_ahead_s"] = round(up[3] - ct0, 3) if up else None+ t0, rms = _fit_cubic(E, setp[0] if setp else tm[0] - 100, tm[0] + rise_ms + 200, own, lambda dt: min(1.0, max(0.0, dt / rise_ms)))+ d["fit_start_after_move_ms"] = None if t0 is None else t0 - tm[0]+ d["fit_rms"] = rms+ after = [s for s in E if tm[0] + 1000 <= s[0] <= min(horizon - 100, tm[0] + 6000) and not s[3]]+ lvl_end = sorted(s[4] for s in after)[len(after) // 2] if after else None+ d["level_after_median"] = lvl_end+ d["level_ratio_to_own"] = round(lvl_end / own, 3) if lvl_end and own else None+ full = next((s for s in E if s[0] >= tm[0] and s[4] >= 0.98 * own), None)+ d["to_full_after_move_ms"] = (full[0] - tm[0]) if full else None+ low = [s[4] for s in E if (full[0] if full else tm[0]) <= s[0] <= min(horizon - 100, tm[0] + 6000) and not s[3]]+ d["vol_min_after_full"] = min(low) if low else None+ d["ramp"] = [(s[0] - tm[0], s[4]) for s in E if tm[0] - 100 <= s[0] <= tm[0] + 700][::2]+ rises.append(d)+ return rises, pauses+++def crossfade_metrics(samples, bounds, traces, other, own=1.0):+ """Per natural song change: the element volume 12 s before to 6 s after the switch (every 500 ms), the longest span at+ volume < 0.1 / < 0.02 while the clock advances, silence (no clock progress) around the switch, the level 3-6 s after."""+ S = [s for s in samples if not s[7]]+ out = []+ xlines = [(o[0], o[3], o[2][:140]) for o in other if "crossfade" in o[2].lower()]+ for b in bounds:+ sw = b["eng_switch_ms"]+ rows = [s for s in S if sw - 12000 <= s[0] <= sw + 6000]+ if not rows:+ continue+ tl = []+ for t in range(-12000, 6001, 500):+ near = min(rows, key=lambda s: abs(s[0] - (sw + t)))+ tl.append((t, near[4], near[1], 0 if near[3] else 1))+ def longest(th):+ best = cur = 0+ start = None+ for a, c in zip(rows, rows[1:]):+ low = c[4] < th and not c[3]+ if low:+ start = start if start is not None else a[0]+ cur = c[0] - start+ best = max(best, cur)+ else:+ start = None+ return best+ aft = [s[4] for s in rows if sw + 3000 <= s[0] <= sw + 6000]+ pre = [s for s in rows if s[0] < sw - 6500]+ out.append(dict(switch_ms=sw, line=b["line"], from_title=b["from_title"], to_title=b["to_title"], audio_gap_ms=b.get("audio_gap_ms"),+ vol_before_fade=(pre[-1][4] if pre else None), longest_below_0_1_ms=longest(0.1), longest_below_0_02_ms=longest(0.02),+ vol_min_overall=min(s[4] for s in rows), level_3_6s_after_min=min(aft) if aft else None,+ timeline=tl, log=[x for x in xlines if sw - 14000 <= x[0] <= sw + 6000]))+ return out++def log_flags(other):pats = [("player stalled", r"player stalled"), ("reload", r"(?<![a-z])reload"), ("crossfade", r"crossfade"), ("volume", r"volume"),("ad", r"\bad (muted|stuck)|ad .*asked the page|blocked ad request|\"kind\":\"ad\""), ("http 429", r"http 429"), ("call timeout", r"timeout after \d+ ms"),@@ -321,13 +439,15 @@ def analyse(base, ref=1.0):bounds = natural_boundaries(traces, merged, samples, cmds)flags = log_flags(other)cm = command_metrics(samples, events, cmds, traces, ref)+ rises, pauses = fade_metrics(samples, events, cmds)+ xf = crossfade_metrics(samples, bounds, traces, other)# A silence of < 3 s at a song's own end is judged as a boundary (tools/pilot.py: limit 3 s), not as a stall.med = [e for e in med if not (e["kind"] == "silence_gap" and any(abs(e["ms"] - b.get("old_audio_end_ms", -10**12)) < 500 and (b.get("audio_gap_ms") or 0) < 3000 for b in bounds))]allev = sorted(ui + med, key=lambda e: e["ms"])counts = Counter((e["kind"], e["scope"]) for e in allev)return dict(base=base, trace_lines=len(traces), media_samples=len(samples), media_events=len(events), commands=[(c[0], c[1]) for c in cmds],counts={f"{k}/{s}": n for (k, s), n in sorted(counts.items())}, events=allev, gaps=gaps, boundaries=bounds, cmd_metrics=cm,- log_flags={k: len(v) for k, v in flags.items()}, log_flag_lines={k: v[:6] for k, v in flags.items()})+ rises=rises, pause_fades=pauses, crossfades=xf, log_flags={k: len(v) for k, v in flags.items()}, log_flag_lines={k: v[:6] for k, v in flags.items()})def summary(a, limit=12):