Skip to content

Native Android client for Spotify, built with Jetpack Compose

Shuffle with an audio-source extension plays the whole list (only the songs after the picked one were shuffled, so a 40-song playlist gave 5 to 10); a Connect speaker's volume is never set by a repair the user did not ask for (a soundbar jumped to 100% on connect, #159), and the ad mute restores only a level that device reported; the device picked in Myspoti is remembered across restarts so a skip no longer pulls playback back to the phone; a local crossfade waits up to 4 s for its second stream on mobile data

kota-zo72275a620aa3
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 1d55a3c6..dd4a8ce9 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
@@ -350,7 +350,10 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
repeatRestoreUntil = System.currentTimeMillis() + REPEAT_RESTORE_MS
if (streamingLevel != "auto") applyAudioQuality()
// The page keeps its volume: an app closed during a muted ad must not stay silent.
- runCatching { if (volume() == 0.0) setVolume(wantedVolume?.takeIf { v -> v > 0.0 } ?: 1.0) }
+ // Only when this page is Connect's active device: the volume is that device's
+ // otherwise, and a speaker at 0 (muted for its ad, not reported yet) went to 100 %
+ // (#159). A page not active yet is looked after by the guard once it plays here.
+ runCatching { if (volume() == 0.0 && ownsConnectVolume(readMedia())) setVolume(wantedVolume?.takeIf { v -> v > 0.0 } ?: 1.0) }
// A reloaded page during an ad break plays the ad again: muted again at once. So is a
// page reloaded to get past an ad, until a real song plays (an ad can come first).
if (_adPlaying.value || muteUntilSong) muteForAd()
@@ -654,6 +657,13 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
*/
internal val remoteActive: Boolean get() = lastMedia?.let { it.active == false && it.paused } == true
+ /**
+ * Whether a volume set on the page now is this page's own: the page player's volume is the
+ * Connect volume of the active device, so it may be set by us (not by the user) only when
+ * [media] says this page is that device. Unknown (no element, the device list not read) is no.
+ */
+ private fun ownsConnectVolume(media: Media?): Boolean = media?.active == true
+
private val _playsElsewhere = MutableStateFlow(false)
/**
* [remoteActive] as the watcher last read it (no call of its own): true while another device of
@@ -1048,7 +1058,10 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
if (wanted <= 0.0) return
// The page's own volume is read with the media element (one call, no second round trip).
val v = media?.playerVolume ?: runCatching { volume() }.getOrNull() ?: return
- if (v <= 0.0) {
+ // Set through Connect: only when this page is known to be the active device. Right after a
+ // transfer the element has not stopped yet (so [remoteActive] is still false) while the
+ // volume read is the speaker's, and a speaker reporting 0 was set to 100 % (#159).
+ if (v <= 0.0 && ownsConnectVolume(media)) {
bridge.logger?.invoke("page silent during a song: volume back to $wanted")
runCatching { setVolume(wanted) }
}
diff --git a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/ConnectVolumeTest.kt b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/ConnectVolumeTest.kt
new file mode 100644
index 00000000..a3148f6d
--- /dev/null
+++ b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/ConnectVolumeTest.kt
@@ -0,0 +1,97 @@
+package app.myspoti.spotify
+
+import app.myspoti.spotify.bridge.AdBlock
+import app.myspoti.spotify.bridge.Bridge
+import app.myspoti.spotify.bridge.BridgeHost
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.cancel
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.flow.MutableSharedFlow
+import kotlinx.coroutines.runBlocking
+import org.junit.jupiter.api.AfterEach
+import org.junit.jupiter.api.Assertions.assertEquals
+import org.junit.jupiter.api.BeforeEach
+import org.junit.jupiter.api.Test
+
+/**
+ * #159: a Samsung soundbar went to 100 % when the music was sent to it. The page player's volume
+ * is the Connect volume of the active device: the page's own repairs (a page back after a reload,
+ * the silent-song guard) set it only when this page is that device, never on a speaker at 0.
+ */
+class ConnectVolumeTest {
+ private class FakeHost : BridgeHost {
+ override val messages = MutableSharedFlow<String>(extraBufferCapacity = 64)
+ /** This page is Connect's active device (the page's device list). */
+ @Volatile var active = false
+ /** The page player's volume: the active device's. */
+ @Volatile var playerVolume = 0.0
+ val sets = java.util.concurrent.CopyOnWriteArrayList<String>()
+ @Volatile var time = 10.0
+ override suspend fun evaluate(script: String) {
+ val m = Regex("""Myspoti\.call\((\d+), "([^"]+)", (.*)\)\.catch""", RegexOption.DOT_MATCHES_ALL).find(script) ?: return
+ val value = when (m.groupValues[2]) {
+ // Right after a transfer: the element has not stopped yet, the volume read is the speaker's.
+ "media.state" -> {
+ time += 2.0
+ """{"paused":false,"muted":false,"volume":1,"level":1,"own":1,"time":$time,"readyState":4,"ended":false,"playerVolume":$playerVolume,"active":$active}"""
+ }
+ "volume.get" -> "$playerVolume"
+ "volume.set" -> { sets += m.groupValues[3]; "null" }
+ else -> "null"
+ }
+ messages.emit("""{"type":"result","id":${m.groupValues[1]},"ok":true,"value":$value}""")
+ }
+ suspend fun post(json: String) = messages.emit(json)
+ }
+
+ private lateinit var scope: CoroutineScope
+ private lateinit var host: FakeHost
+ private lateinit var bridge: Bridge
+ private lateinit var player: SpotifyPlayer
+
+ @BeforeEach fun up() {
+ AdBlock.ahead.value = null
+ scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
+ host = FakeHost()
+ bridge = Bridge(host, scope)
+ player = SpotifyPlayer(bridge, scope)
+ waitFor("bridge listening") { host.messages.subscriptionCount.value > 0 }
+ }
+
+ @AfterEach fun down() {
+ AdBlock.ahead.value = null
+ scope.cancel()
+ }
+
+ private fun waitFor(what: String, ms: Long = 4_000, cond: () -> Boolean) = runBlocking {
+ val end = System.currentTimeMillis() + ms
+ while (!cond()) {
+ check(System.currentTimeMillis() < end) { "timed out: $what" }
+ delay(20)
+ }
+ }
+
+ private suspend fun playing() {
+ host.post("""{"type":"ready"}""")
+ waitFor("page ready") { bridge.ready.value }
+ val item = """{"kind":"track","uri":"spotify:track:A","uid":"uA","name":"A","durationMs":200000}"""
+ host.post("""{"type":"state","state":{"track":$item,"contextUri":"spotify:playlist:C","next":null,"isPaused":false,"isBuffering":false,
+ |"positionMs":10000,"timestamp":${System.currentTimeMillis()},"restrictions":{}}}""".trimMargin())
+ waitFor("state") { player.state.value?.item?.name == "A" }
+ }
+
+ @Test fun `a speaker at 0 that plays is never set to full volume by the page`() = runBlocking {
+ playing()
+ // Past the page back and two volume checks of the watcher.
+ delay(14_000)
+ assertEquals(emptyList<String>(), host.sets.toList())
+ }
+
+ @Test fun `this page silent while it is the active device gets its volume back`() = runBlocking {
+ host.active = true
+ playing()
+ waitFor("volume set", ms = 14_000) { host.sets.isNotEmpty() }
+ }
+}
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
index 0c564c6f..32f69ca5 100644
--- a/base/app/src/main/java/com/music/spotui/connect/RemoteAdMute.kt
+++ b/base/app/src/main/java/com/music/spotui/connect/RemoteAdMute.kt
@@ -54,9 +54,13 @@ object RemoteAdMute {
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 }
+ /**
+ * The level a device is reported at (0..1), else the one the player's volume bar shows
+ * (0..100) when that is this device's ([shown] null: the bar still has its first 100 % or
+ * another device's level, and restoring it would set the device to that, #159).
+ */
+ 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)
}
@@ -134,7 +138,7 @@ object RemoteAdMute {
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 level = Rules.levelOf(active.volume, SongPlayer.knownRemoteVolume(active.id))
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())
diff --git a/base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt b/base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt
index 3729d977..c8261e85 100644
--- a/base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt
+++ b/base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt
@@ -423,6 +423,14 @@ object LocalPlayer {
noFadeFor = -1
queued.clear(); playingQueued = null; radioSongs.clear()
queued += fromSpotify
+ // Shuffle on: the picked song, then every other song of the list shuffled, those above it
+ // too, as Spotify's shuffle does. Shuffling only the songs after the pick left the rest of
+ // the list out (B6: 5 to 10 songs of a 40-song playlist queued, the shuffle button picks
+ // a random song first). The list's order is kept for shuffle off.
+ val start = index.coerceIn(0, list.lastIndex)
+ val whole = shuffle && !isStation && all.size > 1
+ val order = if (whole) LocalQueueOrder.shuffledWhole(all, start, isQueued) { it.shuffled() } else all
+ if (whole) { tracks.clear(); tracks.addAll(order); unshuffled = all.filterNot(isQueued) }
listName = context ?: Graph.app.getString(app.myspoti.engine.R.string.local_files_title)
listUri = contextUri
active.value = true
@@ -435,9 +443,9 @@ object LocalPlayer {
applyRepeat(p)
// Paused before it loads: a player left playing by a song before never starts this one.
if (paused) p.pause()
- p.setMediaItems(all.map(::item), index.coerceIn(0, list.lastIndex), startMs.coerceAtLeast(0L))
+ p.setMediaItems(order.map(::item), if (whole) 0 else start, startMs.coerceAtLeast(0L))
p.prepare()
- if (shuffle) setShuffle(true)
+ if (shuffle && !whole) setShuffle(true)
if (!paused) p.play()
continueIfLast(p)
}
@@ -1065,6 +1073,10 @@ object LocalPlayer {
CrossfadePref.seconds > 0 && !LocalRepeat.loopsSong(repeat, p.mediaItemCount) && p.nextMediaItemIndex != C.INDEX_UNSET &&
p.currentMediaItem != null && p.playWhenReady && !CastPlayback.active
+ /** How long a crossfade's copy of the song may take to be ready, on Wi-Fi and on a metered network. */
+ private const val FADE_READY_MS = 1_500L
+ private const val FADE_READY_METERED_MS = 4_000L
+
private fun beginFade(p: ExoPlayer) {
val item = p.currentMediaItem ?: return
val index = p.currentMediaItemIndex
@@ -1113,10 +1125,17 @@ object LocalPlayer {
}
})
out.prepare()
- // Not ready in time: no fade for this song.
+ // Not ready in time: no fade for this song. The copy is a second connection to the song's
+ // stream, seeked: on mobile data it can take longer than 1.5 s, and the fade was then never
+ // heard there ("crossfade only works on Wi-Fi", B12). Longer on a metered network (the fade
+ // starts later and is shorter, see its length above), and said in the log.
+ val ready = if (com.music.spotui.data.DataSaver.metered) FADE_READY_METERED_MS else FADE_READY_MS
handler.postDelayed({
- if (preparingFade && outgoing == null) { preparingFade = false; noFadeFor = index; out.release() }
- }, 1500)
+ if (preparingFade && outgoing == null) {
+ log("crossfade: the song's second stream not ready in $ready ms, no fade")
+ preparingFade = false; noFadeFor = index; out.release()
+ }
+ }, ready)
}
/** Ends a fade (done, or interrupted by a skip/seek/stop): the copy goes, the main player is at full volume. */
diff --git a/base/app/src/main/java/com/music/spotui/di/LocalQueueOrder.kt b/base/app/src/main/java/com/music/spotui/di/LocalQueueOrder.kt
index f3982d8b..bdaca228 100644
--- a/base/app/src/main/java/com/music/spotui/di/LocalQueueOrder.kt
+++ b/base/app/src/main/java/com/music/spotui/di/LocalQueueOrder.kt
@@ -38,6 +38,18 @@ internal object LocalQueueOrder {
return order.take(cur + 1) + tail.filter(isQueued) + shuffle(tail.filterNot(isQueued))
}
+ /**
+ * A list played from the song at [cur] with shuffle on: that song first, the queued songs right
+ * after it, then every other song of the list [shuffle]d, those before [cur] too (as Spotify's
+ * shuffle plays a whole list from a picked song). [shuffled] alone left the songs above the
+ * pick out: a tap low in a 40-song list queued 5 to 10 of them (reported, B6).
+ */
+ fun <T> shuffledWhole(order: List<T>, cur: Int, isQueued: (T) -> Boolean, shuffle: (List<T>) -> List<T>): List<T> {
+ val current = order.getOrNull(cur) ?: return order
+ val others = order.filterIndexed { i, _ -> i != cur }
+ return listOf(current) + order.drop(cur + 1).filter(isQueued) + shuffle(others.filterNot(isQueued))
+ }
+
/**
* Shuffle off: the list back in its order [before] (songs added since at its end), the queued
* songs still right after the current one.
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 cfa9ec87..1e09b6e5 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
@@ -2337,7 +2337,7 @@ object SongPlayer {
_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 %.
// 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) }
+ active?.volume?.takeIf { it >= 0 }?.let { if (SystemClock.elapsedRealtime() > volumeHoldUntil && !com.music.spotui.connect.RemoteAdMute.muting) { _remoteVolume.intValue = (it * 100).toInt().coerceIn(0, 100); remoteVolumeOf = active.id } }
PlaybackService.setPlaybackDevice(_activeDevice.value != null, remoteVolume)
}
}
@@ -2356,8 +2356,32 @@ object SongPlayer {
return list
}
- /** The other device picked in Myspoti to play on; null: this phone. */
- @Volatile private var chosenRemote: String? = null
+ /**
+ * The other device picked in Myspoti to play on; null: this phone. Kept over a restart of the
+ * app (a day at most): forgotten, the first skip after the app came back took the device for one
+ * that took playback by itself and pulled the music back to the phone (B12, reported: "I skip a
+ * song and the audio starts playing through the phone").
+ */
+ private var chosenRemote: String?
+ get() {
+ if (!chosenLoaded) {
+ chosenLoaded = true
+ chosen = runCatching {
+ val p = chosenPrefs()
+ p.getString("device", null)?.takeIf { System.currentTimeMillis() - p.getLong("at", 0L) < CHOSEN_KEEP_MS }
+ }.getOrNull()
+ }
+ return chosen
+ }
+ set(value) {
+ chosenLoaded = true
+ chosen = value
+ runCatching { chosenPrefs().edit().putString("device", value).putLong("at", System.currentTimeMillis()).apply() }
+ }
+ @Volatile private var chosen: String? = null
+ @Volatile private var chosenLoaded = false
+ private fun chosenPrefs() = Graph.app.getSharedPreferences("myspoti_connect_choice", Context.MODE_PRIVATE)
+ private const val CHOSEN_KEEP_MS = 24 * 3600_000L
/** [chosenRemote], read by RemoteAdMute (only that device's ads are muted). */
val chosenRemoteId: String? get() = chosenRemote
@@ -2476,6 +2500,14 @@ object SongPlayer {
private val _remoteVolume = androidx.compose.runtime.mutableIntStateOf(100)
val remoteVolume: Int get() = _remoteVolume.intValue
@Volatile private var volumeHoldUntil = 0L
+ /**
+ * The device [remoteVolume] is the level of (reported by it, or set by the user while it played);
+ * null: the first 100 %, never any device's.
+ */
+ @Volatile private var remoteVolumeOf: String? = null
+
+ /** [remoteVolume] when it is [deviceId]'s own level, else null (RemoteAdMute never restores a guess). */
+ fun knownRemoteVolume(deviceId: String): Int? = remoteVolume.takeIf { remoteVolumeOf == deviceId }
/**
* The newest volume asked for, sent one at a time by [volumeSender]. A drag on the player's
@@ -2494,6 +2526,7 @@ object SongPlayer {
/** Set the volume of the device that plays (volume keys, system slider, the player's volume bar). */
fun setRemoteVolume(volume: Int) {
_remoteVolume.intValue = volume.coerceIn(0, 100)
+ remoteVolumeOf = _activeDevice.value?.id
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
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
index 7fd0bed2..c43bc7e7 100644
--- a/base/app/src/test/java/com/music/spotui/connect/RemoteAdMuteTest.kt
+++ b/base/app/src/test/java/com/music/spotui/connect/RemoteAdMuteTest.kt
@@ -39,6 +39,8 @@ class RemoteAdMuteTest {
assertEquals(0.4, Rules.levelOf(0.4, 80)!!, 1e-9)
assertEquals(0.8, Rules.levelOf(null, 80)!!, 1e-9)
assertNull(Rules.levelOf(null, 0))
+ // #159: the bar's level is not this device's (its first 100 %): no guess is restored.
+ assertNull(Rules.levelOf(null, null))
// 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))
diff --git a/base/app/src/test/java/com/music/spotui/di/LocalQueueOrderTest.kt b/base/app/src/test/java/com/music/spotui/di/LocalQueueOrderTest.kt
index 2dbbb20b..7379d6d8 100644
--- a/base/app/src/test/java/com/music/spotui/di/LocalQueueOrderTest.kt
+++ b/base/app/src/test/java/com/music/spotui/di/LocalQueueOrderTest.kt
@@ -33,6 +33,17 @@ class LocalQueueOrderTest {
assertEquals(listOf("A", "P", "C", "Q1", "Q2", "B", "D", "X"), LocalQueueOrder.unshuffled(now, 1, before, queued))
}
+ @Test fun aListPlayedShuffledFromASongKeepsEverySongOfIt() {
+ // B6: picked low in the list, the songs above it play too, after it and the queued ones.
+ val list = listOf("A", "B", "C", "Q1", "D")
+ val on = LocalQueueOrder.shuffledWhole(list, 2, queued) { it.reversed() }
+ assertEquals(listOf("C", "Q1", "D", "B", "A"), on)
+ assertEquals(list.toSet(), on.toSet())
+ // Back in the list's order: the picked song at its place, the queued one next.
+ assertEquals(listOf("A", "B", "C", "Q1", "D"), LocalQueueOrder.unshuffled(on, 0, list.filterNot(queued), queued))
+ assertEquals(emptyList<String>(), LocalQueueOrder.shuffledWhole(emptyList<String>(), 0, queued) { it })
+ }
+
@Test fun aSongDraggedAmongTheQueuedOnesIsMovedUp() {
assertEquals(listOf("P", "C", "Q1", "Q2", "Q3", "A", "B"), LocalQueueOrder.settle(listOf("P", "C", "Q1", "A", "Q2", "B", "Q3"), 1, queued))
}