Skip to content

Native Android client for Spotify, built with Jetpack Compose

A player page Chromium never throttles, a resume that rises with the sound, playlists made private as in the official apps, fades between pages

kota-zo6b59b232a4f8
diff --git a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyLibrary.kt b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyLibrary.kt
index 00aaefaf..9cbb1438 100644
--- a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyLibrary.kt
+++ b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyLibrary.kt
@@ -226,10 +226,24 @@ class SpotifyPlaylists(private val gql: Gql, private val bridge: Bridge, private
override suspend fun access(uri: Uri): PlaylistAccess =
PlaylistAccess.of((bridge.service("PlaylistPermissionsAPI", "getBasePermission", JsonPrimitive(uri)) as? JsonPrimitive)?.content)
+ /**
+ * As the Web Player's "Make private": the playlist also leaves the profile (made private with
+ * the base permission alone, it stayed listed on the profile, unlike in the official apps).
+ * Made public again it is not put back on the profile, as there either ([setPublished]).
+ */
override suspend fun setAccess(uri: Uri, access: PlaylistAccess) {
+ if (access == PlaylistAccess.PRIVATE && published(uri)) setPublished(uri, false)
bridge.service("PlaylistPermissionsAPI", "setBasePermission", JsonPrimitive(uri), JsonPrimitive(access.permission))
}
+ /** The library's own "public" flag on the playlist: listed on the profile. */
+ override suspend fun published(uri: Uri): Boolean =
+ (bridge.service("RootlistAPI", "getPublishedState", JsonPrimitive(uri)) as? JsonPrimitive)?.content == "true"
+
+ override suspend fun setPublished(uri: Uri, published: Boolean) {
+ bridge.service("RootlistAPI", "setPublishedState", JsonPrimitive(uri), JsonPrimitive(published))
+ }
+
override suspend fun setCover(uri: Uri, jpeg: ByteArray?) {
bridge.call("playlist.setCover", json(mapOf("uri" to uri, "jpeg" to jpeg?.let { java.util.Base64.getEncoder().encodeToString(it) })) as kotlinx.serialization.json.JsonObject, timeoutMs = 60_000)
}
diff --git a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyPlayer.kt b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyPlayer.kt
index 1003923c..b59ea7e0 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
@@ -984,9 +984,49 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
bridge.logger?.invoke("pause: nothing plays, not sent")
return
}
- command("player.pause")
+ val level = lastMedia?.level?.takeIf { it > 0.01 }
+ val fadeOut = level != null && !_adPlaying.value && !adMuted && lastMedia?.active != false
+ if (fadeOut) {
+ fadeBack?.cancel()
+ runCatching { fade(PAUSE_STEPS.map { it * level!! }, ms = PAUSE_STEP_MS) }
+ delay(PAUSE_STEPS.size * PAUSE_STEP_MS)
+ }
+ try {
+ command("player.pause")
+ } finally {
+ // The element back at its level while paused (not heard): a new song started next
+ // must not begin at the bottom of the fade.
+ if (fadeOut) runCatching { fade(listOf(level!!), restore = true, ms = 1) }
+ }
+ }
+ /*
+ * 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.
+ */
+ override suspend fun resume() {
+ pausedByUser = false
+ val quiet = _adPlaying.value || adMuted || crossfadeArmed || _state.value?.isPaused == false || lastMedia?.active == false
+ if (quiet) { command("player.resume"); return }
+ fadeBackTo = lastMedia?.own?.takeIf { it > 0.01 } ?: 1.0
+ fadeBack?.cancel()
+ runCatching {
+ bridge.call("media.rise", buildJsonObject { put("from", RISE_FROM); put("ms", RISE_MS); put("wait", RISE_WAIT_MS) },
+ timeoutMs = LEVEL_TIMEOUT_MS, quiet = true)
+ }
+ try {
+ command("player.resume")
+ } catch (e: Throwable) {
+ runCatching { restoreLevel() }
+ fadeBackTo = null
+ throw e
+ }
+ fadeBack = scope.launch {
+ try { delay(RISE_WAIT_MS + RISE_MS + 200) } finally { fadeBackTo = null }
+ }
}
- override suspend fun resume() { pausedByUser = false; command("player.resume") }
override suspend fun seek(positionMs: Long) { endCrossfade(restore = true); command("player.seek", buildJsonObject { put("positionMs", positionMs) }) }
override suspend fun next() {
pausedByUser = false
@@ -1214,6 +1254,15 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
const 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
+ /** 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 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.js
index 113b7537..d7f11449 100644
--- a/base/api-spotify/src/main/resources/bridge/player-bridge.js
+++ b/base/api-spotify/src/main/resources/bridge/player-bridge.js
@@ -425,8 +425,53 @@
// A ramp replaces the one before it (a crossfade's up-ramp must not be pulled back down
// by steps still pending from its down-ramp).
cancelFade();
- fadeTimers = steps.map((v, i) => setTimeout(() => set(v), i * per));
- if (a.restore) fadeTimers.push(setTimeout(() => { el.volume = ownLevel(player); }, steps.length * per));
+ // Each tick sets the step the clock is at, not the next one in line: a late timer (a busy
+ // or throttled page) lands on the right level instead of stretching the ramp.
+ const t0 = performance.now();
+ const tick = () => {
+ const i = Math.floor((performance.now() - t0) / per);
+ if (i >= steps.length) { if (a.restore) el.volume = ownLevel(player); else if (steps.length) set(steps[steps.length - 1]); return; }
+ set(steps[i]);
+ fadeTimers.push(setTimeout(tick, per - ((performance.now() - t0) % per)));
+ };
+ tick();
+ 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
+ '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;
+ const waitSound = () => {
+ if (!el.paused && el.currentTime > at + 0.01) rise();
+ else fadeTimers.push(setTimeout(waitSound, 16));
+ };
+ fadeTimers.push(setTimeout(() => { cancelFade(); el.volume = ownLevel(player); }, Math.max(500, Number(a.wait) || 3000)));
+ waitSound();
return true;
},
diff --git a/base/api/src/main/kotlin/app/myspoti/api/Api.kt b/base/api/src/main/kotlin/app/myspoti/api/Api.kt
index 8cf32129..f7ea85e9 100644
--- a/base/api/src/main/kotlin/app/myspoti/api/Api.kt
+++ b/base/api/src/main/kotlin/app/myspoti/api/Api.kt
@@ -139,6 +139,9 @@ interface Playlists {
/** Who may see or change the playlist (owner only). */
suspend fun access(uri: Uri): PlaylistAccess
suspend fun setAccess(uri: Uri, access: PlaylistAccess)
+ /** Shown on the user's profile (the official "Add to profile"); a private playlist never is. */
+ suspend fun published(uri: Uri): Boolean
+ suspend fun setPublished(uri: Uri, published: Boolean)
/** Public playlists show on the profile and in search; private ones only to the owner. */
suspend fun setPublic(uri: Uri, public: Boolean) = setAccess(uri, if (public) PlaylistAccess.PUBLIC else PlaylistAccess.PRIVATE)
/** Collaborative playlists let other users add and remove tracks (owner only). */
diff --git a/base/app/build.gradle.kts b/base/app/build.gradle.kts
index 51c2d5ce..77e06d7a 100644
--- a/base/app/build.gradle.kts
+++ b/base/app/build.gradle.kts
@@ -78,6 +78,12 @@ android {
// Real key when provided (CI releases); otherwise the debug key, so a local
// release build installs over the debug one while testing.
signingConfig = signingConfigs.getByName(if (hasReleaseKey) "release" else "debug")
+ // -PoverDev: the optimised build under the dev app's id, to measure the speed of a
+ // beta on the test phone without replacing the signed beta installed there.
+ if (findProperty("overDev") != null) {
+ applicationIdSuffix = ".dev"
+ manifestPlaceholders["appLabel"] = "Myspoti dev"
+ }
isMinifyEnabled = true
isShrinkResources = true
proguardFiles(
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.kt
index 1cc4b052..40572c56 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
@@ -14,6 +14,9 @@ import kotlinx.serialization.json.jsonObject
* cmd: play (--es track <uri> --es context <uri>), resume, pause, next, previous, seek (--el ms <n>).
* cmd: screenon (--ez on false to release) holds the screen on for a long run: One UI does not
* honour the huge `screen_off_timeout` set over adb, the window flag does.
+ * 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: 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.
@@ -43,6 +46,24 @@ class TestControlReceiver : BroadcastReceiver() {
// The player's own "next" button and the mini player's swipe.
"swipenext" -> SongPlayer.swipeNext()
"previous" -> SongPlayer.previous()
+ "uitrace" -> {
+ val secs = intent.getIntExtra("secs", 30).coerceIn(1, 600)
+ app.myspoti.host.android.MyspotiRuntime.scope.launch(kotlinx.coroutines.Dispatchers.Main) {
+ val song = Graph.currentSongState
+ val end = android.os.SystemClock.elapsedRealtime() + secs * 1000L
+ while (android.os.SystemClock.elapsedRealtime() < end) {
+ val now = System.currentTimeMillis()
+ val e = app.myspoti.host.android.MyspotiRuntime.spotify.player.state.value
+ Log.i("MspTrace", "t=${android.os.SystemClock.elapsedRealtime()} ui_pos=${SongPlayer.getCurrentPosition()} " +
+ "ui_dur=${SongPlayer.getDuration()} ui_play=${SongPlayer.isPlaying()} ui_uri=${SongPlayer.nowPlaying.value.uri} " +
+ "ui_cover=${song.coverUri.value.substringAfterLast('/')} eng_uri=${e?.item?.uri} " +
+ "eng_pos=${e?.positionAt(now)} eng_paused=${e?.isPaused} eng_buf=${e?.isBuffering} " +
+ "ui_title=${song.title.value} | eng_title=${e?.item?.name}")
+ kotlinx.coroutines.delay(200)
+ }
+ Log.i("MspTrace", "end")
+ }
+ }
"seek" -> SongPlayer.seekTo(intent.getLongExtra("ms", 0L))
"screenon" -> context.getSharedPreferences("myspoti_prefs", Context.MODE_PRIVATE)
.edit().putBoolean("keep_screen_on", intent.getBooleanExtra("on", true)).apply()
diff --git a/base/app/src/main/java/com/music/spotui/ui/components/AppComponents.kt b/base/app/src/main/java/com/music/spotui/ui/components/AppComponents.kt
index 49ad3537..6f41891d 100644
--- a/base/app/src/main/java/com/music/spotui/ui/components/AppComponents.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/components/AppComponents.kt
@@ -163,6 +163,15 @@ fun MiniPlayer(navController: NavHostController) {
}
}
+ // The big cover the player will open on, loaded now: the cover that flies into the player
+ // (CoverFlight) and the player's own then come from memory, with nothing to wait for.
+ LaunchedEffect(songCoverUri) {
+ val target = CoverFlight.player ?: return@LaunchedEffect
+ if (songCoverUri.isBlank()) return@LaunchedEffect
+ com.bumptech.glide.Glide.with(context).load(songCoverUri)
+ .override(target.width.toInt(), target.height.toInt()).optionalCenterCrop().preload()
+ }
+
// A new song cross-fades the card's colour instead of snapping to it.
val animatedTint by androidx.compose.animation.animateColorAsState(tint, androidx.compose.animation.core.tween(400), label = "miniTint")
@@ -218,6 +227,16 @@ fun MiniPlayer(navController: NavHostController) {
// T4: during an ad break the page publishes no track, so the song before it
// would sit in the mini player; an explicit ad state is shown instead.
val adPlaying = com.music.spotui.di.SongPlayer.adPlaying
+ // A song change that is no swipe (the end of a song, a skip from the player or
+ // the notification) crossfades instead of swapping in one frame. After a swipe the
+ // new song is already on screen (the page swiped to): no fade then, or the page
+ // jumped back to would show the old song fading out.
+ val shown = MiniSong(s?.title ?: songTitle, s?.singer ?: songSinger, s?.coverUri ?: songCoverUri)
+ androidx.compose.animation.Crossfade(
+ targetState = shown,
+ animationSpec = androidx.compose.animation.core.tween(if (page == 1 && pager.currentPage == 1) 220 else 0),
+ label = "miniSong",
+ ) { m ->
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
GlideImage(
transition = CrossFade,
@@ -225,12 +244,12 @@ fun MiniPlayer(navController: NavHostController) {
.size(40.dp)
// The current song's cover is where the player's cover flies from
// and back to (CoverFlight), and is hidden while it flies.
- .then(if (s == null) Modifier
+ .then(if (page == 1) Modifier
.onGloballyPositioned { CoverFlight.mini = it.boundsInWindow() }
- .graphicsLayer { alpha = if (CoverFlight.flying) 0f else 1f }
+ .graphicsLayer { alpha = CoverFlight.miniCoverAlpha() }
else Modifier)
.clip(RoundedCornerShape(4.dp)),
- model = s?.coverUri ?: songCoverUri,
+ model = m.cover,
contentScale = ContentScale.Crop,
failure = placeholder(R.drawable.placeholder),
loading = placeholder(R.drawable.placeholder),
@@ -239,11 +258,11 @@ fun MiniPlayer(navController: NavHostController) {
val remote = SongPlayer.activeDevice.value
Column(modifier = Modifier.padding(start = 12.dp, end = 8.dp)) {
if (remote == null) {
- Text(text = if (adPlaying) stringResource(R.string.ad_playing) else (s?.title ?: songTitle), color = Color.White, fontSize = 13.sp, fontWeight = FontWeight.Bold, maxLines = 1, overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis)
+ Text(text = if (adPlaying) stringResource(R.string.ad_playing) else (m.title), color = Color.White, fontSize = 13.sp, fontWeight = FontWeight.Bold, maxLines = 1, overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis)
if (!adPlaying) Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
// The artist yields the width: the output's name stays whole.
Text(
- text = s?.singer ?: songSinger, color = Color.White.copy(alpha = 0.7f), fontSize = 13.sp,
+ text = m.singer, color = Color.White.copy(alpha = 0.7f), fontSize = 13.sp,
maxLines = 1, overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis,
modifier = Modifier.weight(1f, fill = false),
)
@@ -266,10 +285,10 @@ fun MiniPlayer(navController: NavHostController) {
Text(
text = androidx.compose.ui.text.buildAnnotatedString {
pushStyle(androidx.compose.ui.text.SpanStyle(fontWeight = FontWeight.Bold, color = Color.White))
- append(s?.title ?: songTitle)
+ append(m.title)
pop()
pushStyle(androidx.compose.ui.text.SpanStyle(color = Color.White.copy(alpha = 0.7f)))
- append(" • " + (s?.singer ?: songSinger))
+ append(" • " + (m.singer))
pop()
},
fontSize = 13.sp, maxLines = 1, overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis, softWrap = false,
@@ -284,6 +303,7 @@ fun MiniPlayer(navController: NavHostController) {
}
}
}
+ }
}
Icon(
painter = painterResource(id = if (SongPlayer.activeDevice.value != null) R.drawable.ic_devices else R.drawable.ic_devices),
@@ -382,3 +402,6 @@ fun Snackbar(showMessage : String) {
}
}
+
+/** What the mini player shows of a song: the crossfade's key, so the old one fades with its own text. */
+private data class MiniSong(val title: String, val singer: String, val cover: String)
diff --git a/base/app/src/main/java/com/music/spotui/ui/components/CoverFlight.kt b/base/app/src/main/java/com/music/spotui/ui/components/CoverFlight.kt
index 1174772d..10da1ed4 100644
--- a/base/app/src/main/java/com/music/spotui/ui/components/CoverFlight.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/components/CoverFlight.kt
@@ -32,17 +32,54 @@ object CoverFlight {
var mini by mutableStateOf<Rect?>(null)
/** The full player's cover once it is open, in window pixels; null when it shows none (Canvas, video, immersive). */
var player by mutableStateOf<Rect?>(null)
+ /**
+ * Where the sheet is (0 .. 1) while it moves, null when still: set by the sheet, read
+ * straight from its transition in draw lambdas. Published by an effect it came one frame
+ * late, and that first frame showed the real covers and the flying one at once (a flash).
+ */
+ var progressSource: () -> Float? = { null }
/** 0 (mini player) .. 1 (full player) while the player opens or closes; null otherwise. */
- var progress by mutableStateOf<Float?>(null)
+ val progress: Float? get() = progressSource()?.takeIf { mini != null && player != null }
/**
* How far down the sliding player is drawn right now (px), set by the player sheet: the
* player's cover is measured on the first frame of its opening, its slide taken back out,
* so the very first opening already knows where the cover lands.
*/
var sheetOffsetPx: () -> Float = { 0f }
+ /**
+ * The sliding player's own layout: the cover is measured against it, so its target does not
+ * move while the sheet slides (measured against the window it was re-measured every frame,
+ * a frame off the slide, and the flying cover visibly jumped in size on the way).
+ */
+ var sheetCoords: androidx.compose.ui.layout.LayoutCoordinates? = null
+ /**
+ * How far the user's finger has pulled the player down (px), set by the player. A player
+ * closed by that pull leaves with its cover, as in the official app: no flight then (the
+ * flight started from where the cover would be without the pull, and a cover detached from
+ * the sliding player showed above it — captured frame by frame on the test phone).
+ */
+ var pulledPx: () -> Float = { 0f }
/** Read in a draw-phase lambda: hides a real cover while its stand-in flies. */
val flying: Boolean get() = progress != null
+
+ // Cross-fades at both ends of the flight (the owner's call: hard cuts between the real
+ // covers and the flying one read as the motion being out of step). Over the last 20 % the
+ // player's cover fades in as the flying one fades out, and over the first 20 % the same with
+ // the mini player's; each reads [progress] in a draw lambda.
+ private const val BLEND = 0.2f
+ /** Opacity of the full player's own cover. */
+ fun playerCoverAlpha(): Float = progress?.let { ((it - (1f - BLEND)) / BLEND).coerceIn(0f, 1f) } ?: 1f
+ /** Opacity of the mini player's own cover. */
+ fun miniCoverAlpha(): Float = progress?.let { ((BLEND - it) / BLEND).coerceIn(0f, 1f) } ?: 1f
+ /** Opacity of the flying cover. */
+ fun flyingAlpha(): Float = progress?.let { 1f - maxOf(playerCoverAlpha(), miniCoverAlpha()) } ?: 0f
+ /**
+ * Opacity of the player's background and controls while it slides: they fade in over the
+ * first 60 % of the opening and out over the last 60 % of the closing, so the sheet never
+ * arrives or leaves as a hard block.
+ */
+ fun sheetAlpha(p: Float): Float = (p / 0.6f).coerceIn(0f, 1f)
}
/**
@@ -63,7 +100,7 @@ fun FlyingCover(coverUri: String, slideOffsetPx: () -> Float) {
.graphicsLayer {
val p = CoverFlight.progress
if (p == null) { alpha = 0f; return@graphicsLayer }
- alpha = 1f
+ alpha = CoverFlight.flyingAlpha()
transformOrigin = TransformOrigin(0f, 0f)
val left = from.left + (to.left - from.left) * p
val top = from.top + (to.top - from.top) * p
@@ -75,11 +112,18 @@ fun FlyingCover(coverUri: String, slideOffsetPx: () -> Float) {
}
.clip(RoundedCornerShape(8.dp)),
) {
+ val context = androidx.compose.ui.platform.LocalContext.current
GlideImage(
model = coverUri,
contentDescription = null,
contentScale = ContentScale.Crop,
modifier = Modifier.size(with(density) { to.width.toDp() }, with(density) { to.height.toDp() }),
+ // The mini player's own small picture (already in memory) until the big one is
+ // there: a cover that had to load first left an empty square flying (a flash).
+ requestBuilderTransform = {
+ it.thumbnail(com.bumptech.glide.Glide.with(context).load(coverUri)
+ .override(from.width.toInt().coerceAtLeast(1), from.height.toInt().coerceAtLeast(1)).optionalCenterCrop())
+ },
)
}
}
diff --git a/base/app/src/main/java/com/music/spotui/ui/components/PlaylistOptionsSheet.kt b/base/app/src/main/java/com/music/spotui/ui/components/PlaylistOptionsSheet.kt
index 039db9c9..dc4ad8b5 100644
--- a/base/app/src/main/java/com/music/spotui/ui/components/PlaylistOptionsSheet.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/components/PlaylistOptionsSheet.kt
@@ -85,13 +85,24 @@ fun PlaylistOptionsSheet(
) {
val context = LocalContext.current
val scope = rememberCoroutineScope()
- LaunchedEffect(Unit) { com.music.spotui.data.api.ProfileCache.ensure(context) }
- val mine = com.music.spotui.data.api.ProfileCache.id?.let { page.ownerUri == "spotify:user:$it" } == true
+ fun isMine() = com.music.spotui.data.api.ProfileCache.id?.let { page.ownerUri == "spotify:user:$it" } == true
+ // The profile id is fetched once per session and is no Compose state: read again until it
+ // is there (opened before it was, the sheet never showed the owner's options at all).
+ var mine by remember { mutableStateOf(isMine()) }
+ LaunchedEffect(Unit) {
+ com.music.spotui.data.api.ProfileCache.ensure(context)
+ kotlinx.coroutines.withTimeoutOrNull(5_000) { while (com.music.spotui.data.api.ProfileCache.id == null) kotlinx.coroutines.delay(100) }
+ mine = isMine()
+ }
var access by remember { mutableStateOf<PlaylistAccess?>(null) }
+ var published by remember { mutableStateOf<Boolean?>(null) }
var editing by remember { mutableStateOf(false) }
var deleting by remember { mutableStateOf(false) }
LaunchedEffect(page.uri, mine) {
- if (mine) access = runCatching { MyspotiRuntime.api.playlists.access(page.uri) }.getOrNull()
+ if (mine) {
+ access = runCatching { MyspotiRuntime.api.playlists.access(page.uri) }.getOrNull()
+ published = runCatching { MyspotiRuntime.api.playlists.published(page.uri) }.getOrNull()
+ }
}
// Taps are sent one at a time, in order; a refused one puts back what Spotify really has.
@@ -99,12 +110,30 @@ fun PlaylistOptionsSheet(
fun setAccess(target: PlaylistAccess) {
if (access == target) return
access = target
+ // Made private, it leaves the profile too (as in the official apps).
+ if (target == PlaylistAccess.PRIVATE) published = false
scope.launch {
accessWrites.withLock {
runCatching { MyspotiRuntime.api.playlists.setAccess(page.uri, target) }
.onSuccess { onChanged() }
.onFailure {
access = runCatching { MyspotiRuntime.api.playlists.access(page.uri) }.getOrNull()
+ published = runCatching { MyspotiRuntime.api.playlists.published(page.uri) }.getOrNull()
+ android.widget.Toast.makeText(context, R.string.playlist_change_refused, android.widget.Toast.LENGTH_SHORT).show()
+ }
+ }
+ }
+ }
+
+ fun setPublished(on: Boolean) {
+ if (published == on) return
+ published = on
+ scope.launch {
+ accessWrites.withLock {
+ runCatching { MyspotiRuntime.api.playlists.setPublished(page.uri, on) }
+ .onSuccess { onChanged() }
+ .onFailure {
+ published = runCatching { MyspotiRuntime.api.playlists.published(page.uri) }.getOrNull()
android.widget.Toast.makeText(context, R.string.playlist_change_refused, android.widget.Toast.LENGTH_SHORT).show()
}
}
@@ -134,6 +163,10 @@ fun PlaylistOptionsSheet(
AccessRow(Icons.Outlined.Group, R.string.playlist_access_collaborative, R.string.playlist_access_collaborative_detail, access == PlaylistAccess.COLLABORATIVE) {
setAccess(PlaylistAccess.COLLABORATIVE)
}
+ // Only a playlist others may see can be listed on the profile.
+ if (access != null && access != PlaylistAccess.PRIVATE && published != null) {
+ ProfileRow(published == true) { setPublished(it) }
+ }
Spacer(Modifier.height(8.dp))
OptionRow(Icons.Outlined.Delete, stringResource(R.string.local_delete_playlist)) { deleting = true }
} else if (page.ownerUri.startsWith("spotify:user:")) {
@@ -271,6 +304,25 @@ private fun OptionRow(icon: ImageVector, label: String, onClick: () -> Unit) {
}
}
+@Composable
+private fun ProfileRow(on: Boolean, onChange: (Boolean) -> Unit) {
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ modifier = Modifier.fillMaxWidth().clickable { onChange(!on) }.padding(horizontal = 20.dp, vertical = 10.dp),
+ ) {
+ Icon(Icons.Outlined.Person, null, tint = Color.White, modifier = Modifier.size(24.dp))
+ Spacer(Modifier.width(16.dp))
+ Column(Modifier.weight(1f)) {
+ Text(stringResource(R.string.playlist_on_profile), color = Color.White, fontSize = 16.sp)
+ Text(stringResource(R.string.playlist_on_profile_detail), color = Color(0xFFB3B3B3), fontSize = 13.sp)
+ }
+ androidx.compose.material3.Switch(
+ checked = on, onCheckedChange = onChange,
+ colors = androidx.compose.material3.SwitchDefaults.colors(checkedTrackColor = AppAccent, checkedThumbColor = Color.Black),
+ )
+ }
+}
+
@Composable
private fun AccessRow(icon: ImageVector, label: Int, detail: Int, selected: Boolean, onClick: () -> Unit) {
Row(
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.kt
index ab619988..adc015d0 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
@@ -377,32 +377,50 @@ private fun NavBackStackEntry.isSheet() = destination.route in sheetRoutes
internal val Decelerate = CubicBezierEasing(0.05f, 0.7f, 0.1f, 1f)
internal val Accelerate = CubicBezierEasing(0.3f, 0f, 0.8f, 0.15f)
private const val PAGE_MS = 300
+private const val TAB_MS = 150
internal const val SHEET_IN_MS = 340
internal const val SHEET_OUT_MS = 240
+// Pages: Material's shared axis with a fade-through. The page leaving fades out over the first
+// 90 ms while it moves a step aside; the page coming in moves the same short step and fades in
+// over the rest. Two opaque pages sliding across the whole screen (as before) read as a heavy
+// block with a hard edge running over the content; a short shift and a fade at the hand-over
+// read as the official apps' quick page change. Tabs: the new one fades in, nothing moves.
+private const val SHIFT = 0.08f
+private const val FADE_OUT_MS = 90
+private val Standard = CubicBezierEasing(0.2f, 0f, 0f, 1f)
+
+private fun pageIn(fromRight: Boolean): EnterTransition =
+ slideInHorizontally(tween(PAGE_MS, easing = Standard)) { (it * SHIFT).toInt() * if (fromRight) 1 else -1 } +
+ fadeIn(tween(PAGE_MS - FADE_OUT_MS, delayMillis = FADE_OUT_MS, easing = Decelerate))
+
+private fun pageOut(toLeft: Boolean): ExitTransition =
+ slideOutHorizontally(tween(PAGE_MS, easing = Standard)) { (it * SHIFT).toInt() * if (toLeft) -1 else 1 } +
+ fadeOut(tween(FADE_OUT_MS, easing = Accelerate))
+
private fun navEnter(from: NavBackStackEntry, to: NavBackStackEntry): EnterTransition = when {
- isTabSwitch(from, to) -> EnterTransition.None
+ isTabSwitch(from, to) -> fadeIn(tween(TAB_MS, easing = Decelerate))
to.isSheet() -> slideInVertically(tween(SHEET_IN_MS, easing = Decelerate)) { it }
- else -> slideInHorizontally(tween(PAGE_MS, easing = Decelerate)) { it }
+ else -> pageIn(fromRight = true)
}
private fun navExit(from: NavBackStackEntry, to: NavBackStackEntry): ExitTransition = when {
isTabSwitch(from, to) -> ExitTransition.None
// The page stays still under the rising sheet until it covers it.
to.isSheet() -> fadeOut(tween(durationMillis = 1, delayMillis = SHEET_IN_MS))
- else -> slideOutHorizontally(tween(PAGE_MS, easing = Decelerate)) { -it / 4 }
+ else -> pageOut(toLeft = true)
}
private fun navPopEnter(from: NavBackStackEntry, to: NavBackStackEntry): EnterTransition = when {
- isTabSwitch(from, to) -> EnterTransition.None
+ isTabSwitch(from, to) -> fadeIn(tween(TAB_MS, easing = Decelerate))
from.isSheet() -> EnterTransition.None
- else -> slideInHorizontally(tween(PAGE_MS, easing = Decelerate)) { -it / 4 }
+ else -> pageIn(fromRight = false)
}
private fun navPopExit(from: NavBackStackEntry, to: NavBackStackEntry): ExitTransition = when {
isTabSwitch(from, to) -> ExitTransition.None
from.isSheet() -> slideOutVertically(tween(SHEET_OUT_MS, easing = Accelerate)) { it }
- else -> slideOutHorizontally(tween(PAGE_MS, easing = Decelerate)) { it }
+ else -> pageOut(toLeft = false)
}
/** A destination on an opaque background, so sliding pages never show through each other. */
diff --git a/base/app/src/main/java/com/music/spotui/ui/navigation/PlayerSheet.kt b/base/app/src/main/java/com/music/spotui/ui/navigation/PlayerSheet.kt
index 9bd1fe47..69d6c0ce 100644
--- a/base/app/src/main/java/com/music/spotui/ui/navigation/PlayerSheet.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/navigation/PlayerSheet.kt
@@ -9,9 +9,10 @@ import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.setValue
-import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.onSizeChanged
+import androidx.compose.ui.graphics.graphicsLayer
+import androidx.compose.ui.layout.onGloballyPositioned
import com.music.spotui.ui.components.CoverFlight
import com.music.spotui.ui.components.FlyingCover
import androidx.compose.animation.core.tween
@@ -62,14 +63,25 @@ fun PlayerOverlay(navController: NavController) {
},
label = "sheet",
) { if (it == EnterExitState.Visible) 1f else 0f }
- LaunchedEffect(transition) {
- snapshotFlow { if (transition.currentState != transition.targetState) sheet.value else null }
- .collect { CoverFlight.progress = it?.takeIf { CoverFlight.mini != null && CoverFlight.player != null } }
+ // Closing after a pull: the player goes down with its cover, no flight.
+ val closedByPull = remember(transition.targetState) {
+ transition.targetState != EnterExitState.Visible && CoverFlight.pulledPx() > 1f
}
- androidx.compose.runtime.DisposableEffect(Unit) { onDispose { CoverFlight.progress = null } }
+ androidx.compose.runtime.SideEffect {
+ CoverFlight.progressSource = {
+ if (transition.currentState != transition.targetState && !closedByPull) sheet.value else null
+ }
+ }
+ androidx.compose.runtime.DisposableEffect(Unit) { onDispose { CoverFlight.progressSource = { null } } }
var heightPx by remember { mutableIntStateOf(0) }
androidx.compose.runtime.SideEffect { CoverFlight.sheetOffsetPx = { (1f - sheet.value) * heightPx } }
- Box(Modifier.fillMaxSize().onSizeChanged { heightPx = it.height }) {
+ Box(Modifier.fillMaxSize().onSizeChanged { heightPx = it.height }
+ .onGloballyPositioned { CoverFlight.sheetCoords = it }) {
+ // The player fades with its slide (see CoverFlight.sheetAlpha); a full layer alpha only
+ // while it moves, so the open player draws without an offscreen buffer.
+ Box(Modifier.fillMaxSize().graphicsLayer {
+ alpha = if (transition.currentState != transition.targetState) CoverFlight.sheetAlpha(sheet.value) else 1f
+ }) {
CompositionLocalProvider(LocalPageSettled provides settled) {
// A podcast episode gets the podcast player (±15 s, speed, sleep timer, no shuffle);
// everything else keeps the music player.
@@ -79,6 +91,7 @@ fun PlayerOverlay(navController: NavController) {
PlayerScreen(navController)
}
}
+ }
if (!com.music.spotui.di.SongPlayer.isEpisode) FlyingCover(
coverUri = com.music.spotui.di.Graph.currentSongState.coverUri.value,
slideOffsetPx = { (1f - sheet.value) * heightPx },
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/PlayerScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/PlayerScreen.kt
index ed323a16..694871c9 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
@@ -316,6 +316,7 @@ fun PlayerScreen(navController: NavController) {
LaunchedEffect(mv.state.value, remote, audioBuffering, displayedTrackId) { if (videoReady && !audioBuffering) mv.warm() }
// Pulled down from the top, the player closes, like the back button (issue #4).
val pullToClose = com.music.spotui.ui.components.rememberPullToDismiss { com.music.spotui.ui.navigation.PlayerSheet.close() }
+ androidx.compose.runtime.SideEffect { com.music.spotui.ui.components.CoverFlight.pulledPx = { pullToClose.offset } }
pullToClose.enabled = !showLyrics && !mv.fullscreen.value
Box(
modifier = Modifier
@@ -463,11 +464,14 @@ fun PlayerScreen(navController: NavController) {
// slide taken out, only for the plain cover of the current song.
.then(if (page == 1) Modifier.onGloballyPositioned {
val flight = com.music.spotui.ui.components.CoverFlight
+ val sheet = flight.sheetCoords?.takeIf { s -> s.isAttached }
+ // Against the sheet, which sits at the window's top once open: the
+ // same rect on every frame of the slide (an equal Rect notifies no one).
flight.player = if (immersive || coverAlpha < 1f) null
- else it.boundsInWindow().translate(0f, -flight.sheetOffsetPx())
+ else sheet?.localBoundingBoxOf(it, clipBounds = false) ?: it.boundsInWindow()
} else Modifier)
.graphicsLayer {
- alpha = coverAlpha * (if (page == 1 && com.music.spotui.ui.components.CoverFlight.flying) 0f else 1f)
+ alpha = coverAlpha * (if (page == 1) com.music.spotui.ui.components.CoverFlight.playerCoverAlpha() else 1f)
val grow = 1f + (1f - coverAlpha) * 0.06f
scaleX = grow; scaleY = grow
},
@@ -918,7 +922,17 @@ fun PlayerInfo(
.fillMaxWidth()
.padding(horizontal = 24.dp)
) {
- Column(modifier = Modifier.weight(1f).padding(end = 16.dp)) {
+ // A new song's title and artist fade in (over 0.2 s) instead of replacing the old ones
+ // in one frame, while its cover slides in above them.
+ val textAlpha = remember { androidx.compose.animation.core.Animatable(1f) }
+ var shownTitle by remember { mutableStateOf(songTitle) }
+ LaunchedEffect(songTitle) {
+ if (songTitle == shownTitle) return@LaunchedEffect
+ shownTitle = songTitle
+ textAlpha.snapTo(0f)
+ textAlpha.animateTo(1f, androidx.compose.animation.core.tween(200))
+ }
+ Column(modifier = Modifier.weight(1f).padding(end = 16.dp).graphicsLayer { alpha = textAlpha.value }) {
Text(
modifier = Modifier
// A few passes, after the sheet has settled (not an endless 120 Hz animation).
diff --git a/base/app/src/main/res/values-de/myspoti_strings.xml b/base/app/src/main/res/values-de/myspoti_strings.xml
index 7dcec7f7..5a9ae76f 100644
--- a/base/app/src/main/res/values-de/myspoti_strings.xml
+++ b/base/app/src/main/res/values-de/myspoti_strings.xml
@@ -271,6 +271,8 @@
<string name="playlist_access_private_detail">Nur du kannst sie sehen</string>
<string name="playlist_access_collaborative">Gemeinsam</string>
<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="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.xml
index e9bc558e..564536c3 100644
--- a/base/app/src/main/res/values-el/myspoti_strings.xml
+++ b/base/app/src/main/res/values-el/myspoti_strings.xml
@@ -271,6 +271,8 @@
<string name="playlist_access_private_detail">Μόνο εσύ μπορείς να τη δεις</string>
<string name="playlist_access_collaborative">Συνεργατική</string>
<string name="playlist_access_collaborative_detail">Όποιος έχει τον σύνδεσμο μπορεί να προσθέτει και να αφαιρεί τραγούδια</string>
+ <string name="playlist_on_profile">Στο προφίλ σου</string>
+ <string name="playlist_on_profile_detail">Εμφανίζεται στο προφίλ σου για τους άλλους</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.xml
index cec0b6c5..62616b40 100644
--- a/base/app/src/main/res/values-es/myspoti_strings.xml
+++ b/base/app/src/main/res/values-es/myspoti_strings.xml
@@ -271,6 +271,8 @@
<string name="playlist_access_private_detail">Solo tú puedes verla</string>
<string name="playlist_access_collaborative">Colaborativa</string>
<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="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.xml
index 908bba76..7c67e7bc 100644
--- a/base/app/src/main/res/values-fr/myspoti_strings.xml
+++ b/base/app/src/main/res/values-fr/myspoti_strings.xml
@@ -311,6 +311,8 @@
<string name="playlist_access_private_detail">Vous seul pouvez la voir</string>
<string name="playlist_access_collaborative">Collaborative</string>
<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="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.xml
index b0f65ce3..c687cc2b 100644
--- a/base/app/src/main/res/values-it/myspoti_strings.xml
+++ b/base/app/src/main/res/values-it/myspoti_strings.xml
@@ -271,6 +271,8 @@
<string name="playlist_access_private_detail">Solo tu puoi vederla</string>
<string name="playlist_access_collaborative">Collaborativa</string>
<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="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.xml
index 3fedfb5d..ec0cc440 100644
--- a/base/app/src/main/res/values-pt/myspoti_strings.xml
+++ b/base/app/src/main/res/values-pt/myspoti_strings.xml
@@ -271,6 +271,8 @@
<string name="playlist_access_private_detail">Só tu a podes ver</string>
<string name="playlist_access_collaborative">Colaborativa</string>
<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="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.xml
index f0e00407..ccdd3dfd 100644
--- a/base/app/src/main/res/values/myspoti_strings.xml
+++ b/base/app/src/main/res/values/myspoti_strings.xml
@@ -311,6 +311,8 @@
<string name="playlist_access_private_detail">Only you can see it</string>
<string name="playlist_access_collaborative">Collaborative</string>
<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="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/base/host-android/src/main/kotlin/app/myspoti/host/android/WebPlayerHost.kt b/base/host-android/src/main/kotlin/app/myspoti/host/android/WebPlayerHost.kt
index 18eb6145..3902ef58 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
@@ -114,7 +114,7 @@ class WebPlayerHost(private val context: Context) : BridgeHost {
* [onRenderProcessGone] returns false (see [rebuild]).
*/
@SuppressLint("SetJavaScriptEnabled")
- private fun createView(): WebView = WebView(context.applicationContext).apply {
+ private fun createView(): WebView = AwakeWebView(context.applicationContext).apply {
settings.apply {
javaScriptEnabled = true
domStorageEnabled = true
@@ -436,3 +436,22 @@ class WebPlayerHost(private val context: Context) : BridgeHost {
const val LOGIN_URL = "https://accounts.spotify.com/login?continue=https%3A%2F%2Fopen.spotify.com%2F"
}
}
+
+/**
+ * The engine's WebView, never hidden as far as Chromium knows. A page Chromium sees hidden has
+ * its timers held to one wake-up a second, then to one a minute once it has been hidden five
+ * minutes without sound (measured on the test phone, app in the background: eight 38 ms steps
+ * took 7.8 s). Everything the page does on a timer waited on that: the fades (a song resumed
+ * after a pause stayed nearly silent for seconds), Spotify's own hand-over at the end of a song,
+ * and the work behind a command sent after a long pause.
+ *
+ * Only Chromium is told: the framework still sees the view's real visibility, so a hidden page
+ * is never drawn (see [WebPlayerHost.attach]). Chromium reads the view's visibility through
+ * [getVisibility], and the window's through [getWindowVisibility] when the view is set up and
+ * [onWindowVisibilityChanged] afterwards (the callback alone left the page hidden).
+ */
+private class AwakeWebView(context: Context) : WebView(context) {
+ override fun getVisibility(): Int = View.VISIBLE
+ override fun getWindowVisibility(): Int = View.VISIBLE
+ override fun onWindowVisibilityChanged(visibility: Int) = super.onWindowVisibilityChanged(View.VISIBLE)
+}
diff --git a/tools/pilot.py b/tools/pilot.py
new file mode 100644
index 00000000..e87962f8
--- /dev/null
+++ b/tools/pilot.py
@@ -0,0 +1,403 @@
+#!/usr/bin/env python3
+"""Unattended playback pilot on the user's phone (debug build app.myspoti.dev, screen off).
+
+usage: tools/pilot.py [--out DIR] [--only A1,A2,B,C,D,F] [--long-pause SECS]
+
+Per scenario: logcat (epoch) + the page's media element sampled every 50 ms (tools/pilot_lib.py) in
+DIR/<scenario>.log / .media.jsonl, analysed by tools/uitrace_check.py into .analysis.json/.txt.
+ A1 short pause (5 s) x3: resume latency, rise to the full level
+ A2 long pause (>= 6 min, app sent to the background): page visibility, timer chain, resume rise,
+ then the end of the song (the "stuck at the end" report)
+ B end of a song (seek to duration - 8 s): the next one within ~3 s at full volume
+ C 4 minutes of continuous play across a song boundary
+ D 10 pause/resume cycles with random gaps, next/previous, swipenext bursts, seeks
+ F tools/qa.py --battery all (PT_SAFE=1: no screen key, no force-stop of other apps)
+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).
+"""
+import argparse, json, os, random, re, signal, subprocess, sys, time
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+import pilot_lib as L # noqa: E402
+import uitrace_check as U # noqa: E402
+import playback_test as pt # noqa: E402
+
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+PKG = L.PKG
+PLAYLIST = pt.PLAYLIST
+os.environ["PT_SAFE"] = "1"
+pt.SAFE = True
+
+
+class Stop(Exception):
+ pass
+
+
+# ── the phone is the user's ───────────────────────────────────────────────────
+
+def user_active():
+ """True when the screen is on and something else than the app is in front."""
+ p = L.adb("shell", "dumpsys", "power", timeout=20)
+ awake = "mWakefulness=Awake" in p
+ if not awake:
+ return False
+ a = L.adb("shell", "dumpsys", "activity", "activities", timeout=20)
+ m = re.search(r"ResumedActivity: ActivityRecord\{\S+ \S+ ([\w.]+)/", a)
+ return not (m and m.group(1) == PKG)
+
+
+def courtesy(note=print):
+ while user_active():
+ note("user on the phone: pausing 2 minutes")
+ time.sleep(120)
+
+
+def nap(secs, step=30):
+ """sleep, but give way to the user"""
+ end = time.time() + secs
+ while time.time() < end:
+ time.sleep(min(step, max(0.0, end - time.time())))
+ if time.time() < end and user_active():
+ courtesy()
+ end += 120
+
+
+# ── helpers ───────────────────────────────────────────────────────────────────
+
+def ensure_app():
+ if not L.adb("shell", "pidof", PKG):
+ pt.launch()
+ time.sleep(18)
+ pt.wait_ready(60)
+
+
+def tracks():
+ return pt.evaluate(f"""(async () => {{
+ const p = await window.Myspoti.call(-1, 'service.call', {{service: 'PlaylistAPI', method: 'getContents', args: [{json.dumps(PLAYLIST)}, {{limit: 12}}]}});
+ return p.items.filter(i => i.isPlayable).map(i => i.uri);
+ }})()""")
+
+
+def media_state():
+ return pt.evaluate("window.Myspoti.call(-1, 'media.state', {})")
+
+
+def start_song(uri, settle=8):
+ L.cmd("play", track=uri + "|", context=PLAYLIST)
+ p = pt.wait_for(lambda q: q["track"]["uri"] == uri and not q.get("paused") and not q.get("buffering") and (q.get("pos") or 0) > 1500, 25, "song playing")
+ time.sleep(settle)
+ return pt.probe()
+
+
+def uitrace(secs):
+ # --ei: the receiver reads getIntExtra("secs"); playback_test.test() sends ints as --el (ignored: 30 s default)
+ L.adb("shell", "am", "broadcast", "-a", "app.myspoti.TEST", "-p", PKG, "--es", "cmd", "uitrace", "--ei", "secs", str(int(secs)))
+
+
+def stop_check(cap):
+ n = cap.licence_429()
+ if n >= 6:
+ raise Stop(f"{n} licence 429 lines: stopped")
+
+
+def finish(cap, name, ref=1.0, notes=None):
+ base = cap.stop()
+ an = U.analyse(base, ref)
+ txt, _ = U.summary(an, 30)
+ open(base + ".analysis.txt", "w").write(txt + "\n")
+ json.dump(an, open(base + ".analysis.json", "w"), indent=1, default=str)
+ return an
+
+
+def failures(an, extra=()):
+ f = []
+ for e in an["events"]:
+ if e["scope"] == "spont" and not e.get("soft"):
+ f.append(dict(kind=e["kind"], ms=e["ms"], detail=e["detail"], file=os.path.basename(an["base"]), line=e["line"], line2=e["line2"]))
+ for m in an["cmd_metrics"]:
+ if m.get("FAIL"):
+ f.append(dict(kind="resume", ms=m["ms"], detail=f"{m['cmd']}: {m['FAIL']}", file=os.path.basename(an["base"]) + ".log", line=m["line"], line2=None))
+ for k in ("player stalled", "call timeout", "not taken", "crash", "http 429"):
+ for ms, no, text in an["log_flag_lines"].get(k, []):
+ if k == "http 429" and "widevine" not in text.lower():
+ continue
+ f.append(dict(kind="log:" + k, ms=ms, detail=text, file=os.path.basename(an["base"]) + ".log", line=no, line2=None))
+ f.extend(extra)
+ return f
+
+
+def resume_rows(an):
+ return [m for m in an["cmd_metrics"] if m["cmd"] in ("resume",)]
+
+
+def pct(v):
+ return None if v is None else round(v, 3)
+
+
+# ── scenarios ─────────────────────────────────────────────────────────────────
+
+def sc_A1(out, T):
+ cap = L.Capture(out, "A1_short_pause")
+ ref = 1.0
+ try:
+ start_song(T[0], 8)
+ ms0 = media_state()
+ ref = float(ms0["own"])
+ uitrace(70)
+ for i in range(3):
+ L.cmd("pause"); time.sleep(5.5)
+ L.cmd("resume"); time.sleep(8)
+ ms1 = media_state()
+ stop_check(cap)
+ finally:
+ an = finish(cap, "A1", ref=ref)
+ f = failures(an)
+ 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"))
+ return dict(name="A1 short pause x3", fail=f, key=dict(
+ own_level=ms0["own"], final=ms1,
+ to_audio_ms=[m.get("to_audio_ms") for m in rr], to_playing_ms=[m.get("to_playing_event_ms") for m in rr],
+ to_full_after_audio_ms=[m.get("to_full_after_audio_ms") for m in rr], to_full_ms=[m.get("to_full_ms") for m in rr],
+ vol_at_audio=[m.get("vol_at_audio") for m in rr], vol_min_after=[m.get("vol_min_1s_to_8s") for m in rr],
+ pause_to_event_ms=[m.get("to_pause_event_ms") for m in an["cmd_metrics"] if m["cmd"] == "pause"],
+ vol_at_pause_event=[m.get("vol_at_pause_event") for m in an["cmd_metrics"] if m["cmd"] == "pause"],
+ ramp=[m.get("ramp") for m in rr][:1]), analysis=an)
+
+
+def sc_A2(out, T, long_s, name="A2_long_pause", idx=0):
+ cap = L.Capture(out, name, sampler=False)
+ notes = {}
+ ref = 1.0
+ try:
+ start_song(T[idx], 6)
+ st = media_state()
+ ref = float(st["own"])
+ notes["before_pause"] = st
+ L.cmd("pause"); time.sleep(3)
+ notes["paused_state"] = media_state()
+ # No HOME key: on this phone it wakes the screen. The app stays as the user leaves it (screen off).
+ time.sleep(2)
+ notes["wakefulness"] = re.findall(r"mWakefulness=\w+", L.adb("shell", "dumpsys", "power"))[:1]
+ a = L.adb("shell", "dumpsys", "activity", "activities", timeout=20)
+ m = re.search(r"ResumedActivity: ActivityRecord\{\S+ \S+ ([\w.]+)/", a)
+ notes["resumed_activity"] = m.group(1) if m else None
+ t0 = time.time()
+ checks = {}
+ for label, at in (("1min", 60), ("end", long_s - 20)):
+ nap(max(0, at - (time.time() - t0)))
+ try:
+ checks[label] = dict(after_s=round(time.time() - t0), **pt.evaluate(L.TIMER_CHAIN_JS, timeout=30))
+ except Exception as e:
+ checks[label] = dict(error=str(e)[:120])
+ stop_check(cap)
+ nap(max(0, long_s - (time.time() - t0)))
+ try:
+ checks["final"] = dict(after_s=round(time.time() - t0), **pt.evaluate(L.TIMER_CHAIN_JS, timeout=30))
+ except Exception as e:
+ checks["final"] = dict(error=str(e)[:120])
+ notes["timers"] = checks
+ notes["paused_state_end"] = media_state()
+ uitrace(75)
+ cap.sampler = L.Sampler(cap.base + ".media.jsonl")
+ cap.sampler.start()
+ time.sleep(4)
+ L.cmd("resume")
+ time.sleep(14)
+ notes["after_resume"] = media_state()
+ # the end of the song after the long pause
+ p = pt.probe()
+ L.cmd("seek", ms=max(0, p["track"]["durationMs"] - 8000))
+ time.sleep(24)
+ notes["after_end"] = pt.probe()
+ notes["after_end_media"] = notes["after_end"].get("media")
+ stop_check(cap)
+ finally:
+ an = finish(cap, "A2", ref=ref)
+ f = failures(an)
+ t = notes.get("timers", {})
+ for lab, c in t.items():
+ if "error" in c:
+ f.append(dict(kind="timer_check", detail=f"{lab}: {c['error']}", file=name + ".log"))
+ else:
+ if c.get("vis") != "visible":
+ f.append(dict(kind="visibility", detail=f"{lab}: visibilityState={c['vis']} hidden={c['hidden']} after {c['after_s']} s", file=name + ".json"))
+ if max(c["chain8x38_ms"]) > 800:
+ f.append(dict(kind="timer_throttled", detail=f"{lab}: 8 x setTimeout(38) took {c['chain8x38_ms']} ms after {c['after_s']} s", file=name + ".json"))
+ b = an["boundaries"]
+ if not b:
+ f.append(dict(kind="no_song_change_after_seek", detail="engine never changed song after the seek to duration-8 s", file=name + ".log"))
+ rr = resume_rows(an)
+ return dict(name="A2 long pause then resume then end of song", fail=f, key=dict(
+ notes=notes, timers=t, to_audio_ms=[m.get("to_audio_ms") for m in rr], to_playing_ms=[m.get("to_playing_event_ms") for m in rr],
+ to_full_after_audio_ms=[m.get("to_full_after_audio_ms") for m in rr], vol_at_audio=[m.get("vol_at_audio") for m in rr],
+ vol_min_after=[m.get("vol_min_1s_to_8s") for m in rr], ramp=[m.get("ramp") for m in rr][:1], boundaries=b), analysis=an)
+
+
+def boundary_failures(an, limit_s=3.0):
+ f = []
+ for b in an["boundaries"]:
+ gap = b.get("audio_gap_ms")
+ if gap is None:
+ f.append(dict(kind="boundary_no_audio", ms=b["eng_switch_ms"], detail=f"engine moved to {b['to_title']!r} but no audio progress followed: {b}", file=os.path.basename(an["base"]) + ".log", line=b["line"]))
+ continue
+ if gap > limit_s * 1000:
+ f.append(dict(kind="boundary_gap", ms=b["eng_switch_ms"], detail=f"{gap} ms of silence between songs ({b['from_title']!r} -> {b['to_title']!r})", file=os.path.basename(an["base"]) + ".log", line=b["line"]))
+ v = b.get("new_vol_min_1.5s_to_4s")
+ if v is not None and v < 0.9:
+ f.append(dict(kind="boundary_low_volume", ms=b["eng_switch_ms"], detail=f"new song volume min {v} 1.5-4 s after its start", file=os.path.basename(an["base"]) + ".log", line=b["line"]))
+ return f
+
+
+def sc_B(out, T, name="B_end_of_track", idx=1):
+ cap = L.Capture(out, name)
+ try:
+ p = start_song(T[idx], 6)
+ uitrace(60)
+ time.sleep(1)
+ d = p["track"]["durationMs"]
+ ref = float(media_state()["own"])
+ L.cmd("seek", ms=d - 8000)
+ time.sleep(26)
+ stop_check(cap)
+ finally:
+ an = finish(cap, "B")
+ f = failures(an) + boundary_failures(an)
+ if not an["boundaries"]:
+ f.append(dict(kind="no_song_change", detail="no song change after the seek to duration-8 s", file="B_end_of_track.log"))
+ return dict(name=name, fail=f, key=dict(duration_ms=d, boundaries=an["boundaries"]), analysis=an)
+
+
+def sc_C(out, T, secs=250):
+ cap = L.Capture(out, "C_long_play")
+ try:
+ p = start_song(T[2], 4)
+ uitrace(secs + 15)
+ d = p["track"]["durationMs"]
+ L.cmd("seek", ms=max(0, d - 100000))
+ nap(secs)
+ stop_check(cap)
+ finally:
+ an = finish(cap, "C")
+ f = failures(an) + boundary_failures(an)
+ if not an["boundaries"]:
+ f.append(dict(kind="no_song_change", detail="no song boundary crossed in the run", file="C_long_play.log"))
+ return dict(name="C long play across a boundary", fail=f, key=dict(duration_ms=d, boundaries=an["boundaries"], seconds=secs), analysis=an)
+
+
+def sc_D(out, T, seed=20261020):
+ rnd = random.Random(seed)
+ cap = L.Capture(out, "D_commands")
+ plan = []
+ try:
+ start_song(T[3], 8)
+ uitrace(330)
+ own = float(media_state()["own"])
+ for i in range(10):
+ gap = round(rnd.uniform(1, 8), 1)
+ plan.append(gap)
+ L.cmd("pause"); time.sleep(gap)
+ L.cmd("resume"); time.sleep(round(rnd.uniform(2.5, 5), 1))
+ courtesy(); stop_check(cap)
+ L.cmd("next"); time.sleep(6)
+ L.cmd("next"); time.sleep(6)
+ L.cmd("previous"); time.sleep(0.9) # >3 s into the song: restart of the same song
+ L.cmd("previous"); time.sleep(6) # right after: the song before
+ for burst in range(2):
+ for _ in range(3):
+ L.cmd("swipenext"); time.sleep(0.15)
+ time.sleep(9)
+ p = pt.probe()
+ pos, d = p["pos"] or 0, p["track"]["durationMs"]
+ L.cmd("seek", ms=min(pos + 30000, d - 30000)); time.sleep(5)
+ L.cmd("seek", ms=max(5000, min(pos + 10000, d - 40000))); time.sleep(5)
+ L.cmd("seek", ms=10000); time.sleep(6)
+ stop_check(cap)
+ final = media_state()
+ finally:
+ an = finish(cap, "D", ref=1.0)
+ f = failures(an)
+ 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"]
+ g = lambda n, k: [m.get(k) for m in cm if m["cmd"] == n]
+ return dict(name="D pause/resume cycles, next/previous, swipenext bursts, seeks", fail=f, key=dict(
+ final=final, pause_gaps_s=plan, resume_to_audio_ms=g("resume", "to_audio_ms"), resume_to_full_after_audio_ms=g("resume", "to_full_after_audio_ms"),
+ resume_vol_min_after=g("resume", "vol_min_1s_to_8s"), next_to_eng_uri_ms=g("next", "to_eng_uri_change_ms"), next_to_audio_ms=g("next", "to_audio_ms"),
+ previous_to_audio_ms=g("previous", "to_audio_ms"), previous_to_eng_uri_ms=g("previous", "to_eng_uri_change_ms"), previous_to_restart_ms=g("previous", "to_eng_restart_ms"),
+ swipenext_to_eng_uri_ms=g("swipenext", "to_eng_uri_change_ms"), swipenext_to_ui_uri_ms=g("swipenext", "to_ui_uri_change_ms"), swipenext_to_audio_ms=g("swipenext", "to_audio_ms"),
+ seek_eng_pos_after=g("seek", "eng_pos_after")), analysis=an)
+
+
+def sc_F(out):
+ log = os.path.join(out, "F_qa_battery_all.txt")
+ env = dict(os.environ, PT_SAFE="1")
+ with open(log, "w") as lf:
+ pr = subprocess.Popen([sys.executable, "-u", os.path.join(ROOT, "tools/qa.py"), "--battery", "all"], stdout=lf, stderr=subprocess.STDOUT, env=env, cwd=ROOT)
+ paused = False
+ while pr.poll() is None:
+ time.sleep(15)
+ act = user_active()
+ if act and not paused:
+ pr.send_signal(signal.SIGSTOP); paused = True
+ lf.write("\n[pilot] user on the phone: battery suspended\n"); lf.flush()
+ elif not act and paused:
+ time.sleep(120)
+ if not user_active():
+ pr.send_signal(signal.SIGCONT); paused = False
+ lf.write("[pilot] battery resumed\n"); lf.flush()
+ txt = open(log).read()
+ f = []
+ for m in re.finditer(r"^(FAIL .*)$", txt, re.M):
+ f.append(dict(kind="battery", detail=m.group(1)[:300], file="F_qa_battery_all.txt"))
+ pm = re.search(r'"passed": (\d+),\s*"total": (\d+)', txt)
+ summ = [f"{pm[1]}/{pm[2]} passed"] if pm else re.findall(r"(\d+/\d+ passed.*)", txt)
+ l429 = re.findall(r'"licence_429": (\d+)', txt)
+ if l429 and int(l429[-1]) >= 6:
+ f.append(dict(kind="licence_429", detail=f"{l429[-1]} licence 429", file="F_qa_battery_all.txt"))
+ return dict(name="F qa.py --battery all", fail=f, key=dict(summary=summ[-1] if summ else None, licence_429=l429[-1] if l429 else None,
+ passes=re.findall(r"^PASS (\S+)", txt, re.M)))
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--out")
+ ap.add_argument("--only", default="A1,A2,B,C,D,F")
+ ap.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"))
+ os.makedirs(out, exist_ok=True)
+ resf = os.path.join(out, "results.json")
+ results = json.load(open(resf)) if os.path.exists(resf) else {}
+ courtesy()
+ ensure_app()
+ 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)}
+ for name in [x for x in a.only.split(",") if x]:
+ courtesy()
+ t0 = time.time()
+ print(f"== {name} ...", flush=True)
+ try:
+ r = jobs[name]()
+ except Stop as e:
+ results[name] = dict(name=name, stopped=str(e))
+ print("STOPPED:", e, flush=True)
+ json.dump(results, open(resf, "w"), indent=1, default=str)
+ break
+ except Exception as e:
+ r = dict(name=name, fail=[dict(kind="pilot_error", detail=repr(e)[:300], file="")], key={})
+ r.pop("analysis", None)
+ r["seconds"] = round(time.time() - t0)
+ results[name] = r
+ json.dump(results, open(resf, "w"), indent=1, default=str)
+ print(f"== {name}: {'PASS' if not r['fail'] else 'FAIL (' + str(len(r['fail'])) + ')'} in {r['seconds']} s", flush=True)
+ for x in r["fail"][:6]:
+ print(" ", x["kind"], x["detail"][:160], x.get("file"), x.get("line"), flush=True)
+ time.sleep(3)
+ print("out:", out)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tools/pilot_lib.py b/tools/pilot_lib.py
new file mode 100644
index 00000000..ac70b9ab
--- /dev/null
+++ b/tools/pilot_lib.py
@@ -0,0 +1,241 @@
+"""Shared helpers of the unattended playback pilot (tools/pilot.py, tools/uitrace_check.py).
+
+Everything is in the PHONE's clock (epoch ms): logcat -v epoch, the page's Date.now().
+The host clock is not used for any measurement.
+"""
+import json, os, re, subprocess, sys, threading, time
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+import cdp # noqa: E402
+import playback_test as pt # noqa: E402
+
+ADB = pt.ADB
+PKG = pt.PKG
+
+# The page-side sampler: every 50 ms, every media element the host's play() hook knows about
+# (window.__mspMedia) that has been used, plus its media events with exact timestamps.
+SAMPLER_JS = r"""(() => {
+ if (window.__pilot && window.__pilot.stop) window.__pilot.stop();
+ const P = window.__pilot = { buf: [], seen: new WeakSet(), ids: new Map(), n: 0, last: 0 };
+ const evs = ['playing','pause','play','waiting','stalled','ended','emptied','loadstart','loadedmetadata','canplay','seeking','seeked','volumechange','error','abort','suspend'];
+ const id = el => { let k = P.ids.get(el); if (!k) { k = ++P.n; P.ids.set(el, k); } return k; };
+ const used = el => el.readyState > 0 || !el.paused || el.currentTime > 0;
+ const hook = el => {
+ if (P.seen.has(el)) return; P.seen.add(el);
+ evs.forEach(e => el.addEventListener(e, () => el.muted || P.buf.push(['e', Date.now(), e, id(el), +el.currentTime.toFixed(3), +el.volume.toFixed(4), el.paused ? 1 : 0, el.readyState])));
+ };
+ P.tick = setInterval(() => {
+ const now = Date.now();
+ const m = window.__mspMedia ? [...window.__mspMedia] : [];
+ m.forEach(hook);
+ for (const el of m) if (used(el) && !el.muted) P.buf.push(['s', now, id(el), +el.currentTime.toFixed(3), el.paused ? 1 : 0, +el.volume.toFixed(4), el.readyState, el.ended ? 1 : 0, el.muted ? 1 : 0]);
+ P.last = now;
+ }, 50);
+ P.stop = () => { clearInterval(P.tick); };
+ P.drain = () => { const b = P.buf; P.buf = []; return b; };
+ return 'sampler on';
+})()"""
+
+TIMER_CHAIN_JS = r"""(async () => {
+ const out = [];
+ for (let k = 0; k < 3; k++) {
+ const t0 = performance.now();
+ await new Promise(res => { let n = 0; const f = () => { if (++n >= 8) return res(); setTimeout(f, 38); }; f(); });
+ out.push(Math.round(performance.now() - t0));
+ await new Promise(res => setTimeout(res, 300));
+ }
+ return { vis: document.visibilityState, hidden: document.hidden, chain8x38_ms: out };
+})()"""
+
+
+def adb(*a, timeout=60, check=False):
+ r = subprocess.run([ADB, *a], capture_output=True, text=True, timeout=timeout)
+ return r.stdout.strip()
+
+
+def phone_now_ms():
+ try:
+ return int(adb("shell", "date", "+%s%3N", timeout=10))
+ except Exception:
+ return 0
+
+
+class Page:
+ """A persistent CDP session on the engine page, reopened when the page goes away."""
+
+ def __init__(self):
+ self.s = None
+ self.n = 0
+ self.lock = threading.Lock()
+
+ def close(self):
+ try:
+ if self.s:
+ self.s.close()
+ except Exception:
+ pass
+ self.s = None
+
+ def eval(self, expr, timeout=20):
+ with self.lock:
+ for attempt in (0, 1):
+ try:
+ if self.s is None:
+ self.s = pt.page_socket()
+ self.n += 1
+ mid = self.n
+ self.s.settimeout(timeout)
+ cdp.ws_send(self.s, json.dumps({"id": mid, "method": "Runtime.evaluate", "params": {
+ "expression": expr, "awaitPromise": True, "returnByValue": True, "timeout": timeout * 1000}}))
+ while True:
+ msg = json.loads(cdp.ws_recv(self.s))
+ if msg.get("id") == mid:
+ r = msg.get("result", {})
+ if "exceptionDetails" in r:
+ raise RuntimeError("page exception: " + str(r["exceptionDetails"].get("exception", {}).get("description", ""))[:200])
+ return r.get("result", {}).get("value")
+ except RuntimeError:
+ raise
+ except Exception:
+ self.close()
+ if attempt:
+ raise
+ time.sleep(1)
+
+
+class Sampler(threading.Thread):
+ """Drains the page sampler every few seconds into a jsonl file (one array per line)."""
+
+ def __init__(self, path, page=None, every=3.0):
+ super().__init__(daemon=True)
+ self.path, self.page, self.every = path, page or Page(), every
+ self.stop_ev = threading.Event()
+ self.errors = []
+ self.installs = 0
+ self.rows = 0
+
+ def drain(self, f):
+ try:
+ data = self.page.eval("window.__pilot ? window.__pilot.drain() : null", timeout=15)
+ if data is None:
+ self.page.eval(SAMPLER_JS, timeout=15)
+ self.installs += 1
+ f.write(json.dumps(["i", int(time.time() * 1000), self.installs]) + "\n")
+ return
+ for row in data:
+ f.write(json.dumps(row) + "\n")
+ self.rows += len(data)
+ f.flush()
+ except Exception as e:
+ self.errors.append(f"{time.strftime('%H:%M:%S')} {str(e)[:120]}")
+ self.page.close()
+
+ def run(self):
+ with open(self.path, "w") as f:
+ try:
+ self.page.eval(SAMPLER_JS, timeout=20) # always a fresh buffer
+ self.installs += 1
+ except Exception as e:
+ self.errors.append(str(e)[:120])
+ while not self.stop_ev.wait(self.every):
+ self.drain(f)
+ self.drain(f)
+
+ def finish(self):
+ self.stop_ev.set()
+ self.join(30)
+ try:
+ self.page.eval("window.__pilot && window.__pilot.stop && window.__pilot.stop()", timeout=10)
+ except Exception:
+ pass
+ self.page.close()
+
+
+class Capture:
+ """One scenario's raw material: logcat (epoch) in <base>.log, page samples in <base>.media.jsonl."""
+
+ def __init__(self, outdir, name, sampler=True, every=3.0):
+ self.base = os.path.join(outdir, name)
+ adb("logcat", "-c")
+ self.logf = open(self.base + ".log", "w")
+ self.proc = subprocess.Popen([ADB, "logcat", "-v", "epoch", "-s", "Myspoti:*", "MspPlayer:*", "MspTrace:*", "AndroidRuntime:E"],
+ stdout=self.logf, stderr=subprocess.DEVNULL)
+ self.sampler = Sampler(self.base + ".media.jsonl", every=every) if sampler else None
+ if self.sampler:
+ self.sampler.start()
+
+ def stop(self):
+ if self.sampler:
+ self.sampler.finish()
+ time.sleep(1.0)
+ self.proc.kill()
+ self.logf.close()
+ return self.base
+
+ def licence_429(self):
+ n = 0
+ with open(self.base + ".log", errors="replace") as f:
+ for l in f:
+ ll = l.lower()
+ if "http 429" in ll and "widevine" in ll:
+ n += 1
+ return n
+
+
+def cmd(c, **extras):
+ pt.test(c, **extras)
+
+
+LINE = re.compile(r"^\s*(\d+\.\d+)\s+\d+\s+\d+\s+([VDIWEF])\s+(\S+?)\s*:\s?(.*)$")
+TRACE = re.compile(r"t=(\d+) ui_pos=(-?\d+) ui_dur=(-?\d+) ui_play=(\w+) ui_uri=(\S*) ui_cover=(\S*) eng_uri=(\S*) "
+ r"eng_pos=(\S*) eng_paused=(\S*) eng_buf=(\S*) ui_title=(.*) \| eng_title=(.*)$")
+
+
+def parse_log(path):
+ """-> (commands [(ms, name, lineno)], traces [dict], other [(ms, tag, text, lineno)])"""
+ cmds, traces, other = [], [], []
+ with open(path, errors="replace") as f:
+ for no, line in enumerate(f, 1):
+ m = LINE.match(line.rstrip("\n"))
+ if not m:
+ continue
+ ms = int(round(float(m[1]) * 1000))
+ tag, text = m[3], m[4]
+ if tag == "MspTrace":
+ t = TRACE.search(text)
+ if t:
+ num = lambda s: None if s in ("null", "") else int(float(s))
+ traces.append(dict(ms=ms, no=no, t=int(t[1]), ui_pos=int(t[2]), ui_dur=int(t[3]), ui_play=t[4] == "true",
+ ui_uri=t[5], ui_cover=t[6], eng_uri=t[7], eng_pos=num(t[8]),
+ eng_paused={"true": True, "false": False}.get(t[9]), eng_buf=t[10] == "true",
+ ui_title=t[11], eng_title=t[12]))
+ elif tag == "MspPlayer" and text.startswith("test command "):
+ cmds.append((ms, text[len("test command "):].strip(), no))
+ else:
+ other.append((ms, tag, text, no))
+ return cmds, traces, other
+
+
+def load_media(path):
+ """-> (samples [(ms, el, ct, paused, vol, rs, ended, muted, lineno)], events [(ms, name, el, ct, vol, paused, rs, lineno)])"""
+ samples, events = [], []
+ if not os.path.exists(path):
+ return samples, events
+ epoch = 0 # the sampler is installed again after a page reload: element ids restart at 1
+ with open(path) as f:
+ for no, line in enumerate(f, 1):
+ try:
+ r = json.loads(line)
+ except ValueError:
+ continue
+ if r[0] == "i":
+ epoch += 1
+ elif r[0] == "s":
+ r[2] += 100 * epoch
+ samples.append(tuple(r[1:]) + (no,))
+ elif r[0] == "e":
+ r[3] += 100 * epoch
+ events.append(tuple(r[1:]) + (no,))
+ samples.sort(key=lambda x: x[0])
+ events.sort(key=lambda x: x[0])
+ return samples, events
diff --git a/tools/pilot_report.py b/tools/pilot_report.py
new file mode 100644
index 00000000..957e285f
--- /dev/null
+++ b/tools/pilot_report.py
@@ -0,0 +1,153 @@
+#!/usr/bin/env python3
+"""Rebuilds the analysis and REPORT.md of a pilot run from its raw files.
+
+usage: tools/pilot_report.py DIR (DIR = tools/qa-results/pilot-<date>; needs results.json from tools/pilot.py)
+Every number comes from DIR/<scenario>.log (logcat -v epoch) and DIR/<scenario>.media.jsonl (page sampler).
+"""
+import json, os, re, sys
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+import pilot_lib as L # noqa: E402
+import uitrace_check as U # noqa: E402
+import pilot # noqa: E402
+
+KEYWORDS = re.compile(r"ad muted|ad stuck|ads?\.(off|skip)|ad .*asked|stalled|reload|silent|timeout|not taken|failed|jserror|ERROR|crossfade|"
+ r"media\.(mute|fade|rise)|player\.(play|next|previous)|http 4|http 5|test command|ready=|page (start|finished)|ended", re.I)
+
+
+def ad_near(other, ms, w=12000):
+ return [o for o in other if abs(o[0] - ms) <= w and re.search(r"\bad (muted|stuck)|ad .*asked the page", o[2])]
+
+
+def telling(base, f, n=6):
+ """3-6 log lines (with line numbers) around a failure."""
+ path = base + ".log"
+ cmds, traces, other = L.parse_log(path)
+ ms = f.get("ms")
+ out = []
+ if ms:
+ near = [o for o in other if ms - 2500 <= o[0] <= ms + 7000 and KEYWORDS.search(o[2]) and not o[2].startswith("console WARNING")]
+ cm = [(c[0], "MspPlayer", "test command " + c[1], c[2]) for c in cmds if ms - 6000 <= c[0] <= ms + 3000]
+ near = sorted(set(near + cm))
+ # keep the most telling ones, spread out
+ pick = near if len(near) <= n else near[:2] + near[len(near) // 2 - 1:len(near) // 2 + 1] + near[-2:]
+ out = [f"{os.path.basename(path)}:{o[3]} {o[2][:170]}" for o in pick[:n]]
+ if f.get("line") and f.get("kind", "").startswith(("ui_", "eng_", "trace", "cover")):
+ with open(path, errors="replace") as fh:
+ for i, line in enumerate(fh, 1):
+ if i == f["line"]:
+ out.insert(0, f"{os.path.basename(path)}:{i} " + re.sub(r"^\s*\d+\.\d+\s+\d+\s+\d+\s+\w\s+", "", line.strip())[:200])
+ break
+ return out[:n + 1]
+
+
+def scenario_failures(name, base, an, res):
+ f = pilot.failures(an)
+ if name in ("B", "B2", "B3", "C", "A2", "A2b"):
+ f += pilot.boundary_failures(an)
+ if name in ("A2", "A2b"):
+ for lab, c in (res.get("key", {}).get("timers") or {}).items():
+ if "error" in c:
+ f.append(dict(kind="timer_check", detail=f"{lab}: {c['error']}", file="results.json"))
+ else:
+ if c.get("vis") != "visible":
+ f.append(dict(kind="visibility", detail=f"{lab}: visibilityState={c['vis']} hidden={c['hidden']} after {c['after_s']} s", file="results.json"))
+ if max(c["chain8x38_ms"]) > 800:
+ f.append(dict(kind="timer_throttled", detail=f"{lab}: 8 x setTimeout(38) took {c['chain8x38_ms']} ms after {c['after_s']} s", file="results.json"))
+ if not an["boundaries"]:
+ f.append(dict(kind="no_song_change_after_seek", detail="engine never changed song after the seek to duration-8 s", file=os.path.basename(base) + ".log"))
+ if name in ("B", "B2", "B3", "C") and not an["boundaries"]:
+ f.append(dict(kind="no_song_change", detail="no song boundary crossed", file=os.path.basename(base) + ".log"))
+ fin = res.get("key", {}).get("final")
+ if name in ("A1", "D") and isinstance(fin, dict) and not (fin["volume"] >= 0.98 * fin["own"] and not fin["paused"]):
+ f.append(dict(kind="final_volume", detail=f"final media.state {fin}", file="results.json"))
+ return f
+
+
+SCEN = [("A1", "A1_short_pause", "A1 short pause (5 s) x3, resume rise + latency"),
+ ("A2", "A2_long_pause", "A2 long pause (>= 6 min, screen off), page visibility/timers, resume rise, end of song after it"),
+ ("A2b", "A2b_long_pause", "A2b long pause again (different song)"),
+ ("B", "B_end_of_track", "B end of track (seek to duration - 8 s)"),
+ ("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")]
+
+
+def fmt(v):
+ return json.dumps(v, default=str)
+
+
+def main(d):
+ results = json.load(open(os.path.join(d, "results.json")))
+ md = ["# Pilot report", "", f"Run directory: `{d}` ", "Times are the phone's epoch ms; `file:N` = line N of that file in this directory. "
+ "Latencies start at the app's `test command` log line (receiver side, adb broadcast overhead not included).", ""]
+ summary, ranked = [], []
+ for key, stem, title in SCEN:
+ base = os.path.join(d, stem)
+ if not os.path.exists(base + ".log"):
+ continue
+ res = results.get(key, {})
+ an = U.analyse(base, 1.0)
+ json.dump(an, open(base + ".analysis.json", "w"), indent=1, default=str)
+ open(base + ".analysis.txt", "w").write(U.summary(an, 40)[0] + "\n")
+ fails = scenario_failures(key, base, an, res)
+ _, _, other = L.parse_log(base + ".log")
+ for f in fails:
+ f["ad"] = bool(f.get("ms") and ad_near(other, f["ms"]))
+ verdict = "PASS" if not fails else "FAIL"
+ summary.append((key, verdict, title, len(fails)))
+ md += [f"## {title}: **{verdict}**", ""]
+ md += [f"Files: `{stem}.log`, `{stem}.media.jsonl`, `{stem}.analysis.txt|json`. Trace lines {an['trace_lines']}, media samples {an['media_samples']}, commands {len(an['commands'])}.", ""]
+ cm = an["cmd_metrics"]
+ g = lambda n, k: [m.get(k) for m in cm if m["cmd"] == n]
+ k = res.get("key", {})
+ if key in ("A1", "A2", "A2b", "D"):
+ md.append(f"- resume: ms to first audio {g('resume', 'to_audio_ms')}, to 'playing' event {g('resume', 'to_playing_event_ms')}, "
+ f"first currentTime change {g('resume', 'to_first_ct_change_ms')}, to full volume after audio start {g('resume', 'to_full_after_audio_ms')}, volume when audio starts {g('resume', 'vol_at_audio')}, "
+ f"min volume 1-8 s after {g('resume', 'vol_min_1s_to_8s')}")
+ warn = [m["WARN"] for m in cm if m.get("WARN")]
+ if warn:
+ md.append(f"- WARN x{len(warn)}: {warn[0]}")
+ md.append(f"- pause: ms to the element's pause event {g('pause', 'to_pause_event_ms')}, volume then {g('pause', 'vol_at_pause_event')}")
+ if key in ("A2", "A2b"):
+ md.append(f"- page checks while paused (screen off): {fmt(k.get('timers'))}")
+ md.append(f"- state: {fmt({x: k['notes'].get(x) for x in ('wakefulness', 'resumed_activity')})}; after resume media.state {fmt(k['notes'].get('after_resume'))}")
+ if key in ("A1", "D"):
+ md.append(f"- final media.state: {fmt(k.get('final'))}")
+ if key == "D":
+ md.append(f"- random pause gaps (s): {k.get('pause_gaps_s')}")
+ for n_ in ("next", "previous", "swipenext"):
+ 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')}")
+ 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']})")
+ md.append(f"- anomaly counts: {an['counts'] or 'none'}; log flags: {an['log_flags'] or 'none'}")
+ for f in fails:
+ ranked.append((key, f))
+ md += ["", f"### FAIL {f['kind']}{' (an ad was in progress)' if f.get('ad') else ''}", f"- {f['detail']}",
+ f"- where: `{f.get('file')}`" + (f" line {f['line']}" + (f"-{f['line2']}" if f.get('line2') else "") if f.get("line") else "")]
+ for t in telling(base, f):
+ md.append(f" - `{t}`")
+ md.append("")
+ if "F" in results:
+ r = results["F"]
+ md += [f"## F qa.py --battery all: **{'PASS' if not r['fail'] else 'FAIL'}**", "", f"- {fmt(r.get('key'))}"]
+ for f in r["fail"]:
+ ranked.append(("F", f))
+ md.append(f"- FAIL {f['detail']} (`{f.get('file')}`)")
+ md.append("")
+ notes = os.path.join(d, "NOTES.md")
+ if os.path.exists(notes):
+ md.insert(4, open(notes).read())
+ md.insert(4, "| scenario | verdict | failures |\n|---|---|---|\n" + "\n".join(f"| {t} | {v} | {n} |" for _, v, t, n in summary) + "\n")
+ open(os.path.join(d, "REPORT.md"), "w").write("\n".join(md) + "\n")
+ print("\n".join(f"{k} {v} {t} ({n})" for k, v, t, n in summary))
+ for k, f in ranked:
+ print(f" {k} {f['kind']}{' [ad]' if f.get('ad') else ''}: {f['detail'][:150]} @ {f.get('file')}:{f.get('line')}")
+
+
+if __name__ == "__main__":
+ main(sys.argv[1])
diff --git a/tools/playback_test.py b/tools/playback_test.py
index 8529a025..6653ff0e 100644
--- a/tools/playback_test.py
+++ b/tools/playback_test.py
@@ -34,6 +34,10 @@ BAD = [
]
SERIAL = None
+# PT_SAFE=1 (unattended runs on the user's own phone): no HOME/sleep/wake key (they light the screen),
+# 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"))
def adb(*args, check=True, timeout=60):
@@ -268,6 +272,10 @@ class Run:
def key(code):
+ if 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 too
+ if not code:
+ return
adb("shell", "input", "keyevent", *[str(c) for c in (code if isinstance(code, list) else [code])])
@@ -623,15 +631,18 @@ def main():
ap.add_argument("--playlist", default=PLAYLIST)
a = ap.parse_args()
SERIAL = a.serial
- for p in OTHERS:
- adb("shell", "am", "force-stop", p, check=False)
- adb("shell", "input", "keyevent", str(WAKE))
+ if not SAFE:
+ for p in OTHERS:
+ adb("shell", "am", "force-stop", p, check=False)
+ adb("shell", "input", "keyevent", str(WAKE))
log = Log()
if not adb("shell", "pidof", PKG, check=False):
launch()
wait_ready()
only = set(filter(None, a.only.split(",")))
skip = set(filter(None, a.skip.split(",")))
+ if SAFE:
+ skip.add("pull_back") # starts the Spotify app on the phone and transfers playback to another device
ctx = {"playlist": a.playlist}
results = []
r = Run(log)
diff --git a/tools/uitrace_check.py b/tools/uitrace_check.py
new file mode 100644
index 00000000..651af4b8
--- /dev/null
+++ b/tools/uitrace_check.py
@@ -0,0 +1,357 @@
+#!/usr/bin/env python3
+"""Analyses what a pilot run captured: the app's UI trace (MspTrace) and the page's media element.
+
+usage: tools/uitrace_check.py BASE [--json] BASE = path without extension of
+ BASE.log (logcat -v epoch) and BASE.media.jsonl (tools/pilot.py's page sampler)
+
+UI trace (what the app SHOWS vs what the engine page reports), counted as anomalies:
+ ui_pos_back / eng_pos_back position going backwards while playing on the same song (> 0.8 s)
+ ui_pos_jump / eng_pos_jump position jumping forward more than 2 s beyond the clock
+ ui_eng_pos_diff |ui_pos - eng_pos| > 1.5 s for > 1 s (same song)
+ ui_eng_uri_diff ui_uri != eng_uri for > 2 s
+ ui_eng_title_diff ui_title != eng_title for > 2 s
+ ui_eng_play_diff ui says playing while the engine is paused (or the reverse) for > 1.5 s
+ cover_change_same_uri the cover changed while the song did not
+ cover_same_after_uri_change (soft) the song changed, the cover did not (same album is legitimate)
+ trace_gap no trace line for > 1 s (the app's main thread / the logger stalled)
+Media element (the page's own audio element, the one that is not muted):
+ ct_back currentTime going backwards while playing, with no load/seek event around it
+ stall not paused, readyState >= 3, currentTime frozen for > 1.5 s
+ low_volume playing with volume < 90 % of the reference level for > 1 s (outside a resume rise)
+ silence_gap no element advancing for > 0.6 s, outside a pause the user asked for
+ resume/pause/next/seek metrics: latency from the app's "test command" log line
+Each anomaly is "cmd" when it happens within 3 s of a seek/previous/play/next command (a jump is then
+expected) and "spont" otherwise; a run fails on "spont" ones. Times are the phone's epoch ms.
+"""
+import argparse, json, os, re, sys
+from collections import Counter
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+import pilot_lib as L # noqa: E402
+
+MOVERS = ("seek", "previous", "play", "next", "swipenext")
+
+
+def near(cmds, ms, names=MOVERS, before=400, after=3000):
+ return any(n in names and c - before <= ms <= c + after for c, n, _ in cmds)
+
+
+def ev(kind, ms, cmds, detail, no=None, no2=None, movers=MOVERS, **extra):
+ return dict(kind=kind, ms=ms, scope="cmd" if near(cmds, ms, movers) else "spont", detail=detail, line=no, line2=no2, **extra)
+
+
+def runs(rows, pred, min_ms):
+ out, start = [], None
+ for i, r in enumerate(rows):
+ if pred(r):
+ if start is None:
+ start = i
+ elif start is not None:
+ if rows[i - 1]["ms"] - rows[start]["ms"] >= min_ms:
+ out.append((start, i - 1))
+ start = None
+ if start is not None and rows[-1]["ms"] - rows[start]["ms"] >= min_ms:
+ out.append((start, len(rows) - 1))
+ return out
+
+
+def check_ui(traces, cmds):
+ E = []
+ for i in range(1, len(traces)):
+ a, b = traces[i - 1], traces[i]
+ dt = b["t"] - a["t"]
+ if dt > 1000:
+ 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"]
+ if d < -800:
+ E.append(ev("ui_pos_back", b["ms"], cmds, f"ui_pos {a['ui_pos']} -> {b['ui_pos']} ({a['ui_title']})", b["no"]))
+ elif d > dt + 2000:
+ E.append(ev("ui_pos_jump", b["ms"], cmds, f"ui_pos {a['ui_pos']} -> {b['ui_pos']} in {dt} ms", b["no"]))
+ if (a["eng_uri"] == b["eng_uri"] and a["eng_paused"] is False and b["eng_paused"] is False
+ and a["eng_pos"] is not None and b["eng_pos"] is not None):
+ d = b["eng_pos"] - a["eng_pos"]
+ if d < -800:
+ E.append(ev("eng_pos_back", b["ms"], cmds, f"eng_pos {a['eng_pos']} -> {b['eng_pos']} ({a['eng_title']})", b["no"]))
+ elif d > dt + 2000:
+ E.append(ev("eng_pos_jump", b["ms"], cmds, f"eng_pos {a['eng_pos']} -> {b['eng_pos']} in {dt} ms", b["no"]))
+ if a["ui_uri"] == b["ui_uri"] and a["ui_cover"] != b["ui_cover"] and a["ui_uri"] not in ("", "null"):
+ E.append(ev("cover_change_same_uri", b["ms"], cmds, f"{a['ui_cover']} -> {b['ui_cover']} on {b['ui_title']}", b["no"]))
+ if a["ui_uri"] != b["ui_uri"] and a["ui_cover"] == b["ui_cover"] and a["ui_uri"] not in ("", "null") and b["ui_uri"] not in ("", "null"):
+ E.append(ev("cover_same_after_uri_change", b["ms"], cmds, f"{a['ui_title']} -> {b['ui_title']}, cover {b['ui_cover']}", b["no"], soft=True))
+ same = lambda r: r["ui_pos"] is not None and r["eng_pos"] is not None and r["ui_uri"] == r["eng_uri"] and r["ui_uri"] not in ("", "null")
+ for s, e in runs(traces, lambda r: same(r) and abs(r["ui_pos"] - r["eng_pos"]) > 1500, 1000):
+ E.append(ev("ui_eng_pos_diff", traces[s]["ms"], cmds,
+ f"{traces[e]['ms'] - traces[s]['ms']} ms, ui {traces[s]['ui_pos']} vs eng {traces[s]['eng_pos']} ({traces[s]['ui_title']})", traces[s]["no"], traces[e]["no"]))
+ for s, e in runs(traces, lambda r: r["ui_uri"] != r["eng_uri"], 2000):
+ E.append(ev("ui_eng_uri_diff", traces[s]["ms"], cmds,
+ f"{traces[e]['ms'] - traces[s]['ms']} ms, ui {traces[s]['ui_uri']} ({traces[s]['ui_title']}) vs eng {traces[s]['eng_uri']} ({traces[s]['eng_title']})", traces[s]["no"], traces[e]["no"]))
+ for s, e in runs(traces, lambda r: r["ui_uri"] == r["eng_uri"] and r["ui_title"] != r["eng_title"], 2000):
+ E.append(ev("ui_eng_title_diff", traces[s]["ms"], cmds,
+ f"{traces[e]['ms'] - traces[s]['ms']} ms, ui {traces[s]['ui_title']!r} vs eng {traces[s]['eng_title']!r}", traces[s]["no"], traces[e]["no"]))
+ for s, e in runs(traces, lambda r: r["eng_paused"] is not None and r["ui_play"] == r["eng_paused"], 1500):
+ E.append(ev("ui_eng_play_diff", traces[s]["ms"], cmds,
+ f"{traces[e]['ms'] - traces[s]['ms']} ms, ui_play={traces[s]['ui_play']} eng_paused={traces[s]['eng_paused']}", traces[s]["no"], traces[e]["no"],
+ movers=("pause", "resume", "play", "next", "previous", "swipenext")))
+ return E
+
+
+def by_el(samples):
+ d = {}
+ for s in samples:
+ if s[7]: # muted: the Canvas video, not the player
+ continue
+ d.setdefault(s[1], []).append(s)
+ return d
+
+
+def check_media(samples, events, cmds, ref=1.0):
+ E = []
+ els = by_el(samples)
+ loads = lambda el, ms: any(e[2] == el and e[1] in ("loadstart", "emptied", "loadedmetadata", "seeking", "seeked") and ms - 1500 <= e[0] <= ms + 800 for e in events)
+ for el, rows in els.items():
+ frozen_from = None
+ for i in range(1, len(rows)):
+ a, b = rows[i - 1], rows[i]
+ if not a[3] and not b[3] and b[2] < a[2] - 0.3 and not loads(el, b[0]):
+ E.append(ev("ct_back", b[0], cmds, f"el{el} currentTime {a[2]} -> {b[2]} with no load/seek event", b[8]))
+ adv = b[2] - a[2] > 0.001
+ if not b[3] and b[5] >= 3 and not adv and not loads(el, b[0]):
+ frozen_from = frozen_from if frozen_from is not None else i - 1
+ else:
+ if frozen_from is not None and rows[i - 1][0] - rows[frozen_from][0] > 1500:
+ E.append(ev("stall", rows[frozen_from][0], cmds, f"el{el} ct frozen {rows[i-1][0]-rows[frozen_from][0]} ms at {rows[frozen_from][2]}", rows[frozen_from][8]))
+ frozen_from = None
+ # audible spans: some unmuted element not paused and advancing
+ spans = []
+ for el, rows in els.items():
+ for i in range(1, len(rows)):
+ a, b = rows[i - 1], rows[i]
+ if not a[3] and not b[3] and b[2] - a[2] > 0.5 * (b[0] - a[0]) / 1000 and b[0] - a[0] < 1500:
+ spans.append((a[0], b[0], el, b[4], b[8]))
+ spans.sort()
+ merged = []
+ for s in spans:
+ if merged and s[0] <= merged[-1][1] + 120:
+ if s[1] > merged[-1][1]:
+ merged[-1] = (merged[-1][0], s[1], merged[-1][2], merged[-1][3], merged[-1][4])
+ else:
+ merged.append(s)
+ gaps = []
+ for a, b in zip(merged, merged[1:]):
+ g = b[0] - a[1]
+ if g > 600:
+ asked = any(n in ("pause", "play", "resume", "next", "previous", "swipenext", "seek") and a[1] - 600 <= c <= b[0] + 200 for c, n, _ in cmds)
+ gaps.append(dict(from_ms=a[1], to_ms=b[0], gap_ms=g, asked=asked, line=a[4], line2=b[4]))
+ if not asked:
+ E.append(ev("silence_gap", a[1], cmds, f"{g} ms without audio progress (el{a[2]} -> el{b[2]})", a[4], b[4]))
+ # low volume while advancing, outside the rise after an audio start
+ for el, rows in els.items():
+ low_from = None
+ for i in range(1, len(rows)):
+ a, b = rows[i - 1], rows[i]
+ adv = not a[3] and not b[3] and b[2] - a[2] > 0.001
+ starts = [s for s in merged if s[2] == el and s[0] <= b[0]]
+ lowv = adv and b[4] < 0.9 * ref
+ if lowv:
+ low_from = low_from if low_from is not None else i
+ else:
+ if low_from is not None:
+ dur = rows[i - 1][0] - rows[low_from][0]
+ if dur > 1000:
+ vmin = min(r[4] for r in rows[low_from:i])
+ E.append(ev("low_volume", rows[low_from][0], cmds, f"el{el} vol<{0.9*ref:.2f} for {dur} ms (min {vmin})", rows[low_from][8], rows[i - 1][8],
+ movers=("resume", "play", "next", "swipenext", "previous", "pause", "seek")))
+ low_from = None
+ return E, gaps, merged
+
+
+def player_el(samples, ms):
+ rows = [s for s in samples if not s[7] and s[0] <= ms]
+ if not rows:
+ return None
+ # the element sampled last before ms, among those that were advancing in the previous minute
+ return rows[-1][1]
+
+
+def command_metrics(samples, events, cmds, traces, ref_default=1.0):
+ """Latency per command, from the 'test command' log line (receiver time) to the first effect."""
+ out = []
+ S = [s for s in samples if not s[7]]
+ prev_level = ref_default
+ for idx, (ms, name, no) in enumerate(cmds):
+ nxt = cmds[idx + 1][0] if idx + 1 < len(cmds) else ms + 20000
+ horizon = min(nxt, ms + 12000)
+ m = dict(cmd=name, ms=ms, line=no)
+ before = [s for s in S if s[0] <= ms]
+ if before:
+ last = before[-1]
+ m["vol_before"] = last[4]
+ m["ct_before"] = last[2]
+ m["el_before"] = last[1]
+ if name == "pause":
+ if before and not before[-1][3]:
+ prev_level = before[-1][4]
+ pe = next((e for e in events if ms <= e[0] <= ms + 3000 and e[1] == "pause"), None)
+ m["to_pause_event_ms"] = pe[0] - ms if pe else None
+ m["vol_at_pause_event"] = pe[4] if pe else None
+ m["ref_level"] = prev_level
+ elif name in ("resume", "play"):
+ ref = prev_level
+ m["ref_level"] = ref
+ win = [s for s in S if ms <= s[0] <= horizon]
+ pl = next((e for e in events if e[0] >= ms and e[1] == "play"), None)
+ pg = next((e for e in events if e[0] >= ms and e[1] == "playing"), None)
+ m["to_play_call_ms"] = pl[0] - ms if pl else None
+ m["to_playing_event_ms"] = pg[0] - ms if pg else None
+ adv = None
+ lastct = {}
+ for s in win:
+ prev = lastct.get(s[1])
+ lastct[s[1]] = s[2]
+ base = m.get("ct_before") if s[1] == m.get("el_before") else None
+ if not s[3] and prev is not None and s[2] > prev + 0.03 and (base is None or name == "play" or s[2] > base + 0.03):
+ adv = s
+ break
+ m["to_audio_ms"] = adv[0] - ms if adv else None
+ first = next((x for x in win if not x[3] and x[1] == m.get("el_before") and m.get("ct_before") is not None and x[2] > m["ct_before"] + 0.001), None) if name == "resume" else None
+ m["to_first_ct_change_ms"] = first[0] - ms if first else None
+ if adv:
+ t_adv = adv[0]
+ el = adv[1]
+ ramp = [(r[0] - t_adv, r[4]) for r in S if r[1] == el and t_adv - 50 <= r[0] <= t_adv + 600]
+ m["vol_at_audio"] = adv[4]
+ full = next((r for r in S if r[1] == el and r[0] >= t_adv and r[4] >= 0.98 * ref), None)
+ m["to_full_after_audio_ms"] = (full[0] - t_adv) if full else None
+ m["to_full_ms"] = (full[0] - ms) if full else None
+ after = [r for r in S if r[1] == el and t_adv + 1000 <= r[0] <= min(horizon, t_adv + 8000)]
+ m["vol_min_1s_to_8s"] = min((r[4] for r in after), default=None)
+ m["vol_end"] = after[-1][4] if after else None
+ m["ramp"] = [(t, v) for t, v in ramp[::max(1, len(ramp) // 8)]]
+ if adv:
+ early = [r for r in S if r[1] == adv[1] and ms <= r[0] < adv[0] - 150 and r[4] >= 0.98 * ref]
+ if adv[4] >= 0.9 * ref and early:
+ m["WARN"] = "the rise finished before the audio began (ramp spent on silence): sound starts at full volume"
+ if name == "resume" and (not adv or m.get("to_full_after_audio_ms") is None):
+ m["FAIL"] = "no audio" if not adv else "volume never reached the full level"
+ elif name == "resume" and m.get("vol_min_1s_to_8s") is not None and m["vol_min_1s_to_8s"] < 0.9 * ref:
+ m["FAIL"] = f"volume dipped to {m['vol_min_1s_to_8s']} after the rise"
+ elif name in ("next", "swipenext", "previous"):
+ tr = [t for t in traces if ms <= t["ms"] <= horizon]
+ base = next((t for t in reversed(traces) if t["ms"] <= ms), None)
+ if base:
+ e1 = next((t for t in tr if t["eng_uri"] != base["eng_uri"]), None)
+ u1 = next((t for t in tr if t["ui_uri"] != base["ui_uri"]), None)
+ m["to_eng_uri_change_ms"] = e1["ms"] - ms if e1 else None
+ m["to_ui_uri_change_ms"] = u1["ms"] - ms if u1 else None
+ if name == "previous" and not e1:
+ r1 = next((t for t in tr if t["eng_pos"] is not None and base["eng_pos"] is not None and t["eng_pos"] < base["eng_pos"] - 2000), None)
+ m["to_eng_restart_ms"] = r1["ms"] - ms if r1 else None
+ w = [s for s in S if ms <= s[0] <= horizon]
+ lastct = {}
+ tfirst = None
+ for s in w:
+ prev = lastct.get(s[1])
+ lastct[s[1]] = s[2]
+ if not s[3] and prev is not None and s[2] > prev + 0.03 and s[0] > ms + 100:
+ ldone = [e for e in events if ms <= e[0] <= s[0] and e[1] in ("loadstart", "emptied", "seeking")]
+ if ldone or s[1] != m.get("el_before"):
+ tfirst = s
+ break
+ m["to_audio_ms"] = tfirst[0] - ms if tfirst else None
+ if tfirst:
+ m["vol_at_audio"] = tfirst[4]
+ elif name == "seek":
+ tr = [t for t in traces if ms <= t["ms"] <= horizon]
+ m["eng_pos_after"] = [t["eng_pos"] for t in tr[::10]][:6]
+ out.append(m)
+ return out
+
+
+def natural_boundaries(traces, merged, samples, cmds):
+ """Song changes the engine made by itself (end of a song): when the old audio ended, when the new began, at what volume."""
+ out = []
+ S = [s for s in samples if not s[7]]
+ ok = lambda u: u not in ("", "null", "None")
+ for i in range(1, len(traces)):
+ a, b = traces[i - 1], traces[i]
+ if a["eng_uri"] == b["eng_uri"] or not ok(a["eng_uri"]) or not ok(b["eng_uri"]):
+ continue
+ if near(cmds, b["ms"], ("next", "previous", "swipenext", "play"), before=1500, after=1500):
+ continue
+ cand = [j for j, sp in enumerate(merged) if sp[1] >= a["ms"] - 2500 and sp[0] <= b["ms"] + 1500]
+ k = cand[0] if cand else None
+ d = dict(eng_switch_ms=b["ms"], from_title=a["eng_title"], to_title=b["eng_title"], old_eng_pos=a["eng_pos"], old_dur=a["ui_dur"], line=b["no"])
+ if k is not None:
+ d["old_audio_end_ms"] = merged[k][1]
+ d["switch_after_audio_end_ms"] = b["ms"] - merged[k][1]
+ if merged[k][1] > b["ms"] + 1500: # one unbroken span across the switch: no silence at all
+ st, el = b["ms"], merged[k][2]
+ d["audio_gap_ms"] = 0
+ elif k + 1 < len(merged) and merged[k + 1][0] - merged[k][1] < 12000:
+ st, el = merged[k + 1][0], merged[k + 1][2]
+ d["audio_gap_ms"] = st - merged[k][1]
+ else:
+ st = None
+ if st is not None:
+ d["new_audio_start_ms"] = st
+ v = [r[4] for r in S if r[1] == el and st + 1500 <= r[0] <= st + 4000]
+ d["new_vol_min_1.5s_to_4s"] = min(v) if v else None
+ out.append(d)
+ 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"),
+ ("not taken", r"not taken|command failed|transport failed|page not answering|page silent"), ("crash", r"FATAL|AndroidRuntime")]
+ out = {}
+ for ms, tag, text, no in other:
+ for k, rx in pats:
+ if re.search(rx, text, re.I):
+ out.setdefault(k, []).append((ms, no, text[:200]))
+ return out
+
+
+def analyse(base, ref=1.0):
+ cmds, traces, other = L.parse_log(base + ".log")
+ samples, events = L.load_media(base + ".media.jsonl")
+ ui = check_ui(traces, cmds)
+ med, gaps, merged = check_media(samples, events, cmds, ref)
+ bounds = natural_boundaries(traces, merged, samples, cmds)
+ flags = log_flags(other)
+ cm = command_metrics(samples, events, cmds, traces, ref)
+ # 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()})
+
+
+def summary(a, limit=12):
+ L_ = [f"{os.path.basename(a['base'])}: {a['trace_lines']} trace lines, {a['media_samples']} media samples, {len(a['commands'])} commands"]
+ spont = {k: n for k, n in a["counts"].items() if k.endswith("/spont") and not k.startswith("cover_same_after")}
+ L_.append("anomalies: " + (", ".join(f"{k}={n}" for k, n in a["counts"].items()) or "none"))
+ L_.append("log flags: " + (", ".join(f"{k}={n}" for k, n in a["log_flags"].items()) or "none"))
+ shown = 0
+ for e in a["events"]:
+ if e["scope"] == "spont" and not e.get("soft") and shown < limit:
+ L_.append(f" [{e['kind']}] @{e['ms']} log:{e['line']}{'-' + str(e['line2']) if e['line2'] else ''} {e['detail']}")
+ shown += 1
+ return "\n".join(L_), bool(spont)
+
+
+if __name__ == "__main__":
+ ap = argparse.ArgumentParser()
+ ap.add_argument("base")
+ ap.add_argument("--json", action="store_true")
+ ap.add_argument("--ref", type=float, default=1.0, help="reference (full) element volume")
+ a = ap.parse_args()
+ res = analyse(a.base, a.ref)
+ txt, bad = summary(res)
+ print(txt)
+ if a.json:
+ json.dump(res, open(a.base + ".analysis.json", "w"), indent=1, default=str)
+ sys.exit(1 if bad else 0)