Skip to content

Native Android client for Spotify, built with Jetpack Compose

Audio sources and battery: a slow audio-source extension no longer holds back one below it that answered (1.5 s more at most, then the answer in hand plays), and less work in the background

kota-zoe531ba09c570
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 384bcfe6..aa8b25b5 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
@@ -121,7 +121,7 @@ object LocalPlayer {
private fun player(): ExoPlayer = exo ?: build(true).also { p ->
mainListener = listenerFor(p).also(p::addListener)
exo = p
- deckEq = if (com.music.spotui.automix.AutoMix.on) com.music.spotui.automix.DeckEq.attach(p.audioSessionId) else null
+ deckEq = if (com.music.spotui.automix.AutoMix.on && com.music.spotui.automix.AutoMix.djEq) com.music.spotui.automix.DeckEq.attach(p.audioSessionId) else null
// A new local session takes the repeat the player shows (it started off).
setRepeatMode(SongPlayer.repeatMode.value)
}
@@ -571,6 +571,18 @@ object LocalPlayer {
return true
}
+ /**
+ * The next AutoMix step: every 20 ms from the deck's readiness (its start and the lock depend on
+ * it), 200 ms around the mix, once a second while it is far (the deck is prepared 15 s ahead,
+ * and a queue edit is still seen within a second): no 5 wakes a second through a whole song.
+ */
+ private fun mixTickDelay(p: ExoPlayer): Long {
+ mix?.let { return if (it.state >= MixState.READY) 20 else 200 }
+ val exit = planned?.takeIf { it.fromIndex == p.currentMediaItemIndex }?.let { (it.plan.exitA * 1000).toLong() }
+ ?: p.duration.takeIf { it > 0 } ?: return 200
+ return if (exit - p.currentPosition > PREPARE_LEAD_MS + RUN_UP_MS + 3_000) 1_000 else 200
+ }
+
/** The plan for this pair: the analysed one, else (once the end is near) a fade on the songs' lengths. */
private fun planFor(p: ExoPlayer, next: Int, nextId: String): app.myspoti.automix.MixPlan? {
val cur = p.currentMediaItemIndex
@@ -635,7 +647,7 @@ object LocalPlayer {
val b = tracks.getOrNull(next)?.let { com.music.spotui.automix.AutoMix.analysis(it.uri) }
// A skip may stretch more than a natural mix (12 %): it is short, and B is back to its tempo soon after.
return app.myspoti.automix.MixPlanner.planSkip(a, b, posMs / 1000.0, (SKIP_RUN_UP_MS + startLead) / 1000.0,
- app.myspoti.automix.MixPlanner.Settings(maxStretch = 0.12))
+ com.music.spotui.automix.AutoMix.settings().let { app.myspoti.automix.MixPlanner.Settings(maxStretch = maxOf(it.maxStretch, 0.12), lengthBias = it.lengthBias) })
}
/**
@@ -666,7 +678,7 @@ object LocalPlayer {
deck.playbackParameters = androidx.media3.common.PlaybackParameters((plan.speedB * rate()).toFloat())
val runUpB = minOf(plan.entryB * 1000, (if (skip) SKIP_RUN_UP_MS else RUN_UP_MS) * plan.speedB)
val start = (plan.entryB * 1000 - runUpB).toLong().coerceAtLeast(0L)
- val run = MixRun(plan, next, nextId, deck, com.music.spotui.automix.DeckEq.attach(deck.audioSessionId), start, skip)
+ val run = MixRun(plan, next, nextId, deck, (if (com.music.spotui.automix.AutoMix.djEq) com.music.spotui.automix.DeckEq.attach(deck.audioSessionId) else null), start, skip)
run.eq?.set(app.myspoti.automix.MixPlan.KILL, 0.0)
run.lastSpeed = deck.playbackParameters.speed
run.a = p; run.eqA = deckEq
@@ -871,11 +883,16 @@ object LocalPlayer {
/** AutoMix turned on or off in the settings. */
fun autoMixChanged(on: Boolean) {
val p = exo ?: return
- if (on && deckEq == null) deckEq = com.music.spotui.automix.DeckEq.attach(p.audioSessionId)
+ if (on && deckEq == null && com.music.spotui.automix.AutoMix.djEq) deckEq = com.music.spotui.automix.DeckEq.attach(p.audioSessionId)
if (!on) { cancelMix("AutoMix off"); planned = null; updateCue() }
if (p.isPlaying) { handler.removeCallbacks(tick); handler.post(tick) }
}
+ /** A planner setting changed (length, tempo range): the next mix is planned again unless it already started. */
+ fun autoMixSettingsChanged() {
+ if (mix == null) { planned = null; updateCue() }
+ }
+
/** For the command line: where the mix stands. */
fun autoMixState(): String {
val run = mix
@@ -1016,8 +1033,7 @@ object LocalPlayer {
return
}
if (mix != null || (com.music.spotui.automix.AutoMix.on && !CastPlayback.active)) {
- // Every 20 ms from the deck's readiness: its start and the lock depend on it.
- if (mixTick(p)) handler.postDelayed(this, if (mix?.let { it.state >= MixState.READY } == true) 20 else 200)
+ if (mixTick(p)) handler.postDelayed(this, mixTickDelay(p))
return
}
if (!p.isPlaying) return
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 acb3e056..155e81be 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
@@ -36,7 +36,9 @@ object SpeakerKeepAlive {
private fun start() {
if (track != null) return
- val size = AudioTrack.getMinBufferSize(RATE, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT)
+ // 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)
val t = runCatching {
AudioTrack.Builder()
.setAudioAttributes(AudioAttributes.Builder()
@@ -49,13 +51,14 @@ object SpeakerKeepAlive {
.setEncoding(AudioFormat.ENCODING_PCM_16BIT)
.build())
.setBufferSizeInBytes(size)
+ .setPerformanceMode(AudioTrack.PERFORMANCE_MODE_POWER_SAVING)
.setTransferMode(AudioTrack.MODE_STREAM)
.build()
}.getOrNull() ?: return
track = t
runCatching { t.play() }
feeder = Thread({
- val zeros = ByteArray(size)
+ 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
}, "speaker-keepalive").apply { isDaemon = true; start() }
diff --git a/base/app/src/main/java/com/music/spotui/extensions/Extensions.kt b/base/app/src/main/java/com/music/spotui/extensions/Extensions.kt
index 021697b3..bc49c980 100644
--- a/base/app/src/main/java/com/music/spotui/extensions/Extensions.kt
+++ b/base/app/src/main/java/com/music/spotui/extensions/Extensions.kt
@@ -881,14 +881,15 @@ object Extensions {
Logbook.log("audio: asked ${asked.joinToString { it.first }} for $label")
val t0 = System.currentTimeMillis()
val answers = ConcurrentHashMap<String, PlayAttempt.Ask>()
- val found = HookDispatch.firstInOrder(asked) { (id, rt) ->
+ // All asked at once; a slow source above one that answered is waited for briefly, not to its limit.
+ val found = HookDispatch.firstInOrderWithin(asked, AUDIO_GRACE_MS) { (id, rt) ->
val a = ask(id, rt, Hook.AUDIO_SOURCE, input, timeoutMs, AudioStream::parse)
answers[id] = PlayAttempt.Ask(id, a.outcome.key, a.ms, detail = a.outcome.detail)
a.value
}
val ms = System.currentTimeMillis() - t0
// A source cut short because one above it answered was not needed.
- val all = skipped + asked.map { (id, _) -> answers[id] ?: PlayAttempt.Ask(id, Outcome.Skipped().key, ms, "not needed: a source above answered") }
+ val all = skipped + asked.map { (id, _) -> answers[id] ?: PlayAttempt.Ask(id, Outcome.Skipped().key, ms, "not needed: another source answered first") }
if (found == null) {
Logbook.log("audio: no extension had $label ($ms ms)"); misses.record(track.id, ahead)
attempts.update(attempt) { it.copy(asked = all, fallback = "Spotify: no extension had it") }
@@ -1069,6 +1070,8 @@ object Extensions {
private const val START_WAIT_MS = 20_000L
/** How long a song picked right after launch waits for them (then plays from Spotify). */
private const val START_AUDIO_MS = 5_000L
+ /** How long a source above one that answered is still waited for (see [HookDispatch.firstInOrderWithin]). */
+ private const val AUDIO_GRACE_MS = 1_500L
/** How old a probe may be: asked again after it while the app is in sight or plays, and before a source is asked. */
private const val STATUS_EVERY_MS = 5 * 60_000L
private val SOURCE_HOOKS = setOf(Hook.AUDIO_SOURCE, Hook.DOWNLOAD_SOURCE)
@@ -1198,7 +1201,8 @@ object Extensions {
var idle = 0
var listening = false
while (true) {
- kotlinx.coroutines.delay(1_000)
+ // Once a second while something plays; nothing playing (stopped for 3 s), every 3 s.
+ kotlinx.coroutines.delay(if (idle >= 3) 3_000 else 1_000)
if (runtimes.values.none { it.listens(ExtensionRuntime.EVENT_PLAYBACK) }) {
if (listening) { playback.observe(null, System.currentTimeMillis()); listening = false }
continue
diff --git a/base/app/src/main/java/com/music/spotui/extensions/HookDispatch.kt b/base/app/src/main/java/com/music/spotui/extensions/HookDispatch.kt
index a976d926..1eacf090 100644
--- a/base/app/src/main/java/com/music/spotui/extensions/HookDispatch.kt
+++ b/base/app/src/main/java/com/music/spotui/extensions/HookDispatch.kt
@@ -33,6 +33,34 @@ object HookDispatch {
null
}
+ /**
+ * The first non-null answer in [candidates]' order, but a slow candidate does not hold back one
+ * below it that already answered for longer than [graceMs]: once any answer is in, the ones
+ * above it still asking get that long, then the highest answer in hand wins (the rest are
+ * cancelled). With every candidate above it done, the answer is taken at once.
+ */
+ suspend fun <C, R : Any> firstInOrderWithin(candidates: List<C>, graceMs: Long, ask: suspend (C) -> R?): Pair<C, R>? = coroutineScope {
+ val asked = candidates.map { c -> async { answer { ask(c) } } }
+ val done = BooleanArray(asked.size)
+ val results = arrayOfNulls<Any>(asked.size)
+ suspend fun awaitOne() = select<Unit> {
+ asked.forEachIndexed { i, d -> if (!done[i]) d.onAwait { done[i] = true; results[i] = it } }
+ }
+ fun best() = results.indices.firstOrNull { results[it] != null }
+ // The best answer is final when every candidate above it is done.
+ fun settled() = best()?.let { b -> (0 until b).all { done[it] } } == true
+ try {
+ while (best() == null && done.any { !it }) awaitOne()
+ if (best() == null) return@coroutineScope null
+ if (!settled()) withTimeoutOrNull(graceMs) { while (!settled()) awaitOne() }
+ val b = best()!!
+ @Suppress("UNCHECKED_CAST")
+ candidates[b] to results[b] as R
+ } finally {
+ asked.forEach { it.cancel() }
+ }
+ }
+
/** The best answer by [rank] (higher is better), ties to the earlier candidate. Waits for all. */
suspend fun <C, R : Any> bestInOrder(candidates: List<C>, rank: (R) -> Int, ask: suspend (C) -> R?): Pair<C, R>? = coroutineScope {
val asked = candidates.map { c -> c to async { answer { ask(c) } } }
diff --git a/base/app/src/test/java/com/music/spotui/extensions/HookDispatchTest.kt b/base/app/src/test/java/com/music/spotui/extensions/HookDispatchTest.kt
index c36e580c..ac5b67df 100644
--- a/base/app/src/test/java/com/music/spotui/extensions/HookDispatchTest.kt
+++ b/base/app/src/test/java/com/music/spotui/extensions/HookDispatchTest.kt
@@ -172,4 +172,31 @@ class HookDispatchTest {
val duet = own.copy(lines = own.lines.mapIndexed { i, l -> l.copy(voice = i % 2 + 1) })
assertEquals("LRCLIB", LyricsMerge.choose(duet, backs.copy(lines = lines("x", "y", "z")))?.provider)
}
+
+ @Test fun withinTakesTheLowerAnswerWhenTheOneAboveIsSlow() = runBlocking {
+ val t0 = System.currentTimeMillis()
+ val r = HookDispatch.firstInOrderWithin(listOf("slow", "quick"), graceMs = 100) { c ->
+ if (c == "slow") { delay(5_000); "a" } else { delay(10); "b" }
+ }
+ assertEquals("quick" to "b", r)
+ assert(System.currentTimeMillis() - t0 < 2_000)
+ }
+
+ @Test fun withinKeepsTheOrderWhenTheOneAboveAnswersInTime() = runBlocking {
+ val r = HookDispatch.firstInOrderWithin(listOf("first", "second"), graceMs = 1_000) { c ->
+ if (c == "first") { delay(80); "a" } else "b"
+ }
+ assertEquals("first" to "a", r)
+ }
+
+ @Test fun withinSkipsAFailureAboveAtOnce() = runBlocking {
+ val r = HookDispatch.firstInOrderWithin(listOf("none", "fails", "ok"), graceMs = 5_000) { c ->
+ when (c) { "none" -> null; "fails" -> error("boom"); else -> "c" }
+ }
+ assertEquals("ok" to "c", r)
+ }
+
+ @Test fun withinGivesNullWhenNobodyAnswers() = runBlocking {
+ assertNull(HookDispatch.firstInOrderWithin(listOf(1, 2), graceMs = 10) { null })
+ }
}