Skip to content

Native Android client for Spotify, built with Jetpack Compose

Playback that holds: an ad or a song loading keeps the service in front, its locks and the app open when closed (cuts after a while on free accounts, Android 17 background audio); a failed speaker keep-alive opens again; the media session marks its queue row only when it is the song shown (AVRCP updates on cars and bikes, #151), tells play and pause at once (#108) and keeps the last song after a restart (#142); Android Auto gets a Podcasts tab and podcasts in search; on Cast and Connect devices an ad plays at volume 0 and the volume comes back after it (#153)

kota-zoec57990a6a44
diff --git a/base/app/src/main/java/com/music/spotui/connect/RemoteAdMute.kt b/base/app/src/main/java/com/music/spotui/connect/RemoteAdMute.kt
new file mode 100644
index 00000000..0d07e612
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/connect/RemoteAdMute.kt
@@ -0,0 +1,184 @@
+package com.music.spotui.connect
+
+import app.myspoti.host.android.Logbook
+import app.myspoti.host.android.MyspotiRuntime
+import com.music.spotui.di.Graph
+import com.music.spotui.di.SongPlayer
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.NonCancellable
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.flow.collectLatest
+import kotlinx.coroutines.flow.combine
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.withContext
+
+/**
+ * Ads on a device the music was sent to (#153). Moved there with Spotify Connect (a Cast
+ * speaker woken by [com.music.spotui.cast.CastSpotify], a Denon/HEOS receiver, any Connect
+ * device), the songs are played by Spotify on that device itself: its ads too, which no host
+ * on the phone can refuse. The page here only follows that device, and it does see the ad (the
+ * player's ad flag, which the screens show as "Advertisement").
+ *
+ * What an ad muter does with a desktop client is done here with the device's volume, through
+ * the same Connect volume command as the player's volume bar: set to 0 when an ad comes on the
+ * device picked in Myspoti, and the level it had set back once the break is over. Nothing is
+ * skipped and no event is sent: the ad plays to its end, unheard.
+ *
+ * Guards: the user's own volume change during the break ends the mute (their level stands); a
+ * break that has not ended after [MAX_MUTE_MS] (some players are said to hold a silenced ad)
+ * gets its sound back and that device is no longer muted until the app restarts; a device that
+ * left before the break ended gets its level back the next time it plays. Never a device
+ * with a fixed volume, nor a Jam host's device.
+ */
+object RemoteAdMute {
+ /** Longer than any break seen (two 30 s ads); past it the sound comes back. */
+ const val MAX_MUTE_MS = 90_000L
+ /** A restore kept over an app restart is dropped after this. */
+ private const val OWED_MAX_AGE_MS = 24 * 3600_000L
+
+ /** The decisions, without Android or the page (tested). */
+ internal object Rules {
+ /**
+ * Whether the ad now on is muted: an [ad] on the device that plays ([elsewhere], [activeId]),
+ * which is the one picked in Myspoti ([chosenId]), with a [level] above 0 (a device with a
+ * fixed volume reports none, or a negative one), outside a Jam joined as a member, and not
+ * a device whose muted ad never ended ([setAside]).
+ */
+ fun mutes(
+ ad: Boolean, elsewhere: Boolean, activeId: String?, chosenId: String?, level: Double?,
+ jamMember: Boolean, setAside: Set<String>,
+ ): Boolean =
+ ad && elsewhere && activeId != null && activeId == chosenId && !activeId.startsWith("social-connect") &&
+ !jamMember && level != null && level > 0.0 && activeId !in setAside
+
+ /** The level a device is reported at (0..1), else the one the player's volume bar shows (0..100). */
+ fun levelOf(reported: Double?, shown: Int): Double? = when {
+ reported == null -> shown.takeIf { it > 0 }?.let { it / 100.0 }
+ reported <= 0.0 -> null
+ else -> reported.coerceAtMost(1.0)
+ }
+
+ /** Whether a restore owed to [owedId] since [owedAt] is done now, [activeId] playing at [now]. */
+ fun restoresOwed(owedId: String?, owedAt: Long, activeId: String?, ad: Boolean, now: Long): Boolean =
+ owedId != null && owedId == activeId && !ad && now - owedAt < OWED_MAX_AGE_MS
+ }
+
+ private class Muted(val deviceId: String, val level: Double, val at: Long)
+
+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
+ @Volatile private var started = false
+ /** The device muted for the break on now. */
+ @Volatile private var muted: Muted? = null
+ /** A device muted for a break it left before the end: its level waits for it. */
+ @Volatile private var owed: Muted? = null
+ private val setAside = java.util.Collections.synchronizedSet(mutableSetOf<String>())
+
+ /** A device is muted for an ad: the volume it reports is not the user's (see SongPlayer.refreshDevice). */
+ val muting: Boolean get() = muted != null
+
+ private val prefs get() = Graph.app.getSharedPreferences("remote_ad_mute", android.content.Context.MODE_PRIVATE)
+
+ /** Follows the player's ad flag (once, when the player is attached). */
+ fun start() {
+ if (started) return
+ started = true
+ // The app went away during a muted break: the level is still owed.
+ runCatching {
+ val p = prefs
+ val id = p.getString("device", null)
+ if (id != null) owed = Muted(id, p.getFloat("level", 1f).toDouble(), p.getLong("at", 0L))
+ }
+ scope.launch {
+ // The engine may start after the player is attached.
+ while (!MyspotiRuntime.isStarted) delay(1_000)
+ val player = MyspotiRuntime.spotify.player
+ combine(player.adPlaying, player.playsElsewhere) { ad, elsewhere -> ad to elsewhere }
+ .collectLatest { (ad, elsewhere) -> runCatching { onChange(ad, elsewhere) } }
+ }
+ }
+
+ /**
+ * The user set the volume of the device that plays: their level stands, nothing is restored
+ * over it. True when that device was muted here (the level must then be sent even if unchanged).
+ */
+ fun userSetVolume(): Boolean {
+ val m = muted ?: owed?.takeIf { it.deviceId == SongPlayer.activeDevice.value?.id } ?: return false
+ if (muted === m) muted = null
+ if (owed === m) owed = null
+ forget()
+ log("volume set by the user during the ad: left to them")
+ return true
+ }
+
+ private suspend fun onChange(ad: Boolean, elsewhere: Boolean) {
+ val api = MyspotiRuntime.api
+ muted?.let { m ->
+ if (ad) { holdUntilTooLong(m); return }
+ restore(m, "break over")
+ return
+ }
+ owed?.let { o ->
+ if (!elsewhere || ad) return@let
+ runCatching { api.devices.refresh() }
+ val activeId = api.devices.devices.value.firstOrNull { it.active }?.id
+ if (Rules.restoresOwed(o.deviceId, o.at, activeId, ad, System.currentTimeMillis())) {
+ runCatching { api.player.setVolume(o.level) }
+ .onSuccess { if (owed === o) owed = null; forget(); log("level put back on a device muted for an earlier ad") }
+ } else if (System.currentTimeMillis() - o.at >= OWED_MAX_AGE_MS) { owed = null; forget() }
+ }
+ if (!ad || !elsewhere) return
+ runCatching { api.devices.refresh() }
+ val active = api.devices.devices.value.firstOrNull { it.active && !it.local } ?: return
+ val level = Rules.levelOf(active.volume, SongPlayer.remoteVolume)
+ val jamMember = api.jam.session.value?.isHost == false
+ if (!Rules.mutes(ad, elsewhere, active.id, SongPlayer.chosenRemoteId, level, jamMember, setAside)) return
+ val m = Muted(active.id, level!!, System.currentTimeMillis())
+ muted = m
+ remember(m)
+ val sent = runCatching { api.player.setVolume(0.0) }
+ if (sent.isFailure) {
+ muted = null
+ forget()
+ log("ad on a ${active.type.lowercase()}: volume not set (${sent.exceptionOrNull()?.message?.take(80)})")
+ return
+ }
+ log("ad on a ${active.type.lowercase()}: muted for the break")
+ holdUntilTooLong(m)
+ }
+
+ /** Returns only when the break is cut short by the next change; past [MAX_MUTE_MS] the sound comes back. */
+ private suspend fun holdUntilTooLong(m: Muted) {
+ val left = MAX_MUTE_MS - (System.currentTimeMillis() - m.at)
+ if (left > 0) delay(left)
+ if (muted !== m) return
+ setAside.add(m.deviceId)
+ restore(m, "the ad still on after ${MAX_MUTE_MS / 1000} s, this device is no longer muted")
+ }
+
+ /** The device's level back, when it still plays; otherwise owed to it. Not cancelled midway. */
+ private suspend fun restore(m: Muted, why: String) = withContext(NonCancellable) {
+ if (muted !== m) return@withContext
+ muted = null
+ val api = MyspotiRuntime.api
+ runCatching { api.devices.refresh() }
+ val activeId = api.devices.devices.value.firstOrNull { it.active }?.id
+ if (activeId != m.deviceId) {
+ owed = m
+ log("$why: the device no longer plays, its level is put back when it does")
+ return@withContext
+ }
+ val sent = runCatching { api.player.setVolume(m.level) }
+ if (sent.isSuccess) { forget(); log("$why: level put back") }
+ else { owed = m; log("$why: level not put back (${sent.exceptionOrNull()?.message?.take(80)}), tried again later") }
+ }
+
+ private fun remember(m: Muted) = runCatching {
+ prefs.edit().putString("device", m.deviceId).putFloat("level", m.level.toFloat()).putLong("at", m.at).apply()
+ }
+
+ private fun forget() = runCatching { prefs.edit().clear().apply() }
+
+ private fun log(line: String) = Logbook.log("connect: ad mute: $line")
+}
diff --git a/base/app/src/main/java/com/music/spotui/di/AutoBrowser.kt b/base/app/src/main/java/com/music/spotui/di/AutoBrowser.kt
index 67483e6b..f33dfb1a 100644
--- a/base/app/src/main/java/com/music/spotui/di/AutoBrowser.kt
+++ b/base/app/src/main/java/com/music/spotui/di/AutoBrowser.kt
@@ -34,13 +34,14 @@ class AudioNotReady(what: String) : IllegalStateException("player not ready: $wh
* Android Auto / media browser tree, built from the app's own data (not the web page).
*
* Root tabs (Auto allows four): Home (recently played, then the home feed's shelves, each a titled
- * group), Library (Liked Songs, playlists, albums, artists), Downloads (served from the files,
- * no network needed). Search answers songs, playlists, albums and artists as titled groups.
+ * group), Library (Liked Songs, playlists, albums, artists), Podcasts (New episodes, then the
+ * followed shows), Downloads (served from the files, no network needed). Search answers songs,
+ * playlists, albums, artists, podcasts and episodes as titled groups.
* Tapping a song plays it in its context, the way the album / playlist screens do: a downloaded
* song plays the local copy (see [playTrack]). "Start radio" items start Spotify's radio.
*
- * Media ids: "home", "library", "downloads" (tabs); "liked", "playlists", "albums", "artists",
- * "dsongs" (lists); "pl:<id>", "al:<id>", "ar:<id>|<name>", "dl:<list uri>" (contexts);
+ * Media ids: "home", "library", "podcasts", "downloads" (tabs); "liked", "playlists", "albums", "artists",
+ * "dsongs", "newep" (lists); "pl:<id>", "al:<id>", "ar:<id>|<name>", "dl:<list uri>", "sh:<show id>" (contexts);
* "t|<context uri>|<play key>" (a song), "d|<list uri or empty>|<track id>" (a downloaded song),
* "radio|<seed uri>|<fallback song uri>" (start a radio).
*/
@@ -72,6 +73,8 @@ object AutoBrowser {
override fun removeEldestEntry(eldest: MutableMap.MutableEntry<String, ContextPageModel>) = size > MAX_PAGES
})
private const val MAX_PAGES = 30
+ /** [ContextPageModel.type] of a show's episodes listed here. */
+ private const val SHOW = "show"
/** The account signs out: nothing it listed stays for the next one. */
fun clearSession() = pages.clear()
@@ -88,6 +91,7 @@ object AutoBrowser {
parentId == ROOT -> return listOf(
tab(context, "home", R.string.aa_home, "aa_ic_home", STYLE_GRID),
tab(context, "library", R.string.aa_library, "aa_ic_library", STYLE_LIST),
+ tab(context, "podcasts", R.string.recents_filter_podcasts, "aa_ic_podcasts", STYLE_LIST),
tab(context, "downloads", R.string.aa_downloads, "aa_ic_downloads", STYLE_LIST),
)
parentId == "library" -> return libraryTab(context)
@@ -111,6 +115,9 @@ object AutoBrowser {
parentId == "artists" -> Graph.api.getFollowedArtists().filter { it.id.isNotBlank() }.take(MAX_ITEMS).map { a ->
browsable("ar:${a.id}|${a.name}", a.name, art(a.coverUri))
}
+ parentId == "podcasts" -> podcastsTab(context)
+ parentId == "newep" -> Graph.api.getNewEpisodes().take(MAX_ITEMS).map { playable("", it) }
+ parentId.startsWith("sh:") -> showEpisodes(parentId.removePrefix("sh:"))
parentId == "liked" -> tracksOf(context, firstResult { Graph.api.getLikedPage() })
parentId.startsWith("pl:") -> tracksOf(context, firstResult { Graph.api.getPlaylistPage(parentId.removePrefix("pl:")) })
parentId.startsWith("al:") -> tracksOf(context, firstResult { Graph.api.getAlbumPage(parentId.removePrefix("al:")) })
@@ -144,6 +151,35 @@ object AutoBrowser {
browsable("artists", context.getString(R.string.aa_artists), resource(context, "aa_ic_artists"), grid = false),
)
+ /**
+ * "New episodes" (the episodes not played yet of the followed shows), then the followed shows
+ * (the phone's Library > Podcasts). Spotify not answering is an error, not an empty tab.
+ */
+ private suspend fun podcastsTab(context: Context): List<MediaItem> {
+ val entries = Graph.api.followedShows().getOrElse { throw AudioNotReady("podcasts: ${it.message}") }
+ val shows = context.getString(R.string.recents_filter_podcasts)
+ return entries.take(MAX_ITEMS).mapNotNull { e ->
+ val showPrefix = com.music.spotui.data.api.Api.SHOW_PREFIX
+ when {
+ e.spotifyId == com.music.spotui.data.api.Api.NEW_EPISODES_ID ->
+ browsable("newep", e.name, art(e.coverUri), subtitle = e.subtitle, grid = false)
+ e.spotifyId.startsWith(showPrefix) ->
+ browsable("sh:" + e.spotifyId.removePrefix(showPrefix), e.name, art(e.coverUri), subtitle = e.subtitle, grid = false, group = shows)
+ else -> null
+ }
+ }
+ }
+
+ /** A show's latest episodes (the first page, newest first); a tap plays the episode in its show, as the show screen does. */
+ private suspend fun showEpisodes(showId: String): List<MediaItem> {
+ val episodes = firstResult { Graph.api.getShowEpisodes(showId) }.orEmpty()
+ if (episodes.isEmpty()) return emptyList()
+ val page = ContextPageModel(uri = "spotify:show:$showId", type = SHOW, name = episodes.first().album,
+ coverUri = episodes.first().coverUri, tracks = episodes.take(MAX_ITEMS))
+ pages[page.uri] = page
+ return page.tracks.map { playable(page.uri, it) }
+ }
+
/** Recently played, then the home feed's shelves (mixes, jump back in, …), each a titled group. */
private suspend fun homeTab(context: Context): List<MediaItem> = kotlinx.coroutines.coroutineScope {
val recents = async { runCatching { recentItems(context) }.getOrDefault(emptyList()) }
@@ -238,7 +274,8 @@ object AutoBrowser {
suspend fun search(query: String): List<MediaItem> {
if (!awaitPlayer()) throw AudioNotReady("search")
- val r = firstResult { Graph.api.searchEverything(query) } ?: return emptyList()
+ // The last answer: the music comes first, the podcasts and episodes in a second one.
+ val r = lastResult { Graph.api.searchEverything(query) } ?: return emptyList()
val context = Graph.app
val songs = r.songs.take(10)
val out = ArrayList<MediaItem>()
@@ -257,6 +294,12 @@ object AutoBrowser {
r.artists.filter { it.id.isNotBlank() }.take(8).forEach {
out += browsable("ar:${it.id}|${it.name}", it.name, art(it.coverUri), group = artists)
}
+ val podcasts = context.getString(R.string.recents_filter_podcasts)
+ r.shows.filter { it.id.isNotBlank() }.take(8).forEach {
+ out += browsable("sh:${it.id}", it.name, art(it.coverUri), subtitle = it.publisher, group = podcasts)
+ }
+ val episodes = context.getString(R.string.show_tab_episodes)
+ r.episodes.take(8).forEach { out += playable("", it, episodes) }
return out
}
@@ -319,7 +362,8 @@ object AutoBrowser {
}
// The list's songs: an audio-source extension then plays the list on from the song, as on
// the phone, instead of the song alone and its radio. Spotify plays the context anyway.
- SongPlayer.playSong(key, contextUri = contextUri, songs = page?.tracks)
+ // A show's episodes play in the show, as on its screen: Spotify's queue, never the extensions'.
+ SongPlayer.playSong(key, contextUri = contextUri, songs = page?.tracks?.takeIf { page.type != SHOW })
song?.let { Graph.currentSongState.updateSongState(it.coverUri, it.title, it.singer, true, it.id, 0, it.album) }
}
@@ -360,6 +404,13 @@ object AutoBrowser {
return radio + page.tracks.take(MAX_ITEMS).map { playable(page.uri, it, songs) }
}
+ /** The last answer of [load] within [TIMEOUT_MS] (a flow that answers in steps); null when none came. */
+ private suspend fun <T> lastResult(load: suspend () -> kotlinx.coroutines.flow.Flow<Response<T>>): T? {
+ var last: T? = null
+ withTimeoutOrNull(TIMEOUT_MS) { load().collect { if (it is Response.Success) last = it.data } }
+ return last
+ }
+
private suspend fun <T> firstResult(load: suspend () -> kotlinx.coroutines.flow.Flow<Response<T>>): T? =
withTimeoutOrNull(TIMEOUT_MS) {
(load().first { it !is Response.Loading } as? Response.Success)?.data
diff --git a/base/app/src/main/java/com/music/spotui/di/SongPlayer.kt b/base/app/src/main/java/com/music/spotui/di/SongPlayer.kt
index 8a3533cc..faf3f9fa 100644
--- a/base/app/src/main/java/com/music/spotui/di/SongPlayer.kt
+++ b/base/app/src/main/java/com/music/spotui/di/SongPlayer.kt
@@ -294,6 +294,8 @@ object SongPlayer {
}
}
scope.launch { MyspotiRuntime.spotify.player.stalled.collect { on -> onSoundStalled(on) } }
+ // Ads on a Connect device the music was sent to are muted there (#153).
+ com.music.spotui.connect.RemoteAdMute.start()
// Smart shuffle plays a mixed order as the list and leaves Spotify's own shuffle off, so
// turning it off sends no shuffle command at all (the button finds shuffle already off):
// the list's own order comes back here.
@@ -365,8 +367,11 @@ object SongPlayer {
/** System controls (notification, headset, car) land here. */
private object Controls : app.myspoti.host.android.PlaybackControls {
- override fun play() = SongPlayer.play(by = "media session")
- override fun pause() = SongPlayer.pause(by = "media session")
+ // The session says the new state at once, not when the page answers: a Bluetooth headset or
+ // stereo reads it (AVRCP play status) to choose between play and pause, and kept sending
+ // "pause" to a paused player while the session still said playing (#108).
+ override fun play() { SongPlayer.play(by = "media session"); pushNotification(null, boundState?.likeState?.value ?: false) }
+ override fun pause() { SongPlayer.pause(by = "media session"); pushNotification(null, boundState?.likeState?.value ?: false) }
override fun next() = SongPlayer.next(by = "media session")
override fun previous() = SongPlayer.previous(by = "media session")
override fun seekTo(ms: Long) = SongPlayer.seekTo(ms)
@@ -430,6 +435,14 @@ object SongPlayer {
album = p.getString("album", "").orEmpty(),
)
state.likeState.value = p.getBoolean("liked", false)
+ // The media session has the last song, paused, before anything plays: a car or a Bluetooth
+ // stereo that binds first (after the app was killed too) shows it and can resume it (#142).
+ PlaybackService.update(Graph.app, NowPlayingInfo(
+ id = uri, title = title, artist = p.getString("singer", "").orEmpty(), album = p.getString("album", "").orEmpty(),
+ coverUrl = p.getString("cover", "").orEmpty().ifBlank { null }, durationMs = durationMs, positionMs = positionMs,
+ playing = false, liked = state.likeState.value, shuffle = state.shuffle.value == true,
+ episode = uri.startsWith("spotify:episode:"),
+ ))
// Spotify's own queue too: the page's replaces it once it reports.
val rest = com.music.spotui.data.preferences.LastSession.decodeQueue(p.getString("queue", null))
if (rest.isNotEmpty()) {
@@ -2317,7 +2330,8 @@ object SongPlayer {
val active = api.devices.devices.value.firstOrNull { it.active }
_activeDevice.value = active?.takeIf { !it.local }?.let { ConnectDevice(it.id, it.name, it.type, false, true) }
// A negative volume is a device with a fixed one (Web Player: disable_volume): not 0 %.
- active?.volume?.takeIf { it >= 0 }?.let { if (SystemClock.elapsedRealtime() > volumeHoldUntil) _remoteVolume.intValue = (it * 100).toInt().coerceIn(0, 100) }
+ // Nor the 0 of a device muted for an ad (RemoteAdMute): the bar keeps the user's level.
+ active?.volume?.takeIf { it >= 0 }?.let { if (SystemClock.elapsedRealtime() > volumeHoldUntil && !com.music.spotui.connect.RemoteAdMute.muting) _remoteVolume.intValue = (it * 100).toInt().coerceIn(0, 100) }
PlaybackService.setPlaybackDevice(_activeDevice.value != null, remoteVolume)
}
}
@@ -2338,6 +2352,8 @@ object SongPlayer {
/** The other device picked in Myspoti to play on; null: this phone. */
@Volatile private var chosenRemote: String? = null
+ /** [chosenRemote], read by RemoteAdMute (only that device's ads are muted). */
+ val chosenRemoteId: String? get() = chosenRemote
/**
* Another device took playback without being picked here (the Spotify app opened on the
@@ -2474,6 +2490,12 @@ object SongPlayer {
_remoteVolume.intValue = volume.coerceIn(0, 100)
volumeHoldUntil = SystemClock.elapsedRealtime() + 1500
volumeSender
+ // A device muted for an ad is at 0 whatever the bar says: the same level as the last one sent
+ // would not go out through [volumeToSend], so it is sent here.
+ if (com.music.spotui.connect.RemoteAdMute.userSetVolume()) {
+ val v = remoteVolume
+ scope.launch { runCatching { api.player.setVolume(v / 100.0) } }
+ }
volumeToSend.value = remoteVolume
PlaybackService.setPlaybackDevice(_activeDevice.value != null, remoteVolume)
}
diff --git a/base/app/src/main/java/com/music/spotui/di/SpeakerKeepAlive.kt b/base/app/src/main/java/com/music/spotui/di/SpeakerKeepAlive.kt
index 155e81be..1aea95ee 100644
--- a/base/app/src/main/java/com/music/spotui/di/SpeakerKeepAlive.kt
+++ b/base/app/src/main/java/com/music/spotui/di/SpeakerKeepAlive.kt
@@ -17,11 +17,15 @@ object SpeakerKeepAlive {
private const val RATE = 48_000
/** Pauses and song changes shorter than this keep the stream (and the output) open. */
private const val LINGER_MS = 15_000L
+ /** A stream that failed is opened again after this long at the soonest. */
+ private const val RETRY_MS = 10_000L
private val main = Handler(Looper.getMainLooper())
@Volatile private var track: AudioTrack? = null
@Volatile private var feeder: Thread? = null
private val release = Runnable { stop() }
+ /** When the last stream failed (see [start]); 0: none. */
+ @Volatile private var failedAt = 0L
/** [playingHere]: music plays on this phone (not on a Connect device). */
fun set(playingHere: Boolean) = main.post {
@@ -36,6 +40,8 @@ object SpeakerKeepAlive {
private fun start() {
if (track != null) return
+ // A stream that just failed is not rebuilt on every state the page reports.
+ if (failedAt != 0L && android.os.SystemClock.elapsedRealtime() - failedAt < RETRY_MS) return
// A second of buffer, written half at a time: two wakes a second instead of 25 to 50 with the
// minimum buffer (silence needs no low latency).
val size = maxOf(AudioTrack.getMinBufferSize(RATE, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT), RATE * 2)
@@ -61,6 +67,10 @@ object SpeakerKeepAlive {
val zeros = ByteArray(size / 2)
// Blocking writes pace themselves on the output: no busy loop.
while (track === t) if (t.write(zeros, 0, zeros.size) < 0) break
+ // The stream failed (the audio server restarted, the output went away): it is let go,
+ // and the next song playing opens a new one. Kept, it held its place for the rest of
+ // the session while feeding nothing, and nothing held the output open any more.
+ if (track === t) main.post { if (track === t) { failedAt = android.os.SystemClock.elapsedRealtime(); stop() } }
}, "speaker-keepalive").apply { isDaemon = true; start() }
}
diff --git a/base/app/src/main/res/drawable/aa_ic_podcasts.xml b/base/app/src/main/res/drawable/aa_ic_podcasts.xml
new file mode 100644
index 00000000..c5643ec7
--- /dev/null
+++ b/base/app/src/main/res/drawable/aa_ic_podcasts.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Android Auto icon: Material Icons "mic" (Google, Apache License 2.0). Tinted by the car on tabs. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp"
+ android:viewportWidth="24" android:viewportHeight="24">
+ <path android:fillColor="#FFFFFFFF" android:pathData="M12,14c1.66,0 2.99,-1.34 2.99,-3L15,5c0,-1.66 -1.34,-3 -3,-3S9,3.34 9,5v6c0,1.66 1.34,3 3,3zM17.3,11c0,3 -2.54,5.1 -5.3,5.1S6.7,14 6.7,11L5,11c0,3.41 2.72,6.23 6,6.72L11,21h2v-3.28c3.28,-0.48 6,-3.3 6,-6.72h-1.7z" />
+</vector>
diff --git a/base/app/src/test/java/com/music/spotui/connect/RemoteAdMuteTest.kt b/base/app/src/test/java/com/music/spotui/connect/RemoteAdMuteTest.kt
new file mode 100644
index 00000000..7fd0bed2
--- /dev/null
+++ b/base/app/src/test/java/com/music/spotui/connect/RemoteAdMuteTest.kt
@@ -0,0 +1,55 @@
+package com.music.spotui.connect
+
+import com.music.spotui.connect.RemoteAdMute.Rules
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class RemoteAdMuteTest {
+ private fun mutes(
+ ad: Boolean = true, elsewhere: Boolean = true, activeId: String? = "denon", chosenId: String? = "denon",
+ level: Double? = 0.4, jamMember: Boolean = false, setAside: Set<String> = emptySet(),
+ ) = Rules.mutes(ad, elsewhere, activeId, chosenId, level, jamMember, setAside)
+
+ @Test fun anAdOnThePickedDeviceIsMuted() = assertTrue(mutes())
+
+ @Test fun noAdOrAnAdOnThisPhoneIsLeftAlone() {
+ assertFalse(mutes(ad = false))
+ assertFalse(mutes(elsewhere = false))
+ }
+
+ @Test fun onlyTheDevicePickedInMyspoti() {
+ assertFalse(mutes(chosenId = null))
+ assertFalse(mutes(chosenId = "desktop"))
+ assertFalse(mutes(activeId = null))
+ }
+
+ @Test fun neverAJamOrADeviceWithoutVolume() {
+ assertFalse(mutes(jamMember = true))
+ assertFalse(mutes(activeId = "social-connect-1", chosenId = "social-connect-1"))
+ assertFalse(mutes(level = null))
+ assertFalse(mutes(level = 0.0))
+ }
+
+ @Test fun aDeviceWhoseMutedAdNeverEndedIsSetAside() = assertFalse(mutes(setAside = setOf("denon")))
+
+ @Test fun theLevelIsTheReportedOneElseTheBars() {
+ assertEquals(0.4, Rules.levelOf(0.4, 80)!!, 1e-9)
+ assertEquals(0.8, Rules.levelOf(null, 80)!!, 1e-9)
+ assertNull(Rules.levelOf(null, 0))
+ // A fixed volume (negative) or a device already at 0: nothing to mute or restore.
+ assertNull(Rules.levelOf(-1.0, 80))
+ assertNull(Rules.levelOf(0.0, 80))
+ }
+
+ @Test fun anOwedLevelGoesBackWhenItsDevicePlaysWithoutAnAd() {
+ val now = 1_000_000L
+ assertTrue(Rules.restoresOwed("denon", now - 5_000, "denon", ad = false, now = now))
+ assertFalse(Rules.restoresOwed("denon", now - 5_000, "phone", ad = false, now = now))
+ assertFalse(Rules.restoresOwed("denon", now - 5_000, "denon", ad = true, now = now))
+ assertFalse(Rules.restoresOwed(null, now, "denon", ad = false, now = now))
+ assertFalse(Rules.restoresOwed("denon", now - 25 * 3600_000L, "denon", ad = false, now = now + 0))
+ }
+}
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.kt
index 4b274895..b6486038 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
@@ -53,10 +53,24 @@ data class NowPlayingInfo(
/** A podcast episode: the notification offers 15 s skips, the headset next / previous skip 15 s. */
val episode: Boolean = false,
) {
+ /**
+ * Audio goes on, or is about to: a song plays or loads, or an ad break runs. An ad is shown
+ * "paused" ([playing] false, for the screens) but the page plays it (muted) and the app is busy
+ * getting past it: the service keeps the foreground and its locks then, or a break over a
+ * minute let Android freeze the app (cached apps freezer, Android 14+) and, on Android 17,
+ * silence a player with no foreground service (background audio hardening).
+ */
+ val makesSound: Boolean get() = playing || buffering || id == AD_ID
+
/** Everything but the position: a moving position alone is not a new state. */
fun sameAs(other: NowPlayingInfo) = id == other.id && title == other.title && artist == other.artist &&
album == other.album && coverUrl == other.coverUrl && durationMs == other.durationMs &&
playing == other.playing && buffering == other.buffering && liked == other.liked && shuffle == other.shuffle && episode == other.episode
+
+ companion object {
+ /** The [id] the app gives an ad break (the screens then say "Advertisement"). */
+ const val AD_ID = "spotify:ad"
+ }
}
/**
@@ -144,6 +158,7 @@ class PlaybackService : MediaBrowserServiceCompat() {
// The paused notification was swiped away: leave the foreground with it.
if (info?.playing != true && isStop(intent)) {
handler.removeCallbacks(leaveForeground)
+ holdLocks(false)
ServiceCompat.stopForeground(this, ServiceCompat.STOP_FOREGROUND_REMOVE)
foreground = false
}
@@ -170,7 +185,8 @@ class PlaybackService : MediaBrowserServiceCompat() {
* notification goes with the service.
*/
override fun onTaskRemoved(rootIntent: Intent?) {
- if (current?.playing == true && !playingRemote && !keepsPlayingOnClose(this)) {
+ // An ad or a song loading counts as playing: closing the app then stopped the service under it.
+ if (current?.makesSound == true && !playingRemote && !keepsPlayingOnClose(this)) {
controls?.pause()
handler.postDelayed({
ServiceCompat.stopForeground(this, ServiceCompat.STOP_FOREGROUND_REMOVE)
@@ -179,7 +195,7 @@ class PlaybackService : MediaBrowserServiceCompat() {
}, CLOSE_STOP_MS)
return
}
- if (current?.playing != true) stopSelf()
+ if (current?.makesSound != true) stopSelf()
}
/** A Spotify Connect device plays (the session's volume is that device's). */
@@ -307,7 +323,7 @@ class PlaybackService : MediaBrowserServiceCompat() {
.addCustomAction(ACTION_SHUFFLE, getString(if (info.shuffle) R.string.msp_shuffle_off else R.string.msp_shuffle_on),
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)
- .setActiveQueueItemId(activeQueueId)
+ .setActiveQueueItemId(QueueSync.activeRow(queue, activeQueueId, info.title, info.artist))
.build())
}
@@ -322,9 +338,11 @@ class PlaybackService : MediaBrowserServiceCompat() {
.build(), e.id)
}.takeIf { it.isNotEmpty() })
// Only the marked row changes: the rest of the state (and its position clock) stays as it was.
+ // A row that is not the song shown is not marked (see QueueSync: Bluetooth holds its updates).
val state = session.controller.playbackState ?: return
- if (state.activeQueueItemId != activeQueueId) {
- session.setPlaybackState(PlaybackStateCompat.Builder(state).setActiveQueueItemId(activeQueueId).build())
+ val active = QueueSync.activeRow(queue, activeQueueId, current?.title, current?.artist)
+ if (state.activeQueueItemId != active) {
+ session.setPlaybackState(PlaybackStateCompat.Builder(state).setActiveQueueItemId(active).build())
}
}
@@ -398,9 +416,14 @@ class PlaybackService : MediaBrowserServiceCompat() {
}
private val handler = android.os.Handler(android.os.Looper.getMainLooper())
- /** Leaves the foreground only after a real pause, never between two songs. */
+ /**
+ * Leaves the foreground only after a real pause, never between two songs; the locks go with it
+ * (see [show]).
+ */
private val leaveForeground = Runnable {
- if (current?.playing != true && foreground) {
+ if (current?.makesSound == true) return@Runnable
+ holdLocks(false)
+ if (foreground) {
ServiceCompat.stopForeground(this, ServiceCompat.STOP_FOREGROUND_DETACH)
foreground = false
}
@@ -437,19 +460,25 @@ class PlaybackService : MediaBrowserServiceCompat() {
private fun show(info: NowPlayingInfo) {
val notification = build(info)
- holdLocks(info.playing || info.buffering)
- if (info.playing || info.buffering) {
+ if (info.makesSound) {
+ holdLocks(true)
handler.removeCallbacks(leaveForeground)
startForegroundSafely(notification)
} else {
// The player is briefly "paused" while it loads the next song. Leaving the
// foreground then let Android freeze the app with the screen off, and playback
- // stopped after one song: the service stays a minute in the foreground.
+ // stopped after one song: the service stays a minute in the foreground. The locks
+ // stay for that minute too: in that gap the page has closed its audio stream, and a
+ // CPU lock dropped right then left a phone with the screen off free to sleep before
+ // the next song had loaded.
if (foreground) {
runCatching { NotificationManagerCompat.from(this).notify(NOTIFICATION_ID, notification) }
handler.removeCallbacks(leaveForeground)
handler.postDelayed(leaveForeground, PAUSE_GRACE_MS)
- } else runCatching { NotificationManagerCompat.from(this).notify(NOTIFICATION_ID, notification) }
+ } else {
+ holdLocks(false)
+ runCatching { NotificationManagerCompat.from(this).notify(NOTIFICATION_ID, notification) }
+ }
}
}
@@ -709,7 +738,7 @@ class PlaybackService : MediaBrowserServiceCompat() {
if (svc == null) {
// Loading counts: Android gives the audio only to a player in the foreground, and a
// song an extension is still resolving starts right after.
- if (info.playing || info.buffering) runCatching {
+ if (info.makesSound) runCatching {
androidx.core.content.ContextCompat.startForegroundService(context, Intent(context, PlaybackService::class.java))
}.onFailure { Logbook.logEvery("service-start", 10_000, "service not started for playback: ${it.javaClass.simpleName} ${it.message?.take(80)}") }
return
@@ -723,7 +752,7 @@ class PlaybackService : MediaBrowserServiceCompat() {
svc.apply(info)
svc.show(info)
// Sound with no foreground service (bound by the car only, promotion refused): start it.
- if ((info.playing || info.buffering) && !svc.foreground) svc.ensureStarted()
+ if (info.makesSound && !svc.foreground) svc.ensureStarted()
}
/**
diff --git a/base/host-android/src/main/kotlin/app/myspoti/host/android/QueueSync.kt b/base/host-android/src/main/kotlin/app/myspoti/host/android/QueueSync.kt
new file mode 100644
index 00000000..7d747b6f
--- /dev/null
+++ b/base/host-android/src/main/kotlin/app/myspoti/host/android/QueueSync.kt
@@ -0,0 +1,22 @@
+package app.myspoti.host.android
+
+/**
+ * The queue row the session marks as playing. Android's Bluetooth stack (AVRCP, what a car stereo,
+ * a bike dashboard or headphones read) holds every now-playing change back while the marked row is
+ * not the song in the metadata ("metadata out of sync", up to 2 s per change), and sends nothing
+ * when the player becomes the active one in that state. The row is marked only when it is the song
+ * shown (the same title and artist); otherwise none is ([NONE]), which the stack takes as in sync.
+ * The queue lags the metadata at every song change and during ads.
+ */
+object QueueSync {
+ /** MediaSessionCompat.QueueItem.UNKNOWN_ID: no row marked. */
+ const val NONE = -1L
+
+ fun activeRow(queue: List<QueueEntry>, activeId: Long, title: String?, artist: String?): Long {
+ if (activeId == NONE) return NONE
+ val row = queue.firstOrNull { it.id == activeId } ?: return NONE
+ // Nothing shown yet: no metadata to be out of sync with.
+ if (title == null) return activeId
+ return if (row.title == title && row.artist == artist.orEmpty()) activeId else NONE
+ }
+}
diff --git a/base/host-android/src/test/kotlin/app/myspoti/host/android/NowPlayingInfoTest.kt b/base/host-android/src/test/kotlin/app/myspoti/host/android/NowPlayingInfoTest.kt
new file mode 100644
index 00000000..1dd9bd27
--- /dev/null
+++ b/base/host-android/src/test/kotlin/app/myspoti/host/android/NowPlayingInfoTest.kt
@@ -0,0 +1,24 @@
+package app.myspoti.host.android
+
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class NowPlayingInfoTest {
+ private fun info(id: String = "spotify:track:x", playing: Boolean = false, buffering: Boolean = false) =
+ NowPlayingInfo(id, "t", "a", "al", null, 200_000L, 0L, playing, buffering)
+
+ @Test fun playingOrLoadingMakesSound() {
+ assertTrue(info(playing = true).makesSound)
+ assertTrue(info(buffering = true).makesSound)
+ }
+
+ /** An ad break is shown paused, but the service keeps the foreground and the locks through it. */
+ @Test fun adBreakMakesSoundThoughShownPaused() {
+ assertTrue(info(id = NowPlayingInfo.AD_ID).makesSound)
+ }
+
+ @Test fun pausedSongMakesNoSound() {
+ assertFalse(info().makesSound)
+ }
+}
diff --git a/base/host-android/src/test/kotlin/app/myspoti/host/android/QueueSyncTest.kt b/base/host-android/src/test/kotlin/app/myspoti/host/android/QueueSyncTest.kt
new file mode 100644
index 00000000..54b6764e
--- /dev/null
+++ b/base/host-android/src/test/kotlin/app/myspoti/host/android/QueueSyncTest.kt
@@ -0,0 +1,37 @@
+package app.myspoti.host.android
+
+import org.junit.Assert.assertEquals
+import org.junit.Test
+
+class QueueSyncTest {
+ private val queue = listOf(
+ QueueEntry(0, "Song A", "Artist A", null),
+ QueueEntry(1, "Song B", "Artist B", null),
+ )
+
+ @Test fun rowOfTheSongShownIsMarked() {
+ assertEquals(0L, QueueSync.activeRow(queue, 0, "Song A", "Artist A"))
+ }
+
+ @Test fun queueBehindTheMetadataMarksNoRow() {
+ // The song changed, the queue has not followed yet.
+ assertEquals(QueueSync.NONE, QueueSync.activeRow(queue, 0, "Song B", "Artist B"))
+ // An ad plays over the song's row.
+ assertEquals(QueueSync.NONE, QueueSync.activeRow(queue, 0, "Ad", ""))
+ }
+
+ @Test fun missingRowOrNoneMarksNoRow() {
+ assertEquals(QueueSync.NONE, QueueSync.activeRow(queue, 5, "Song A", "Artist A"))
+ assertEquals(QueueSync.NONE, QueueSync.activeRow(queue, QueueSync.NONE, "Song A", "Artist A"))
+ assertEquals(QueueSync.NONE, QueueSync.activeRow(emptyList(), 0, "Song A", "Artist A"))
+ }
+
+ @Test fun nothingShownYetKeepsTheRow() {
+ assertEquals(1L, QueueSync.activeRow(queue, 1, null, null))
+ }
+
+ @Test fun missingArtistMatchesAnEmptyOne() {
+ val q = listOf(QueueEntry(0, "Episode", "", null))
+ assertEquals(0L, QueueSync.activeRow(q, 0, "Episode", null))
+ }
+}