Native Android client for Spotify, built with Jetpack Compose
Kotlin ad-freeadblockandroidjetpack-composekotlinlyricsmusic-playermusic-videomyspotispotifyspotify-adblockerspotify-clientspotify-connectspotui
Cover flight between the mini player and the player, a native crash of the video aligner fixed, notification artwork that no longer goes missing, tools/qa.py
kota-zoaa0bdd207eb2
diff --git a/.gitignore b/.gitignoreindex 8a5ec3cd..b3cb406f 100644--- a/.gitignore+++ b/.gitignore@@ -18,3 +18,4 @@ ANNEXE-ETAT.txtdocs/RESTE-A-FAIRE.mdtools/handoff_state.shREDDIT-*.md+tools/qa-results/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.ktindex 719cc9ab..49ad3537 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@@ -40,6 +40,8 @@ import androidx.compose.runtime.rememberimport androidx.compose.runtime.setValueimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifier+import androidx.compose.ui.layout.onGloballyPositioned+import androidx.compose.ui.layout.boundsInWindowimport androidx.compose.ui.graphics.graphicsLayerimport androidx.compose.ui.draw.clipimport androidx.compose.ui.draw.clipToBounds@@ -221,6 +223,12 @@ fun MiniPlayer(navController: NavHostController) {transition = CrossFade,modifier = Modifier.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+ .onGloballyPositioned { CoverFlight.mini = it.boundsInWindow() }+ .graphicsLayer { alpha = if (CoverFlight.flying) 0f else 1f }+ else Modifier).clip(RoundedCornerShape(4.dp)),model = s?.coverUri ?: songCoverUri,contentScale = ContentScale.Crop,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.ktnew file mode 100644index 00000000..1174772d--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/components/CoverFlight.kt@@ -0,0 +1,85 @@+package com.music.spotui.ui.components++import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.geometry.Rect+import androidx.compose.ui.graphics.TransformOrigin+import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.unit.dp+import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi+import com.bumptech.glide.integration.compose.GlideImage++/**+ * The cover that flies between the mini player and the full player while the player opens+ * or closes, as in the official app: the small artwork grows into the big one as the player+ * rises, and shrinks back into the mini player as it goes down.+ *+ * Both covers report where they sit; while [progress] is set the real ones are hidden and+ * [FlyingCover] draws one in between. Everything moves in the draw phase (graphicsLayer),+ * so the flight recomposes nothing.+ */+object CoverFlight {+ /** The mini player's cover, in window pixels. */+ 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)+ /** 0 (mini player) .. 1 (full player) while the player opens or closes; null otherwise. */+ var progress by mutableStateOf<Float?>(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 }++ /** Read in a draw-phase lambda: hides a real cover while its stand-in flies. */+ val flying: Boolean get() = progress != null+}++/**+ * The flying cover. Drawn inside the sliding player, so the slide's own offset+ * ([slideOffsetPx], from the same animation) is taken back out: the cover moves in window+ * coordinates, not with the sheet.+ */+@OptIn(ExperimentalGlideComposeApi::class)+@Composable+fun FlyingCover(coverUri: String, slideOffsetPx: () -> Float) {+ val to = CoverFlight.player ?: return+ val from = CoverFlight.mini ?: return+ if (to.width <= 0f || to.height <= 0f) return+ val density = LocalDensity.current+ Box(+ Modifier+ .size(with(density) { to.width.toDp() }, with(density) { to.height.toDp() })+ .graphicsLayer {+ val p = CoverFlight.progress+ if (p == null) { alpha = 0f; return@graphicsLayer }+ alpha = 1f+ transformOrigin = TransformOrigin(0f, 0f)+ val left = from.left + (to.left - from.left) * p+ val top = from.top + (to.top - from.top) * p+ val width = from.width + (to.width - from.width) * p+ scaleX = width / to.width+ scaleY = scaleX+ translationX = left+ translationY = top - slideOffsetPx()+ }+ .clip(RoundedCornerShape(8.dp)),+ ) {+ GlideImage(+ model = coverUri,+ contentDescription = null,+ contentScale = ContentScale.Crop,+ modifier = Modifier.size(with(density) { to.width.toDp() }, with(density) { to.height.toDp() }),+ )+ }+}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.ktindex a98514a2..9bd1fe47 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@@ -2,6 +2,18 @@ package com.music.spotui.ui.navigationimport androidx.activity.compose.BackHandlerimport androidx.compose.animation.AnimatedVisibility+import androidx.compose.animation.EnterExitState+import androidx.compose.animation.core.animateFloat+import androidx.compose.foundation.layout.Box+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 com.music.spotui.ui.components.CoverFlight+import com.music.spotui.ui.components.FlyingCoverimport androidx.compose.animation.core.tweenimport androidx.compose.animation.slideInVerticallyimport androidx.compose.animation.slideOutVertically@@ -40,14 +52,37 @@ fun PlayerOverlay(navController: NavController) {) {BackHandler { PlayerSheet.close() }val settled = remember { derivedStateOf { transition.currentState == transition.targetState } }- CompositionLocalProvider(LocalPageSettled provides settled) {- // A podcast episode gets the podcast player (±15 s, speed, sleep timer, no shuffle);- // everything else keeps the music player.- if (com.music.spotui.di.SongPlayer.isEpisode) {- com.music.spotui.ui.screens.PodcastPlayerScreen(navController)- } else {- PlayerScreen(navController)+ // The sheet's own progress (same curves as its slide), for the cover's flight: read only+ // in a flow and in draw lambdas, never in composition, so the player does not recompose+ // on every frame of the slide.+ val sheet = transition.animateFloat(+ transitionSpec = {+ if (targetState == EnterExitState.Visible) tween(SHEET_IN_MS, easing = Decelerate)+ else tween(SHEET_OUT_MS, easing = Accelerate)+ },+ 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 } }+ }+ androidx.compose.runtime.DisposableEffect(Unit) { onDispose { CoverFlight.progress = null } }+ var heightPx by remember { mutableIntStateOf(0) }+ androidx.compose.runtime.SideEffect { CoverFlight.sheetOffsetPx = { (1f - sheet.value) * heightPx } }+ Box(Modifier.fillMaxSize().onSizeChanged { heightPx = it.height }) {+ CompositionLocalProvider(LocalPageSettled provides settled) {+ // A podcast episode gets the podcast player (±15 s, speed, sleep timer, no shuffle);+ // everything else keeps the music player.+ if (com.music.spotui.di.SongPlayer.isEpisode) {+ com.music.spotui.ui.screens.PodcastPlayerScreen(navController)+ } else {+ 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.ktindex 7ef6ea6d..ed323a16 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@@ -81,6 +81,8 @@ import androidx.compose.runtime.rememberimport com.music.spotui.ui.components.pressableimport kotlinx.coroutines.launchimport androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.layout.boundsInWindow+import androidx.compose.ui.layout.onGloballyPositionedimport androidx.compose.ui.input.nestedscroll.nestedScrollimport androidx.compose.runtime.setValueimport androidx.compose.ui.Alignment@@ -457,8 +459,15 @@ fun PlayerScreen(navController: NavController) {modifier = (if (immersive) Modifier.fillMaxSize()// Normal layout keeps the inset, rounded cover.else Modifier.padding(horizontal = 24.dp).aspectRatio(1f).clip(RoundedCornerShape(8.dp)))+ // Where the mini player's cover flies to (CoverFlight), the sheet's+ // 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+ flight.player = if (immersive || coverAlpha < 1f) null+ else it.boundsInWindow().translate(0f, -flight.sheetOffsetPx())+ } else Modifier).graphicsLayer {- alpha = coverAlpha+ alpha = coverAlpha * (if (page == 1 && com.music.spotui.ui.components.CoverFlight.flying) 0f else 1f)val grow = 1f + (1f - coverAlpha) * 0.06fscaleX = grow; scaleY = grow},diff --git a/base/app/src/main/java/com/music/spotui/video/AudioAlign.kt b/base/app/src/main/java/com/music/spotui/video/AudioAlign.ktindex 7a412e58..42b1146e 100644--- a/base/app/src/main/java/com/music/spotui/video/AudioAlign.kt+++ b/base/app/src/main/java/com/music/spotui/video/AudioAlign.kt@@ -71,6 +71,9 @@ object AudioAlign {val ex = MediaExtractor()var decoderToRelease: MediaCodec? = nullvar threadToStop: android.os.HandlerThread? = null+ // Set on the codec's own thread when it is released: a callback still queued then+ // must not touch a buffer of the released codec.+ var closing = falsetry {ex.setDataSource(file.absolutePath)val track = (0 until ex.trackCount).first { ex.getTrackFormat(it).getString(MediaFormat.KEY_MIME)!!.startsWith("audio/") }@@ -93,7 +96,7 @@ object AudioAlign {val t0 = System.nanoTime()codec.setCallback(object : MediaCodec.Callback() {override fun onInputBufferAvailable(c: MediaCodec, index: Int) {- if (inputDone) return+ if (inputDone || closing) returnif (maxSeconds > 0 && out.size() >= maxSeconds * SR) {// Enough audio for a first alignment: stop here.inputDone = true@@ -113,8 +116,10 @@ object AudioAlign {}override fun onOutputBufferAvailable(c: MediaCodec, index: Int, info: MediaCodec.BufferInfo) {+ if (closing) returntry {val bb = c.getOutputBuffer(index)!!.order(ByteOrder.nativeOrder())+ bb.position(info.offset).limit(info.offset + info.size)if (isFloat) {val count = info.size / 4if (floatPcm.size < count) floatPcm = FloatArray(count)@@ -147,7 +152,21 @@ object AudioAlign {android.util.Log.i("MusicVideo", "decode $codecName: ${(System.nanoTime() - t0) / 1_000_000} ms")return out.result()} finally {- decoderToRelease?.let { decoder ->+ // Released on the codec's own thread, after the callback running there: released from+ // here it unmapped the output buffer a callback was still copying (native crash,+ // SIGSEGV in memcpy under ByteBufferAsShortBuffer.get, measured on the test phone).+ val decoder = decoderToRelease+ val looper = threadToStop?.looper+ if (decoder != null && looper != null) {+ val released = java.util.concurrent.CountDownLatch(1)+ android.os.Handler(looper).post {+ closing = true+ runCatching { decoder.stop() }+ runCatching { decoder.release() }+ released.countDown()+ }+ released.await(5, java.util.concurrent.TimeUnit.SECONDS)+ } else if (decoder != null) {runCatching { decoder.stop() }runCatching { decoder.release() }}diff --git a/base/host-android/src/main/kotlin/app/myspoti/host/android/PlaybackService.kt b/base/host-android/src/main/kotlin/app/myspoti/host/android/PlaybackService.ktindex 556b84e0..20b9f380 100644--- a/base/host-android/src/main/kotlin/app/myspoti/host/android/PlaybackService.kt+++ b/base/host-android/src/main/kotlin/app/myspoti/host/android/PlaybackService.kt@@ -10,6 +10,7 @@ import android.content.pm.ApplicationInfoimport android.content.pm.ServiceInfoimport android.graphics.Bitmapimport android.graphics.BitmapFactory+import android.net.Uriimport android.os.Buildimport android.os.Bundleimport android.support.v4.media.MediaBrowserCompat@@ -23,10 +24,13 @@ import androidx.media.MediaBrowserServiceCompatimport androidx.media.VolumeProviderCompatimport androidx.media.app.NotificationCompat.MediaStyleimport androidx.media.session.MediaButtonReceiver+import android.util.LruCacheimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Jobimport kotlinx.coroutines.SupervisorJobimport kotlinx.coroutines.cancel+import kotlinx.coroutines.delayimport kotlinx.coroutines.launchimport kotlinx.coroutines.withContextimport okhttp3.OkHttpClient@@ -82,6 +86,15 @@ class PlaybackService : MediaBrowserServiceCompat() {private var foreground = falseprivate var lastCoverUrl: String? = nullprivate var cover: Bitmap? = null+ private var coverJob: Job? = null+ /**+ * The last covers: a song heard again, or the one after an ad, shows its artwork at once+ * instead of leaving the notification bare until the download ends. Bitmaps are never+ * recycled by hand: the session, the notification and this cache may all hold one.+ */+ private val covers = object : LruCache<String, Bitmap>(COVER_CACHE_BYTES) {+ override fun sizeOf(key: String, value: Bitmap) = value.byteCount+ }override fun onCreate() {super.onCreate()@@ -155,6 +168,11 @@ class PlaybackService : MediaBrowserServiceCompat() {}private fun apply(info: NowPlayingInfo) {+ // Before the metadata: a cached cover is in it at once. A cover that failed (offline, Doze with the screen off, a 5xx) is asked again on the next+ // real state change: it used to stay bare until the next song.+ if (info.coverUrl != lastCoverUrl || (cover == null && !info.coverUrl.isNullOrBlank() && coverJob?.isActive != true)) {+ loadCover(info.coverUrl)+ }session.setMetadata(MediaMetadataCompat.Builder().putString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID, info.id).putString(MediaMetadataCompat.METADATA_KEY_TITLE, info.title)@@ -162,7 +180,12 @@ class PlaybackService : MediaBrowserServiceCompat() {.putString(MediaMetadataCompat.METADATA_KEY_ALBUM, info.album).putString(MediaMetadataCompat.METADATA_KEY_ALBUM_ART_URI, info.coverUrl).putLong(MediaMetadataCompat.METADATA_KEY_DURATION, info.durationMs)- .putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, cover.takeIf { info.coverUrl == lastCoverUrl })+ .apply {+ // Both keys: the lock screen, the shade, Bluetooth and the car do not read the same one.+ val art = cover.takeIf { info.coverUrl == lastCoverUrl }+ putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, art)+ putBitmap(MediaMetadataCompat.METADATA_KEY_ART, art)+ }.build())val state = when {info.buffering && info.playing -> PlaybackStateCompat.STATE_BUFFERING@@ -179,26 +202,77 @@ class PlaybackService : MediaBrowserServiceCompat() {if (info.shuffle) R.drawable.msp_ic_shuffle_on else R.drawable.msp_ic_shuffle).setState(state, info.positionMs, if (info.playing && !info.buffering) 1f else 0f).build())- if (info.coverUrl != lastCoverUrl) loadCover(info.coverUrl)}private fun loadCover(url: String?) {+ coverJob?.cancel()lastCoverUrl = url- cover = null- if (url.isNullOrBlank()) return- scope.launch {- val bitmap = withContext(Dispatchers.IO) {- runCatching {- http.newCall(Request.Builder().url(url).build()).execute().use { BitmapFactory.decodeStream(it.body.byteStream()) }- }.getOrNull()- }- if (url == lastCoverUrl && bitmap != null) {- cover = bitmap- current?.let { apply(it); show(it) }+ cover = url?.let { covers.get(it) }+ if (url.isNullOrBlank() || cover != null) return+ coverJob = scope.launch {+ // Retried with a growing pause: a failed load used to be forgotten.+ var attempt = 0+ while (true) {+ val bitmap = withContext(Dispatchers.IO) { fetchCover(url) }+ if (bitmap != null) {+ covers.put(url, bitmap)+ if (url == lastCoverUrl) {+ cover = bitmap+ current?.let { apply(it); show(it) }+ val art = session.controller.metadata?.getBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART)+ android.util.Log.d("Myspoti", "cover $url -> ${bitmap.width}x${bitmap.height}, session art ${art?.width}x${art?.height}")+ }+ return@launch+ }+ delay(COVER_RETRY_MS.getOrNull(attempt++) ?: break)}+ android.util.Log.w("Myspoti", "cover not loaded: $url")}}+ /** The cover as a bitmap of at most [COVER_MAX_PX], from a Spotify image id, a URL or a local content URI; null on failure. */+ private fun fetchCover(url: String): Bitmap? {+ // The same ids the app resolves for Glide (SpotifyImages.kt): profile and playlist items give them.+ val resolved = when {+ url.startsWith("spotify:image:") -> "https://i.scdn.co/image/" + url.removePrefix("spotify:image:")+ url.startsWith("spotify:mosaic:") -> "https://mosaic.scdn.co/640/" + url.removePrefix("spotify:mosaic:").split(':').joinToString("")+ else -> url+ }+ // An album cover comes in 64, 300 and 640 px under the same id: ask for the 640 one first+ // (the queue and the next song may only carry the small one), the given size is the fallback.+ val candidates = listOfNotNull(+ SMALL_ALBUM_COVER.find(resolved)?.let { resolved.replace(it.value, LARGE_ALBUM_COVER_PREFIX) },+ resolved,+ ).distinct()+ for (candidate in candidates) {+ val bytes = runCatching {+ if (candidate.startsWith("http")) {+ http.newCall(Request.Builder().url(candidate).build()).execute().use { r ->+ if (r.isSuccessful) r.body.bytes() else null.also { android.util.Log.w("Myspoti", "cover http ${r.code} $candidate") }+ }+ } else contentResolver.openInputStream(Uri.parse(candidate))?.use { it.readBytes() }+ }.onFailure { android.util.Log.w("Myspoti", "cover $candidate: $it") }.getOrNull() ?: continue+ decode(bytes)?.let { return it }+ }+ return null+ }++ /** Never decodes more pixels than needed, never keeps more than [COVER_MAX_PX] a side. */+ private fun decode(bytes: ByteArray): Bitmap? {+ val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }+ BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds)+ if (bounds.outWidth <= 0 || bounds.outHeight <= 0) return null+ var sample = 1+ while (maxOf(bounds.outWidth, bounds.outHeight) / (sample * 2) >= COVER_MAX_PX) sample *= 2+ val bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size, BitmapFactory.Options().apply { inSampleSize = sample })+ ?: return null+ val longest = maxOf(bitmap.width, bitmap.height)+ if (longest <= COVER_MAX_PX) return bitmap+ val scale = COVER_MAX_PX.toFloat() / longest+ return Bitmap.createScaledBitmap(bitmap, (bitmap.width * scale).toInt().coerceAtLeast(1),+ (bitmap.height * scale).toInt().coerceAtLeast(1), true).also { if (it !== bitmap) bitmap.recycle() }+ }+private val handler = android.os.Handler(android.os.Looper.getMainLooper())/** Leaves the foreground only after a real pause, never between two songs. */private val leaveForeground = Runnable {@@ -367,6 +441,14 @@ class PlaybackService : MediaBrowserServiceCompat() {PlaybackStateCompat.ACTION_SEEK_TO or PlaybackStateCompat.ACTION_PLAY_FROM_MEDIA_ID orPlaybackStateCompat.ACTION_PLAY_FROM_SEARCHprivate val http = OkHttpClient()+ /** The largest side kept for artwork: what Android's media controls expect (640 is Spotify's biggest cover). */+ private const val COVER_MAX_PX = 640+ /** About four 640 px covers. */+ private const val COVER_CACHE_BYTES = 8 * 1024 * 1024+ /** Pause before each new try of a failed cover; after the last one the cover waits for the next state change. */+ private val COVER_RETRY_MS = longArrayOf(2_000L, 6_000L, 15_000L)+ private val SMALL_ALBUM_COVER = Regex("ab67616d0000(?:1e02|4851)")+ private const val LARGE_ALBUM_COVER_PREFIX = "ab67616d0000b273"@Volatile private var instance: PlaybackService? = null@Volatile private var current: NowPlayingInfo? = nulldiff --git a/tools/qa.py b/tools/qa.pynew file mode 100644index 00000000..6b979ea0--- /dev/null+++ b/tools/qa.py@@ -0,0 +1,263 @@+#!/usr/bin/env python3+"""One command, one short summary: the capture -> fix -> retest loop of a change.++usage: tools/qa.py [--build] [--unit] [--battery all|light|name,name] [--perf] [--notif N]+ [--save NAME] [--compare NAME] [--serial S]++ --build assemble the debug APK and install it (the app restarts)+ --unit unit tests of every module (count and failures)+ --battery phone playback scenarios (tools/playback_test.py); "light" = the fast ones+ --perf player screen, 12 s: frames, late frames, slow UI frames, app/renderer CPU+ --notif N N skips; after each, is there artwork in the media notification?+ --anim LABEL record the player opening and closing: a contact sheet of the frames+ (tools/qa-results/anim-LABEL.png, 12 per second) and the late frames+ --notif-mode plain|rapid|screenoff|cold how the N rounds skip (default plain): rapid = 5 skips+ in a burst, screenoff = skips with the screen asleep, cold = app killed and restarted+ --save NAME keep this run's numbers in tools/qa-results/NAME.json (ignored by git)+ --compare NAME print this run next to a saved one++Every phone step also counts Spotify's HTTP 429 on audio licences: a run that triggers them+is stopped, since more runs would only make Spotify's limit on the test account last.+Debug build only; one driver at a time on the phone.+"""+import argparse, glob, json, os, re, subprocess, sys, time++ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+sys.path.insert(0, os.path.join(ROOT, "tools"))+import playback_test as pt # noqa: E402++PKG = "app.myspoti.dev"+LIGHT = "play_playlist,next,rapid_next,rapid_swipe,seek,pause_resume,mute"+# A song of the test playlist without a Canvas: the player screen then shows only the bar moving.+STILL_TRACK = "spotify:track:0cIR7aXpYCI1eKXMglSMS7"+++def sh(*a, check=False, timeout=600):+ return subprocess.run(list(a), capture_output=True, text=True, timeout=timeout, check=check).stdout+++def adb(*a):+ return sh(pt.ADB, *(["-s", pt.SERIAL] if pt.SERIAL else []), *a)+++def licence_429():+ return sum(1 for l in adb("logcat", "-d", "-s", "Myspoti:*").splitlines() if "http 429" in l and "widevine" in l)+++def step_build(out):+ r = subprocess.run(["./gradlew", ":app:assembleDebug", "--console=plain", "-q"], cwd=os.path.join(ROOT, "base"),+ capture_output=True, text=True)+ errors = [l for l in (r.stdout + r.stderr).splitlines() if l.startswith("e: ") and "Incremental" not in l and "Daemon" not in l]+ if r.returncode != 0 and errors:+ out["build"] = "FAILED: " + " | ".join(errors[:3])+ return False+ inst = adb("install", "-r", os.path.join(ROOT, "base/app/build/outputs/apk/debug/app-debug.apk"))+ out["build"] = "ok, installed" if "Success" in inst else "built, install failed: " + inst.strip()[-120:]+ return "Success" in inst+++def step_unit(out):+ subprocess.run(["./gradlew", ":app:testDebugUnitTest", ":api-spotify:test", ":host-cdp:test",+ ":host-android:testDebugUnitTest", "--console=plain", "-q"], cwd=os.path.join(ROOT, "base"),+ capture_output=True, text=True)+ t = f = 0+ for p in glob.glob(os.path.join(ROOT, "base/*/build/test-results/*/*.xml")):+ m = re.search(r'tests="(\d+)" skipped="\d+" failures="(\d+)" errors="(\d+)"', open(p).read())+ if m:+ t += int(m[1]); f += int(m[2]) + int(m[3])+ out["unit"] = {"tests": t, "failed": f}+++def ensure_app():+ adb("shell", "monkey", "-p", PKG, "-c", "android.intent.category.LAUNCHER", "1")+ time.sleep(2)+ pt.wait_ready(60)+++def step_battery(out, which):+ names = LIGHT if which == "light" else ("" if which == "all" else which)+ cmd = [sys.executable, "-u", os.path.join(ROOT, "tools/playback_test.py")] + (["--serial", pt.SERIAL] if pt.SERIAL else [])+ if names:+ cmd += ["--only", names]+ r = subprocess.run(cmd, capture_output=True, text=True, timeout=1500)+ lines = [l for l in r.stdout.splitlines() if l.startswith(("PASS", "FAIL"))]+ out["battery"] = {"passed": sum(l.startswith("PASS") for l in lines), "total": len(lines),+ "failures": [l[:200] for l in lines if l.startswith("FAIL")]}+++def cpu(seconds):+ """% of one core used by the app process and its WebView renderer over [seconds]."""+ app = adb("shell", "pidof", PKG).strip()+ ren = [l.split()[0] for l in adb("shell", "ps", "-A", "-o", "PID,NAME").splitlines() if "sandboxed_process0" in l]+ def ticks():+ d = {}+ for p in [app] + ren:+ st = adb("shell", "cat", f"/proc/{p}/stat").split()+ if len(st) > 15:+ d[p] = int(st[13]) + int(st[14])+ return d+ a = ticks(); time.sleep(seconds); b = ticks()+ use = {p: (b[p] - a[p]) / 100 / seconds * 100 for p in a if p in b}+ return {"app": round(use.get(app, 0), 1), "renderer": round(max([use[p] for p in use if p != app] or [0]), 1)}+++def gfx():+ g = adb("shell", "dumpsys", "gfxinfo", PKG)+ num = lambda rx: int(re.search(rx, g).group(1)) if re.search(rx, g) else None+ return {"frames": num(r"Total frames rendered: (\d+)"), "late": num(r"Janky frames: (\d+)"),+ "slow_ui": num(r"Number Slow UI thread: (\d+)")}+++def step_perf(out):+ ensure_app()+ pt.test("play", track=STILL_TRACK + "|", context=pt.PLAYLIST)+ time.sleep(6)+ w, h = map(int, re.search(r"(\d+)x(\d+)", adb("shell", "wm", "size")).groups())+ adb("shell", "input", "tap", str(w * 28 // 100), str(h * 868 // 1000)) # the mini player+ time.sleep(3)+ adb("shell", "dumpsys", "gfxinfo", PKG, "reset")+ c = cpu(12)+ out["perf_player"] = {**gfx(), "per_s": 12, **{f"cpu_{k}": v for k, v in c.items()}}+ adb("shell", "input", "keyevent", "4")+++def notif_art():+ """(title, artwork width in px, 0 when none) of the app's media notification."""+ n = adb("shell", "dumpsys", "notification", "--noredact")+ blocks = [b for b in n.split("NotificationRecord(") if f"pkg={PKG}" in b[:200]]+ media = next((b for b in blocks if "MediaStyle" in b or "mediaSession" in b or "android.mediaSession" in b), None)+ if not media:+ return None, False+ title = re.search(r"android\.title=String \((.*?)\)", media)+ m = re.search(r"android\.largeIcon=Icon \(Icon\(typ=BITMAP size=(\d+)x(\d+)", media)+ return (title.group(1) if title else "?"), (int(m.group(1)) if m else 0)+++def step_notif(out, n, mode="plain"):+ ensure_app()+ # A freshly installed app restarts paused: no playback, no notification to measure.+ pt.test("resume")+ time.sleep(5)+ seen = []+ for i in range(n):+ early = None+ if mode == "cold":+ adb("shell", "am", "force-stop", PKG)+ time.sleep(1)+ pt.launch()+ time.sleep(2.5)+ pt.wait_ready(60)+ pt.test("resume")+ time.sleep(5)+ elif mode == "rapid":+ pt.key([pt.NEXT] * 5)+ time.sleep(1.5)+ early = notif_art()[1]+ time.sleep(6)+ elif mode == "screenoff":+ pt.key(pt.SLEEP)+ time.sleep(2)+ pt.key(pt.NEXT)+ time.sleep(1.5)+ early = notif_art()[1]+ time.sleep(3)+ else:+ pt.key(pt.NEXT)+ time.sleep(4)+ p = pt.probe()+ title, art = notif_art()+ if mode == "screenoff":+ pt.key(pt.WAKE)+ seen.append({"page": (p.get("track") or {}).get("name"), "notif": title, "art": art, "early_art": early})+ out["notification"] = {"mode": mode, "skips": n, "missing_art": sum(1 for s in seen if not s["art"]),+ "missing_art_early": sum(1 for s in seen if s["early_art"] == 0),+ "art_px": sorted({s["art"] for s in seen if s["art"]}),+ "title_mismatch": sum(1 for s in seen if s["page"] and s["notif"] and not s["notif"].startswith(s["page"])),+ "samples": [s for s in seen if not s["art"] or (s["page"] and s["notif"] and not s["notif"].startswith(s["page"]))][:4]}+++def step_anim(out, label):+ """Opens then closes the player while recording the screen: one contact sheet of the+ frames (tools/qa-results/anim-<label>.png) and the late frames of the two transitions."""+ # No playback needed (the mini player shows the last song): no audio licence is asked for,+ # so this runs even while Spotify limits the test account.+ ensure_app()+ time.sleep(3)+ w, h = map(int, re.search(r"(\d+)x(\d+)", adb("shell", "wm", "size")).groups())+ adb("shell", "dumpsys", "gfxinfo", PKG, "reset")+ rec = subprocess.Popen([pt.ADB, "-s", pt.SERIAL, "shell", "screenrecord", "--time-limit", "4",+ "--size", f"{w // 2}x{h // 2}", "/sdcard/qa-anim.mp4"])+ time.sleep(0.8)+ adb("shell", "input", "tap", str(w * 28 // 100), str(h * 868 // 1000)) # open (the mini player)+ time.sleep(1.4)+ adb("shell", "input", "keyevent", "4") # close+ rec.wait(timeout=15)+ out["anim_frames"] = gfx()+ keep = os.path.join(ROOT, "tools", "qa-results"); os.makedirs(keep, exist_ok=True)+ mp4 = os.path.join(keep, "anim.mp4")+ adb("pull", "/sdcard/qa-anim.mp4", mp4)+ frames = os.path.join(keep, "frames"); os.makedirs(frames, exist_ok=True)+ for old in glob.glob(os.path.join(frames, "*.png")):+ os.remove(old)+ # 12 frames a second from the tap (0.8 s) to past the close (~2.8 s): both transitions.+ subprocess.run(["ffmpeg", "-loglevel", "error", "-ss", "0.75", "-t", "2.2", "-i", mp4, "-vf", "fps=12,scale=180:-1",+ os.path.join(frames, "f%02d.png")], check=False)+ from PIL import Image+ shots = sorted(glob.glob(os.path.join(frames, "*.png")))+ if shots:+ ims = [Image.open(p) for p in shots]+ cols = 9; cw, ch = ims[0].size; rows = (len(ims) + cols - 1) // cols+ sheet = Image.new("RGB", (cols * cw, rows * ch))+ for i, im in enumerate(ims):+ sheet.paste(im, ((i % cols) * cw, (i // cols) * ch))+ path = os.path.join(keep, f"anim-{label}.png")+ sheet.save(path)+ out["anim_sheet"] = path+++def main():+ ap = argparse.ArgumentParser()+ ap.add_argument("--serial")+ ap.add_argument("--build", action="store_true")+ ap.add_argument("--unit", action="store_true")+ ap.add_argument("--battery")+ ap.add_argument("--perf", action="store_true")+ ap.add_argument("--notif", type=int, default=0)+ ap.add_argument("--anim", help="label: record the player opening/closing (contact sheet + late frames)")+ ap.add_argument("--notif-mode", default="plain", choices=["plain", "rapid", "screenoff", "cold"])+ ap.add_argument("--save")+ ap.add_argument("--compare")+ a = ap.parse_args()+ pt.SERIAL = a.serial or next((l.split()[0] for l in sh(pt.ADB, "devices").splitlines()[1:] if l.endswith("device")), None)+ out = {}+ if a.unit:+ step_unit(out)+ if a.build and not step_build(out):+ print(json.dumps(out, ensure_ascii=False, indent=1)); sys.exit(1)+ phone = a.battery or a.perf or a.notif or a.anim+ if phone:+ adb("logcat", "-c")+ for name, run in (("battery", lambda: step_battery(out, a.battery)), ("perf", lambda: step_perf(out)),+ ("notif", lambda: step_notif(out, a.notif, a.notif_mode)), ("anim", lambda: step_anim(out, a.anim))):+ if not {"battery": a.battery, "perf": a.perf, "notif": a.notif, "anim": a.anim}[name]:+ continue+ run()+ n = licence_429()+ if n >= 6:+ out["stopped"] = f"Spotify limits the test account ({n} licence 429): no more phone steps"+ break+ if phone:+ out["licence_429"] = licence_429()+ print(json.dumps(out, ensure_ascii=False, indent=1))+ keep = os.path.join(ROOT, "tools", "qa-results")+ if a.save:+ os.makedirs(keep, exist_ok=True)+ json.dump(out, open(os.path.join(keep, a.save + ".json"), "w"), ensure_ascii=False, indent=1)+ if a.compare:+ before = json.load(open(os.path.join(keep, a.compare + ".json")))+ print("--- before (" + a.compare + "):")+ print(json.dumps({k: before.get(k) for k in out}, ensure_ascii=False, indent=1))+++if __name__ == "__main__":+ main()