Skip to content

Native Android client for Spotify, built with Jetpack Compose

AutoMix: play segue plans in the audio chain, behind a Mix Lab setting

kota-zodec7556b7c9a
diff --git a/base/app/build.gradle.kts b/base/app/build.gradle.kts
index 958152e7..83589d2b 100644
--- a/base/app/build.gradle.kts
+++ b/base/app/build.gradle.kts
@@ -40,6 +40,7 @@ android {
versionName = version
// GitHub "owner/repo" whose releases the app checks for updates; empty = off
// (local builds). CI sets it to the repository it builds.
+ buildConfigField("boolean", "AUTOMIX_LAB", automixLab.toString())
buildConfigField("String", "UPDATE_REPO", "\"${(findProperty("updateRepo") as String?) ?: System.getenv("MYSPOTI_UPDATE_REPO") ?: ""}\"")
ndk {
// -Pabis=arm64-v8a: a smaller test APK for one phone.
diff --git a/base/app/src/main/java/com/music/spotui/automix/AutoMix.kt b/base/app/src/main/java/com/music/spotui/automix/AutoMix.kt
index c18acb87..fda69395 100644
--- a/base/app/src/main/java/com/music/spotui/automix/AutoMix.kt
+++ b/base/app/src/main/java/com/music/spotui/automix/AutoMix.kt
@@ -125,6 +125,24 @@ object AutoMix {
djMode = sessionDj,
)
+ /** The data-plan transitions (the Mix Lab's test of them), in place of the planner; only for the beat blend style. */
+ var segue by mutableStateOf(Graph.app.getSharedPreferences(PREFS, 0).getBoolean("automix_segue", false))
+ private set
+ fun changeSegue(value: Boolean) { segue = value; Graph.app.getSharedPreferences(PREFS, 0).edit().putBoolean("automix_segue", value).apply(); com.music.spotui.di.LocalPlayer.autoMixSettingsChanged() }
+ val segueActive: Boolean get() = app.myspoti.engine.BuildConfig.AUTOMIX_LAB && segue && style == 0
+
+ /** The policy's decision for two analysed songs. The listener's settings may only tighten its limits. */
+ fun decide(a: TrackAnalysis, b: TrackAnalysis, earliestExit: Double, sameAlbum: Boolean, listener: Float): app.myspoti.automix.segue.SegueDecision {
+ val s = settings()
+ val d = app.myspoti.automix.segue.SeguePolicy.decide(app.myspoti.automix.segue.SegueRequest(a, b, (earliestExit * 1e6).toLong(),
+ listenerRate = (listener * app.myspoti.automix.segue.SegueFormat.RATE_NOMINAL).toLong(),
+ maxRatePpm = (s.maxStretch * 1e6).toLong(), maxBars = s.maxBars, eq = djEq, harmonic = harmonic, sameAlbum = sameAlbum))
+ val plan = d.plan ?: return d
+ if (app.myspoti.automix.segue.SegueDeck.playable(plan)) return d
+ return app.myspoti.automix.segue.SegueDecision(app.myspoti.automix.segue.SegueLevel.NORMAL, null,
+ d.attempts + app.myspoti.automix.segue.SegueAttempt(d.level, app.myspoti.automix.segue.SegueCause.INVALID_PLAN, "the engine cannot play it"))
+ }
+
// ── Why a song is not mixed (for the screens) ──
/** Why the next transition is not an AutoMix one. */
diff --git a/base/app/src/main/java/com/music/spotui/automix/MixPreparation.kt b/base/app/src/main/java/com/music/spotui/automix/MixPreparation.kt
index 7d8e2339..b2b923ce 100644
--- a/base/app/src/main/java/com/music/spotui/automix/MixPreparation.kt
+++ b/base/app/src/main/java/com/music/spotui/automix/MixPreparation.kt
@@ -13,6 +13,20 @@ internal object MixPreparation {
playing && bufferedMs >= minOf(BUFFER_MS, remainingMs.coerceAtLeast(0)) &&
(!synced || phaseMs != null && kotlin.math.abs(phaseMs) <= 80.0)
+ /** A plan's outgoing lanes are armed this long before its cue at most, and at least: past the player's buffer, or they would come late. */
+ const val SEGUE_ARM_LEAD_MS = 1_500L
+ const val SEGUE_ARM_MIN_MS = 1_000L
+ /** How far ahead of what is heard the audio chain may be working. */
+ private const val SEGUE_PLACE_SLACK_MS = 5_000L
+
+ /** The audio chain's idea of the song position agrees with the player's: its automation will land where the plan says. */
+ fun placed(chainPositionUs: Long, playerPositionMs: Long): Boolean =
+ kotlin.math.abs(chainPositionUs / 1000 - playerPositionMs) <= SEGUE_PLACE_SLACK_MS
+
+ fun segueReady(prepared: Boolean, bufferedMs: Long, remainingMs: Long, placedA: Boolean, placedB: Boolean, phaseMs: Double?): Boolean =
+ prepared && placedA && placedB && bufferedMs >= minOf(BUFFER_MS, remainingMs.coerceAtLeast(0)) &&
+ (phaseMs == null || kotlin.math.abs(phaseMs) <= 80.0)
+
/** Audio lost on B must not make the still-playing A fade away. */
fun preserveOutgoing(incomingReady: Boolean, outgoingPlaying: Boolean): Boolean = !incomingReady && outgoingPlaying
}
diff --git a/base/app/src/main/java/com/music/spotui/automix/SegueProcessor.kt b/base/app/src/main/java/com/music/spotui/automix/SegueProcessor.kt
new file mode 100644
index 00000000..8d3bdc95
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/automix/SegueProcessor.kt
@@ -0,0 +1,107 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+package com.music.spotui.automix
+
+import androidx.media3.common.C
+import androidx.media3.common.audio.AudioProcessor
+import androidx.media3.common.audio.BaseAudioProcessor
+import androidx.media3.common.util.UnstableApi
+import androidx.media3.exoplayer.audio.AudioSink
+import androidx.media3.exoplayer.audio.ForwardingAudioSink
+import app.myspoti.automix.segue.LaneSide
+import app.myspoti.automix.segue.SegueDeck
+import app.myspoti.automix.segue.SeguePlan
+import java.nio.ByteBuffer
+import java.nio.ByteOrder
+
+/**
+ * Plays a side of a plan in the player's audio chain. Until one is armed it copies its input as it
+ * came. It runs ahead of the player's buffers and its speed, and knows from [SegueSink] where each
+ * buffer sits in the song: an automation point lands on its sample, however late that sample is heard.
+ */
+@UnstableApi
+class SegueProcessor : BaseAudioProcessor() {
+ private class Armed(val plan: SeguePlan, val side: LaneSide)
+
+ @Volatile private var armed: Armed? = null
+ @Volatile private var holding = false
+ private var deck: SegueDeck? = null
+ private var deckOf: Armed? = null
+ private var scratch = FloatArray(0)
+
+ /** The song position of the next frame, microseconds, once a buffer has told it. */
+ @Volatile var positionUs = 0L
+ private set
+ @Volatile var marked = false
+ private set
+
+ /** From [SegueSink], on the playback thread, ahead of the buffer it describes. */
+ fun mark(sourceUs: Long) { positionUs = sourceUs; marked = true }
+
+ fun arm(plan: SeguePlan, side: LaneSide) { holding = false; armed = Armed(plan, side) }
+
+ /** Plain copies from the next buffer on: for a side whose lanes have settled on neutral. */
+ fun disarm() { holding = false; armed = null }
+
+ /** The plain song again over a short ramp, then a plain copy: the plan no longer applies. */
+ fun release() { if (armed != null) holding = true }
+
+ val isArmed: Boolean get() = armed != null
+
+ override fun onConfigure(format: AudioProcessor.AudioFormat): AudioProcessor.AudioFormat {
+ if (format.encoding != C.ENCODING_PCM_16BIT && format.encoding != C.ENCODING_PCM_FLOAT) return AudioProcessor.AudioFormat.NOT_SET
+ if (format.channelCount !in 1..2) return AudioProcessor.AudioFormat.NOT_SET
+ deck = null; deckOf = null
+ return format
+ }
+
+ override fun queueInput(input: ByteBuffer) {
+ val size = input.remaining()
+ if (size == 0) return
+ val format = inputAudioFormat
+ val frames = size / format.bytesPerFrame
+ val at = positionUs
+ positionUs = at + frames * 1_000_000L / format.sampleRate
+ val out = replaceOutputBuffer(size)
+ val a = armed
+ if (a == null) { deck = null; deckOf = null; out.put(input); out.flip(); return }
+ if (deckOf !== a) {
+ deck = SegueDeck(a.plan, a.side, format.sampleRate, format.channelCount)
+ deckOf = a
+ }
+ val d = deck!!
+ d.hold = holding
+ val n = frames * format.channelCount
+ if (scratch.size < n) scratch = FloatArray(n)
+ val s = scratch
+ val pcm = input.order(ByteOrder.nativeOrder())
+ if (format.encoding == C.ENCODING_PCM_FLOAT) for (i in 0 until n) s[i] = pcm.getFloat()
+ else for (i in 0 until n) s[i] = pcm.getShort() / 32768f
+ d.process(s, frames, at)
+ if (format.encoding == C.ENCODING_PCM_FLOAT) for (i in 0 until n) out.putFloat(s[i])
+ else for (i in 0 until n) out.putShort((s[i] * 32767f).toInt().coerceIn(-32768, 32767).toShort())
+ out.flip()
+ if (holding && d.holdSettled) { armed = null; holding = false }
+ }
+
+ override fun onReset() { deck = null; deckOf = null; armed = null; holding = false; marked = false; positionUs = 0 }
+}
+
+/** Tells the [SegueProcessor] at the head of the chain where each buffer sits in the song. */
+@UnstableApi
+class SegueSink(sink: AudioSink, private val processor: SegueProcessor) : ForwardingAudioSink(sink) {
+ private var offsetUs = 0L
+ private var last = Long.MIN_VALUE
+
+ override fun setOutputStreamOffsetUs(outputStreamOffsetUs: Long) {
+ offsetUs = outputStreamOffsetUs
+ super.setOutputStreamOffsetUs(outputStreamOffsetUs)
+ }
+
+ override fun handleBuffer(buffer: ByteBuffer, presentationTimeUs: Long, encodedAccessUnitCount: Int): Boolean {
+ // The same buffer comes back while the sink is full: only a new one tells a new place.
+ if (presentationTimeUs != last) { last = presentationTimeUs; processor.mark(presentationTimeUs - offsetUs) }
+ return super.handleBuffer(buffer, presentationTimeUs, encodedAccessUnitCount)
+ }
+
+ override fun flush() { last = Long.MIN_VALUE; super.flush() }
+}
diff --git a/base/app/src/main/java/com/music/spotui/cli/Cli.kt b/base/app/src/main/java/com/music/spotui/cli/Cli.kt
index 81429d86..89decd96 100644
--- a/base/app/src/main/java/com/music/spotui/cli/Cli.kt
+++ b/base/app/src/main/java/com/music/spotui/cli/Cli.kt
@@ -40,6 +40,8 @@ sealed interface CliCommand {
data class Nav(val route: String) : CliCommand
/** AutoMix on or off; null: as it is. */
data class AutoMixSet(val on: Boolean?) : CliCommand
+ /** The data-plan transitions on or off; null: as they are. */
+ data class AutoMixSegue(val on: Boolean?) : CliCommand
data object AutoMixStatus : CliCommand
/** Phone songs (a piece of each one's MediaStore folder + title) played as the local queue. */
data class AutoMixFiles(val names: List<String>) : CliCommand
@@ -57,7 +59,7 @@ object CliParser {
"status", "ext.list", "ext.install <zip path>", "ext.uninstall <id>", "ext.enable <id>", "ext.disable <id>",
"ext.setting <id> <key> <value|null>", "ext.press <id> <key>", "ext.call <id> <hook> [json]",
"ext.log <id> [lines]", "ext.storage <id>", "ext.why [n]", "play <spotify uri> [context uri]", "pause", "resume", "next", "previous",
- "nav <route>", "automix [on|off]", "automix.status", "automix.files <folder+title piece> <folder+title piece>...", "automix.seek <ms>", "jam.join <token|link>", "jam.status", "jam.leave",
+ "nav <route>", "automix [on|off]", "automix.segue [on|off]", "automix.status", "automix.files <folder+title piece> <folder+title piece>...", "automix.seek <ms>", "jam.join <token|link>", "jam.status", "jam.leave",
)
private val ID = Regex("[A-Za-z0-9][A-Za-z0-9._-]{0,127}")
@@ -106,6 +108,7 @@ object CliParser {
CliCommand.Play(uri, args.getOrNull(1)?.takeIf { it.isNotBlank() }?.also { if (!URI.matches(it)) throw CliError("play: the context is not a spotify: uri") })
}
"automix" -> CliCommand.AutoMixSet(when (args.getOrNull(0)) { null -> null; "on" -> true; "off" -> false; else -> throw CliError("automix: on or off") }).also { most(1) }
+ "automix.segue" -> CliCommand.AutoMixSegue(when (args.getOrNull(0)) { null -> null; "on" -> true; "off" -> false; else -> throw CliError("automix.segue: on or off") }).also { most(1) }
"automix.status" -> CliCommand.AutoMixStatus.also { most(0) }
"automix.files" -> CliCommand.AutoMixFiles(args.filter { it.isNotBlank() }.also { if (it.size < 2) throw CliError("automix.files: at least two files") })
"jam.join" -> CliCommand.JamJoin(arg(0, "token").let { a -> Regex("socialsession[:/]([A-Za-z0-9]+)").find(a)?.groupValues?.get(1) ?: a }).also { most(1) }
diff --git a/base/app/src/main/java/com/music/spotui/cli/CliReceiver.kt b/base/app/src/main/java/com/music/spotui/cli/CliReceiver.kt
index 6a9009e7..18fd52ed 100644
--- a/base/app/src/main/java/com/music/spotui/cli/CliReceiver.kt
+++ b/base/app/src/main/java/com/music/spotui/cli/CliReceiver.kt
@@ -216,6 +216,10 @@ class CliReceiver : BroadcastReceiver() {
c.on?.let { com.music.spotui.automix.AutoMix.set(it); com.music.spotui.di.LocalPlayer.autoMixChanged(it) }
JsonPrimitive(com.music.spotui.di.LocalPlayer.autoMixState())
}
+ is CliCommand.AutoMixSegue -> onMain {
+ c.on?.let { com.music.spotui.automix.AutoMix.changeSegue(it) }
+ JsonPrimitive(com.music.spotui.automix.AutoMix.segue)
+ }
is CliCommand.JamJoin -> jamJson(MyspotiRuntime.api.jam.join(c.token))
CliCommand.JamStatus -> { MyspotiRuntime.api.jam.refresh(); jamJson(MyspotiRuntime.api.jam.session.value) }
CliCommand.JamLeave -> { MyspotiRuntime.api.jam.leave(); JsonNull }
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 644f26c1..2d40e604 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
@@ -62,6 +62,10 @@ object LocalPlayer {
}
@androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class)
+ /** Each player's automation stage, set as its renderers are built (see [AudioRenderers]). */
+ private val segueStages = java.util.WeakHashMap<ExoPlayer, com.music.spotui.automix.SegueProcessor>()
+ private var lastSegueStage: com.music.spotui.automix.SegueProcessor? = null
+
private fun build(main: Boolean, deck: Boolean = false): ExoPlayer = ExoPlayer.Builder(Graph.app, if (deck) DeckRenderers else Renderers)
// The fading-out copy of a crossfade owns neither the audio focus nor the noisy-audio pause:
// the main player has them and the fade follows its play state.
@@ -73,21 +77,27 @@ object LocalPlayer {
.build()
// The speed and the silence skipping of the settings (the fading-out copy too: both are heard).
.also(::tune)
+ .also { p -> lastSegueStage?.let { segueStages[p] = it } }
/**
* The default renderers, with the equalizer and the spatial stage after it in the audio chain
* (each player its own, see EqualizerProcessor and SpatialProcessor), ahead of the silence
* skipping and the speed the sink adds after them. The spatial stage is last of the two: its
- * limiter is what keeps a widened peak under full scale.
+ * limiter is what keeps a widened peak under full scale. The segue stage comes first: it passes
+ * the audio as it came unless a plan is armed, and it must see the buffers whole to know their place.
*/
@androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class)
private open class AudioRenderers : androidx.media3.exoplayer.DefaultRenderersFactory(Graph.app) {
- override fun buildAudioSink(context: android.content.Context, enableFloatOutput: Boolean, enableAudioTrackPlaybackParams: Boolean): androidx.media3.exoplayer.audio.AudioSink =
- androidx.media3.exoplayer.audio.DefaultAudioSink.Builder(context)
+ override fun buildAudioSink(context: android.content.Context, enableFloatOutput: Boolean, enableAudioTrackPlaybackParams: Boolean): androidx.media3.exoplayer.audio.AudioSink {
+ val builder = androidx.media3.exoplayer.audio.DefaultAudioSink.Builder(context)
.setEnableFloatOutput(enableFloatOutput)
.setEnableAudioTrackPlaybackParams(enableAudioTrackPlaybackParams)
- .setAudioProcessors(arrayOf(EqualizerProcessor(), SpatialProcessor()))
- .build()
+ // The data plans are a test of the Mix Lab: every other build keeps its chain as it was.
+ if (!app.myspoti.engine.BuildConfig.AUTOMIX_LAB) return builder.setAudioProcessors(arrayOf(EqualizerProcessor(), SpatialProcessor())).build()
+ val stage = com.music.spotui.automix.SegueProcessor()
+ lastSegueStage = stage
+ return com.music.spotui.automix.SegueSink(builder.setAudioProcessors(arrayOf(stage, EqualizerProcessor(), SpatialProcessor())).build(), stage)
+ }
}
private object Renderers : AudioRenderers()
@@ -520,6 +530,17 @@ object LocalPlayer {
var bufferedHold = false
var recoveryGainA = 1f
var recoveryStartedAt = 0L
+ /** A data plan's outgoing lanes are armed and the deck's volume up: its automation decides what is heard. */
+ var go = false
+ private var incomingLevel: app.myspoti.automix.segue.LaneCurve? = null
+ /** The incoming song's gain in a data plan at [x] of the window. */
+ fun segueGainB(x: Double): Double {
+ val p = plan.segue ?: return 1.0
+ val c = incomingLevel ?: p.lanes.firstOrNull { it.side == app.myspoti.automix.segue.LaneSide.INCOMING && it.target == app.myspoti.automix.segue.Target.LEVEL }
+ ?.let { app.myspoti.automix.segue.LaneCurve(it) }?.also { incomingLevel = it } ?: return 1.0
+ val u = x * app.myspoti.automix.segue.SegueFormat.T_MAX
+ return if (c.isNull(u)) 0.0 else Math.pow(10.0, c.value(u) / 20)
+ }
/** Progress of the mix from the outgoing song's position (1 once it ended). */
fun progress(): Double = a?.let {
if (it.playbackState == Player.STATE_ENDED || it.playbackState == Player.STATE_IDLE) 1.0
@@ -542,6 +563,8 @@ object LocalPlayer {
private var preparationFailures = 0
private var retryDeckAt = 0L
private var askedAt = 0L
+ /** The analyses for which the policy chose plain playback: no need to ask again every tick. */
+ private var noMixFor: Pair<app.myspoti.automix.TrackAnalysis, app.myspoti.automix.TrackAnalysis>? = null
private const val PREPARE_LEAD_MS = 15_000L
/**
@@ -590,11 +613,21 @@ object LocalPlayer {
run.plan = skipPlan(p, next, pos)
com.music.spotui.automix.AutoMix.journal("skip moved: ${run.plan}")
} else if (!run.skip && pos > exitMs + 250) cancelMix("cue passed before run-up; replanning")
- else if (pos >= startAt) startRunUp(run)
+ else {
+ segueGo(run, p, pos, exitMs)
+ if (mix === run && pos >= startAt) startRunUp(run)
+ }
}
MixState.PREROLL -> {
lock(run, p, preroll = true)
- if (pos >= exitMs) {
+ segueGo(run, p, pos, exitMs)
+ if (mix !== run) return true
+ if (run.plan.segue != null) {
+ if (pos >= exitMs) {
+ if (run.go && run.deck.isPlaying) takeOver(run, p)
+ else if (pos > exitMs + 1_500) cancelMix("deck not playing at the cue; replanning")
+ }
+ } else if (pos >= exitMs) {
val d = run.deck
val remaining = (d.duration.takeIf { it > 0 } ?: Long.MAX_VALUE) - d.currentPosition
if (MixPreparation.readyToTakeOver(d.isPlaying, d.totalBufferedDuration, remaining, run.errors.lastOrNull(), run.plan.synced)) takeOver(run, p)
@@ -634,7 +667,7 @@ object LocalPlayer {
val b = tracks.getOrNull(next) ?: return null
val pair = cur to nextId
if (planningPair != pair) {
- planningPair = pair; planned = null; preparationFailures = 0; retryDeckAt = 0
+ planningPair = pair; planned = null; preparationFailures = 0; retryDeckAt = 0; noMixFor = null
}
// Policies are checked before a cached plan: a setting must apply immediately.
if (spoken(a, b)) { planned = null; whyNot(com.music.spotui.automix.AutoMix.Reason.Podcast); return null }
@@ -660,9 +693,11 @@ object LocalPlayer {
if (enoughLead && !upgraded && (old!!.provisional || old.analysisA === ra && old.analysisB === rb)) return old.plan
val refused = (if (ra == null) com.music.spotui.automix.AutoMix.missing(a.uri) else null) ?: (if (rb == null) com.music.spotui.automix.AutoMix.missing(b.uri) else null)
whyNot(refused)
+ val segue = com.music.spotui.automix.AutoMix.segueActive
+ if (segue && ra != null && rb != null && preparationFailures < 2 && noMixFor?.first === ra && noMixFor?.second === rb) return null
if (ra != null && rb != null && preparationFailures < 2) {
val earliest = (p.currentPosition + RUN_UP_MS + startLead + 500) / 1000.0
- com.music.spotui.automix.AutoMix.planAfter(ra, rb, earliest)?.let { plan ->
+ choosePlan(a, b, ra, rb, earliest).also { if (it == null && segue) { noMixFor = ra to rb; planned = null; whyNot(null); return null } }?.let { plan ->
planned = Planned(cur, nextId, plan, ra, rb)
whyNot(null)
com.music.spotui.automix.AutoMix.journal("plan ${a.title} → ${b.title}: $plan")
@@ -684,6 +719,41 @@ object LocalPlayer {
return plan
}
+ /** The plan for two analysed songs. With the data plans on, null means the policy chose plain playback. */
+ private fun choosePlan(a: LocalTrack, b: LocalTrack, ra: app.myspoti.automix.TrackAnalysis, rb: app.myspoti.automix.TrackAnalysis, earliest: Double): app.myspoti.automix.MixPlan? {
+ if (!com.music.spotui.automix.AutoMix.segueActive) return com.music.spotui.automix.AutoMix.planAfter(ra, rb, earliest)
+ val album = a.album.trim()
+ val sameAlbum = com.music.spotui.automix.AutoMix.albumOrder && album.isNotEmpty() && !album.equals("<unknown>", true) && album.equals(b.album.trim(), true)
+ val d = com.music.spotui.automix.AutoMix.decide(ra, rb, earliest, sameAlbum, rate())
+ com.music.spotui.automix.AutoMix.journal("segue ${d.level} ${d.fingerprint?.take(12) ?: ""}${if (d.attempts.isEmpty()) "" else ": ${d.why}"}")
+ return app.myspoti.automix.segue.SeguePolicy.timing(d)
+ }
+
+ /**
+ * A data plan's last check ahead of its cue: both songs placed and buffered. The outgoing lanes are
+ * armed early enough for what is still ahead of the player's buffer. Refused, the deck goes while
+ * the song is still whole, and a late failure falls back on the plain fade as any other deck.
+ */
+ private fun segueGo(run: MixRun, p: ExoPlayer, pos: Long, exitMs: Long) {
+ val plan = run.plan.segue ?: return
+ if (run.go || exitMs - pos > MixPreparation.SEGUE_ARM_LEAD_MS) return
+ val d = run.deck
+ val stageA = segueStages[p]; val stageB = segueStages[d]
+ val remaining = (d.duration.takeIf { it > 0 } ?: Long.MAX_VALUE) - d.currentPosition
+ val ready = stageA != null && stageB != null && stageA.marked && stageB.marked &&
+ MixPreparation.segueReady(d.playbackState == Player.STATE_READY, d.totalBufferedDuration, remaining,
+ MixPreparation.placed(stageA.positionUs, pos), MixPreparation.placed(stageB.positionUs, d.currentPosition),
+ if (run.state == MixState.PREROLL && run.plan.synced) run.errors.lastOrNull() else null)
+ if (ready) {
+ stageA!!.arm(plan, app.myspoti.automix.segue.LaneSide.OUTGOING)
+ d.volume = 1f
+ run.go = true
+ com.music.spotui.automix.AutoMix.journal("segue armed ${exitMs - pos} ms ahead, chain at ${stageA.positionUs / 1000} ms, player at $pos ms")
+ } else if (exitMs - pos < MixPreparation.SEGUE_ARM_MIN_MS) {
+ cancelMix("segue not ready ${exitMs - pos} ms ahead (chain ${stageA?.marked}/${stageB?.marked}, buffered ${d.totalBufferedDuration} ms); replanning")
+ }
+ }
+
/** A prepared but silent fallback can still become a real mix when its analysis finishes. */
private fun upgradePreparedFallback(run: MixRun, p: ExoPlayer, next: Int, nextId: String) {
if (preparationFailures >= 2) return
@@ -691,8 +761,16 @@ object LocalPlayer {
val b = tracks.getOrNull(next)?.let { com.music.spotui.automix.AutoMix.analysis(it.uri) } ?: return
// Once per completed analysis pair, including pairs with no future musical cue.
planned = Planned(p.currentMediaItemIndex, nextId, run.plan, a, b)
- val plan = com.music.spotui.automix.AutoMix.planAfter(a, b, (p.currentPosition + RUN_UP_MS + startLead + 500) / 1000.0) ?: return
+ val trackA = tracks.getOrNull(p.currentMediaItemIndex) ?: return
+ val trackB = tracks.getOrNull(next) ?: return
+ val plan = choosePlan(trackA, trackB, a, b, (p.currentPosition + RUN_UP_MS + startLead + 500) / 1000.0)
+ if (plan == null) {
+ // The policy says no effect: the prepared fade goes too.
+ if (com.music.spotui.automix.AutoMix.segueActive) { noMixFor = a to b; cancelMix("no mix for this pair", again = true) }
+ return
+ }
run.plan = plan
+ plan.segue?.let { s -> run.eq?.neutral(); segueStages[run.deck]?.arm(s, app.myspoti.automix.segue.LaneSide.INCOMING) }
run.startMs = (plan.entryB * 1000 - minOf(plan.entryB * 1000, RUN_UP_MS * plan.speedB)).toLong().coerceAtLeast(0L)
run.deck.playbackParameters = androidx.media3.common.PlaybackParameters((plan.speedB * rate()).toFloat())
run.lastSpeed = run.deck.playbackParameters.speed
@@ -765,14 +843,16 @@ 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, (if (com.music.spotui.automix.AutoMix.djEq) com.music.spotui.automix.DeckEq.attach(deck.audioSessionId) else null), start, skip)
+ // A data plan's lanes play in the audio chain, on no effect of the player's session.
+ val run = MixRun(plan, next, nextId, deck, (if (plan.segue == null && com.music.spotui.automix.AutoMix.djEq) com.music.spotui.automix.DeckEq.attach(deck.audioSessionId) else null), start, skip)
+ plan.segue?.let { segueStages[deck]?.arm(it, app.myspoti.automix.segue.LaneSide.INCOMING) }
run.eq?.set(app.myspoti.automix.MixPlan.KILL, 0.0)
run.lastSpeed = deck.playbackParameters.speed
run.a = p; run.eqA = deckEq
mix = run
deck.addListener(object : Player.Listener {
override fun onAudioSessionIdChanged(audioSessionId: Int) {
- if (mix !== run || run.state >= MixState.MIXING || !com.music.spotui.automix.AutoMix.djEq) return
+ if (mix !== run || run.state >= MixState.MIXING || !com.music.spotui.automix.AutoMix.djEq || run.plan.segue != null) return
run.eq?.release()
run.eq = com.music.spotui.automix.DeckEq.attach(audioSessionId)
run.eq?.set(app.myspoti.automix.MixPlan.KILL, 0.0)
@@ -888,7 +968,8 @@ object LocalPlayer {
exo = d
outgoing = a
run.eqA = deckEq
- deckEq = run.eq
+ // A later plain plan still needs the main player's EQ.
+ deckEq = run.eq ?: if (run.plan.segue != null && com.music.spotui.automix.AutoMix.djEq) com.music.spotui.automix.DeckEq.attach(d.audioSessionId) else null
run.state = MixState.MIXING
SongPlayer.onLocalFade(true)
com.music.spotui.automix.AutoMix.journal(String.format("mix started (%s), deck %+.0f ms from its place%s", run.plan.style, err, if (run.locked) ", locked" else ""))
@@ -910,6 +991,7 @@ object LocalPlayer {
run.bufferedHold = true
a.volume = (a.volume + 0.04f).coerceAtMost(1f); d.volume = 0f
run.eqA?.neutral()
+ segueStages[a]?.release()
return true
}
if (run.bufferedHold && d.isPlaying) {
@@ -917,6 +999,7 @@ object LocalPlayer {
val left = (a.duration.takeIf { it > 0 } ?: a.currentPosition) - a.currentPosition
if (left > 500 && a.isPlaying) {
// Re-enter gently from the audio actually heard; do not chase an obsolete grid after a stall.
+ segueStages[a]?.disarm(); segueStages[d]?.disarm()
plan = app.myspoti.automix.MixPlan(app.myspoti.automix.MixPlan.Style.FADE, a.currentPosition / 1000.0,
d.currentPosition / 1000.0, minOf(4.0, left / 1000.0), 1.0, 0, 0.5, 0.1, run.plan.matchB, 0.0, "fade: incoming buffer recovered")
run.plan = plan; run.lastSpeed = 0f
@@ -926,7 +1009,8 @@ object LocalPlayer {
}
}
val x = run.progress()
- if (x >= 1.0) {
+ val tail = plan.segue?.let { app.myspoti.automix.segue.SegueDeck.tailUs(it) / (plan.length * 1e6) } ?: 0.0
+ if (x >= 1.0 + tail || a.playbackState == Player.STATE_ENDED || a.playbackState == Player.STATE_IDLE) {
// A is gone.
com.music.spotui.automix.AutoMix.journal(String.format("mix done, largest gap %.0f ms", run.worstMs))
handler.removeCallbacks(tick)
@@ -934,7 +1018,14 @@ object LocalPlayer {
outgoing = null
SongPlayer.onLocalFade(false)
run.eqA?.release(); run.eqA = null; run.a = null
+ // Its lanes end neutral: the song plays on as it came.
+ segueStages[d]?.disarm()
run.state = MixState.RESTORING
+ } else if (plan.segue != null) {
+ // The lanes play in the audio chain; the players stay at full volume and hold the beat.
+ a.volume = 1f; d.volume = 1f
+ if (a.isPlaying) lock(run, a, preroll = false, quiet = run.segueGainB(x) < 0.35 || plan.style == app.myspoti.automix.MixPlan.Style.CUT)
+ return d.playWhenReady
} else {
val lv = plan.levels(x)
val recovery = if (run.recoveryStartedAt == 0L) 1f else ((android.os.SystemClock.uptimeMillis() - run.recoveryStartedAt) / 400f).coerceIn(0f, 1f)
@@ -969,11 +1060,15 @@ object LocalPlayer {
if (run.state == MixState.PREROLL) {
run.deck.pause(); run.deck.seekTo(run.startMs); run.state = MixState.READY
}
+ if (run.state < MixState.MIXING && run.go) {
+ run.go = false; run.deck.volume = 0f
+ run.a?.let { segueStages[it]?.release() }
+ }
}
/** The user moved in the song before the mix: the deck goes (prepared again if the end is still ahead). */
private fun mixMoved() {
- planned = null; preparationFailures = 0; retryDeckAt = 0
+ planned = null; preparationFailures = 0; retryDeckAt = 0; noMixFor = null
val run = mix ?: return
if (run.state < MixState.MIXING) cancelMix("seek", again = true)
}
@@ -985,6 +1080,7 @@ object LocalPlayer {
planned = null
if (!again) { preparationFailures++; retryDeckAt = android.os.SystemClock.uptimeMillis() + 500 }
// Retry a future cue; after two failures a plain fade is prepared instead. Three attempts at most.
+ if (run.go) run.a?.let { segueStages[it]?.release() }
run.eq?.release()
run.deck.release()
com.music.spotui.automix.AutoMix.journal("deck dropped: $why")
@@ -997,6 +1093,8 @@ object LocalPlayer {
mix = null
run.eqA?.release()
run.eq?.neutral()
+ segueStages[run.deck]?.release()
+ if (run.plan.segue != null) run.deck.volume = 1f
if (exo === run.deck) tune(run.deck)
com.music.spotui.automix.AutoMix.journal("mix ended early")
}
@@ -1013,7 +1111,7 @@ object LocalPlayer {
fun autoMixSettingsChanged() {
if (mix?.state?.let { it < MixState.MIXING } == true) cancelMix("settings changed", again = true)
if (mix == null) {
- planned = null; asking = null; preparationFailures = 0; retryDeckAt = 0
+ planned = null; asking = null; preparationFailures = 0; retryDeckAt = 0; noMixFor = null
updateCue()
if (exo?.isPlaying == true) { handler.removeCallbacks(tick); handler.post(tick) }
}
diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveSettingsScreen.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveSettingsScreen.kt
index 33f9ab85..ef53834b 100644
--- a/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveSettingsScreen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveSettingsScreen.kt
@@ -464,6 +464,8 @@ private fun CrossfadePage(back: () -> Unit) {
}
if (mode == TransitionMode.AUTOMIX) immersiveGroup("automix", headerRes = R.string.settings_automix_title, footerRes = R.string.settings_automix_detail) {
row {
+ if (app.myspoti.engine.BuildConfig.AUTOMIX_LAB) ImmersiveSwitchRow(stringResource(R.string.settings_automix_segue), checked = automix.segue,
+ onChecked = automix::changeSegue, detail = stringResource(R.string.settings_automix_segue_detail))
ImmersiveSwitchRow(stringResource(R.string.settings_automix_session), checked = automix.sessionDj,
onChecked = automix::changeSessionDj, detail = stringResource(R.string.settings_automix_session_detail))
}
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/SettingsScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/SettingsScreen.kt
index dbdd5d35..1d20c9f5 100644
--- a/base/app/src/main/java/com/music/spotui/ui/screens/SettingsScreen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/SettingsScreen.kt
@@ -600,6 +600,8 @@ private fun TransitionsRow() {
if (mode == TransitionMode.AUTOMIX) {
OptionRow(stringResource(R.string.settings_automix_session), stringResource(R.string.settings_automix_session_detail),
checked = automix.sessionDj, onChecked = automix::changeSessionDj)
+ if (app.myspoti.engine.BuildConfig.AUTOMIX_LAB) OptionRow(stringResource(R.string.settings_automix_segue), stringResource(R.string.settings_automix_segue_detail),
+ checked = automix.segue, onChecked = automix::changeSegue)
OptionRow(stringResource(R.string.settings_automix_on_next), stringResource(R.string.settings_automix_on_next_detail),
checked = automix.mixOnNext, onChecked = automix::changeMixOnNext)
OptionRow(stringResource(R.string.settings_automix_album_order), stringResource(R.string.settings_automix_album_order_detail),
diff --git a/base/app/src/main/res/values-fr/automix_session_strings.xml b/base/app/src/main/res/values-fr/automix_session_strings.xml
index 9b189ba0..6bff7318 100644
--- a/base/app/src/main/res/values-fr/automix_session_strings.xml
+++ b/base/app/src/main/res/values-fr/automix_session_strings.xml
@@ -2,4 +2,6 @@
<resources>
<string name="settings_automix_session">Session DJ</string>
<string name="settings_automix_session_detail">Autoriser les transitions sur un changement de section avant la fin. Désactivez pour garder davantage de chaque morceau.</string>
+ <string name="settings_automix_segue">Transitions planifiées</string>
+ <string name="settings_automix_segue_detail">Version de test : une nouvelle façon de choisir et de jouer les transitions, avec des limites plus strictes. Une paire peut rester sans mix.</string>
</resources>
diff --git a/base/app/src/main/res/values/automix_session_strings.xml b/base/app/src/main/res/values/automix_session_strings.xml
index 305b69fa..0f686479 100644
--- a/base/app/src/main/res/values/automix_session_strings.xml
+++ b/base/app/src/main/res/values/automix_session_strings.xml
@@ -2,4 +2,6 @@
<resources>
<string name="settings_automix_session">DJ session</string>
<string name="settings_automix_session_detail">Let transitions begin at a musical section before the end. Turn off to keep more of each song.</string>
+ <string name="settings_automix_segue">Plan-based transitions</string>
+ <string name="settings_automix_segue_detail">Test build: a new way of choosing and playing transitions, with stricter limits. It may leave a pair unmixed.</string>
</resources>
diff --git a/base/app/src/test/java/com/music/spotui/automix/SegueProcessorTest.kt b/base/app/src/test/java/com/music/spotui/automix/SegueProcessorTest.kt
new file mode 100644
index 00000000..2bff7423
--- /dev/null
+++ b/base/app/src/test/java/com/music/spotui/automix/SegueProcessorTest.kt
@@ -0,0 +1,117 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+package com.music.spotui.automix
+
+import androidx.media3.common.C
+import androidx.media3.common.audio.AudioProcessor
+import app.myspoti.automix.segue.Clock
+import app.myspoti.automix.segue.KnotForm
+import app.myspoti.automix.segue.LaneSide
+import app.myspoti.automix.segue.PulseState
+import app.myspoti.automix.segue.SegueFormat
+import app.myspoti.automix.segue.SeguePlan
+import app.myspoti.automix.segue.SegueUnit
+import app.myspoti.automix.segue.Target
+import app.myspoti.automix.segue.UnitKind
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import java.nio.ByteBuffer
+import java.nio.ByteOrder
+
+class SegueProcessorTest {
+ private val rate = 44_100
+
+ private fun plan(anchorUs: Long, lengthUs: Long = 100_000) = SeguePlan(SeguePlan.Origin("t", "t"),
+ SeguePlan.Side("a", null, anchorUs, SegueFormat.RATE_NOMINAL), SeguePlan.Side("b", null, anchorUs, SegueFormat.RATE_NOMINAL),
+ SeguePlan.Span(lengthUs, null, UnitKind.BAR, Clock.ELAPSED), SeguePlan.Pulse(PulseState.FREE, null, null),
+ listOf(SeguePlan.Lane(LaneSide.OUTGOING, Target.LEVEL, SegueUnit.DB, listOf(SeguePlan.Knot(0, 0, KnotForm.Step), SeguePlan.Knot(SegueFormat.T_MAX, null, KnotForm.Ramp)))))
+
+ private fun processor(encoding: Int = C.ENCODING_PCM_FLOAT, channels: Int = 1) = SegueProcessor().apply {
+ configure(AudioProcessor.AudioFormat(rate, channels, encoding)); flush()
+ }
+
+ private fun floats(n: Int, v: Float): ByteBuffer {
+ val b = ByteBuffer.allocateDirect(n * 4).order(ByteOrder.nativeOrder())
+ repeat(n) { b.putFloat(v) }; b.flip(); return b
+ }
+
+ private fun run(p: SegueProcessor, input: ByteBuffer): ByteBuffer { p.queueInput(input); return p.output.order(ByteOrder.nativeOrder()) }
+
+ @Test fun unarmedItCopiesItsInputExactly() {
+ val p = processor()
+ val out = run(p, floats(1024, 0.25f))
+ assertEquals(4096, out.remaining())
+ repeat(1024) { assertEquals(0.25f, out.getFloat(), 0f) }
+ }
+
+ @Test fun itFollowsTheSinksPlaceAndCountsFromIt() {
+ val p = processor()
+ assertFalse(p.marked)
+ p.mark(1_000_000)
+ assertTrue(p.marked)
+ run(p, floats(rate / 10, 0f))
+ assertEquals(1_100_000, p.positionUs)
+ p.mark(5_000_000)
+ assertEquals(5_000_000, p.positionUs)
+ }
+
+ @Test fun armedTheSamplesFollowTheirPlaceInTheSong() {
+ val p = processor()
+ p.arm(plan(anchorUs = 1_000_000), LaneSide.OUTGOING)
+ p.mark(500_000)
+ val before = run(p, floats(1024, 0.5f))
+ repeat(1024) { assertEquals(0.5f, before.getFloat(), 1e-6f) }
+ p.mark(2_000_000)
+ val after = run(p, floats(4096, 0.5f))
+ // The new deck starts past its window: silence, whatever the player's buffers hold before it.
+ repeat(1024) { after.getFloat() }
+ repeat(3072) { assertEquals(0f, after.getFloat(), 0f) }
+ }
+
+ @Test fun sixteenBitAudioPassesThroughTheSameLanes() {
+ val p = processor(C.ENCODING_PCM_16BIT)
+ p.arm(plan(anchorUs = 0), LaneSide.OUTGOING)
+ p.mark(1_000_000)
+ val b = ByteBuffer.allocateDirect(8192).order(ByteOrder.nativeOrder())
+ repeat(4096) { b.putShort(16384) }; b.flip()
+ val out = run(p, b)
+ repeat(2048) { out.getShort() }
+ repeat(2048) { assertEquals(0, out.getShort().toInt()) }
+ }
+
+ @Test fun releasedItReturnsToThePlainSongAndThenDisarms() {
+ val p = processor()
+ p.arm(plan(anchorUs = 0), LaneSide.OUTGOING)
+ p.mark(1_000_000)
+ run(p, floats(4096, 0.5f))
+ p.release()
+ assertTrue(p.isArmed)
+ val second = rate // the ramp lasts 400 ms
+ val out = run(p, floats(second, 0.5f))
+ repeat(second - 1) { out.getFloat() }
+ assertEquals(0.5f, out.getFloat(), 1e-6f)
+ assertFalse(p.isArmed)
+ }
+
+ @Test fun otherFormatsAreLeftAlone() {
+ assertEquals(AudioProcessor.AudioFormat.NOT_SET, SegueProcessor().configure(AudioProcessor.AudioFormat(rate, 6, C.ENCODING_PCM_FLOAT)))
+ assertEquals(AudioProcessor.AudioFormat.NOT_SET, SegueProcessor().configure(AudioProcessor.AudioFormat(rate, 2, C.ENCODING_AC3)))
+ }
+
+ @Test fun theChainAndThePlayerMustAgreeOnThePlace() {
+ assertTrue(MixPreparation.placed(61_000_000, 60_000))
+ assertTrue(MixPreparation.placed(60_000_000, 60_000))
+ assertFalse(MixPreparation.placed(61_000_000, 10_000))
+ }
+
+ @Test fun aPlanGoesOnlyWhenBothSongsArePlacedBufferedAndAligned() {
+ assertTrue(MixPreparation.segueReady(true, 800, 100_000, true, true, null))
+ assertTrue(MixPreparation.segueReady(true, 800, 100_000, true, true, 50.0))
+ assertFalse(MixPreparation.segueReady(false, 800, 100_000, true, true, null))
+ assertFalse(MixPreparation.segueReady(true, 100, 100_000, true, true, null))
+ assertFalse(MixPreparation.segueReady(true, 800, 100_000, false, true, null))
+ assertFalse(MixPreparation.segueReady(true, 800, 100_000, true, false, null))
+ assertFalse(MixPreparation.segueReady(true, 800, 100_000, true, true, 120.0))
+ }
+}
diff --git a/base/automix/src/main/kotlin/app/myspoti/automix/segue/SegueDeck.kt b/base/automix/src/main/kotlin/app/myspoti/automix/segue/SegueDeck.kt
new file mode 100644
index 00000000..e5de61bf
--- /dev/null
+++ b/base/automix/src/main/kotlin/app/myspoti/automix/segue/SegueDeck.kt
@@ -0,0 +1,198 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+package app.myspoti.automix.segue
+
+import kotlin.math.PI
+import kotlin.math.max
+import kotlin.math.min
+import kotlin.math.pow
+import kotlin.math.sqrt
+import kotlin.math.tan
+
+/**
+ * Plays one side of a plan on that song's samples, in its source time: what it does to a sample is
+ * fixed by where the sample is in the song, however long the player's buffers hold it afterwards.
+ * Pure Kotlin, so the phone and the desktop render run the same sound. Decides nothing.
+ */
+class SegueDeck(
+ private val plan: SeguePlan,
+ private val side: LaneSide,
+ private val sampleRate: Int,
+ private val channels: Int,
+ private val tuning: SegueTuning = SegueTuning(),
+) {
+ private val s = plan.side(side)
+ private val level = curve(Target.LEVEL)
+ private val bottom = curve(Target.SHELF_BOTTOM); private val core = curve(Target.BAND_CORE); private val top = curve(Target.SHELF_TOP)
+ private val sweep = curve(Target.SWEEP_HZ); private val peak = curve(Target.SWEEP_PEAK)
+ private val room = curve(Target.SEND_ROOM); private val echo = curve(Target.SEND_ECHO)
+ private val usesSends = room != null || echo != null
+
+ private fun curve(t: Target) = plan.lanes.firstOrNull { it.side == side && it.target == t }?.let(::LaneCurve)
+
+ private val shelfBass = Array(channels) { Shape() }
+ private val bellCore = Array(channels) { Shape() }
+ private val shelfTop = Array(channels) { Shape() }
+ private val svf = Array(channels) { Svf() }
+ private val echoes = if (echo != null) Array(channels) { Delay(frames(tuning.echoDelayUs)) } else null
+ private val rooms = if (room != null) Array(channels) { Room(tuning, sampleRate) } else null
+
+ private var lastGain = Double.NaN
+ private val coreHz = sqrt(tuning.shelfLowHz * tuning.shelfHighHz)
+ private var filterMix = 0.0
+ private var holdMix = 0.0
+ private val holdStep = 1.0 / max(1.0, tuning.holdRampUs * sampleRate / 1e6)
+
+ /** The plain song, smoothly, whatever the plan says from now on: the other song has stalled. */
+ @Volatile var hold: Boolean = false
+
+ /** [hold] has finished its ramp: only the plain song comes out. */
+ val holdSettled: Boolean get() = holdMix >= 1.0
+
+ private fun frames(us: Long) = max(1, (us * sampleRate / 1_000_000).toInt())
+
+ /** Position on the lanes' 0..1000000 scale of a source position. */
+ private fun u(sourceUs: Double): Double =
+ (sourceUs - s.anchorUs) * SegueFormat.RATE_NOMINAL / s.ratePpm / plan.span.lengthUs * SegueFormat.T_MAX
+
+ private fun gain(u: Double): Double {
+ val l = level ?: return 1.0
+ return if (l.isNull(u)) 0.0 else 10.0.pow(l.value(u) / 20)
+ }
+
+ /** [x] holds [frames] interleaved frames, changed in place; [sourceUs] is the first frame's place in the song. */
+ fun process(x: FloatArray, frames: Int, sourceUs: Long) {
+ val block = max(1, tuning.blockFrames)
+ var done = 0
+ while (done < frames) {
+ val n = min(block, frames - done)
+ val atUs = sourceUs + done * 1e6 / sampleRate
+ run(x, done, n, u(atUs), u(atUs + n * 1e6 / sampleRate))
+ done += n
+ }
+ }
+
+ private fun run(x: FloatArray, from: Int, n: Int, u0: Double, u1: Double) {
+ val g1 = gain(u1)
+ val g0 = if (lastGain.isNaN()) gain(u0) else lastGain
+ val bassDb = bottom?.value(u1) ?: 0.0; val coreDb = core?.value(u1) ?: 0.0; val topDb = top?.value(u1) ?: 0.0
+ val eqNeutral = bassDb == 0.0 && coreDb == 0.0 && topDb == 0.0
+ for (c in 0 until channels) {
+ shelfBass[c].lowShelf(tuning.shelfLowHz, bassDb, tuning.shelfQ, sampleRate)
+ bellCore[c].bell(coreHz, coreDb, tuning.coreQ, sampleRate)
+ shelfTop[c].highShelf(tuning.shelfHighHz, topDb, tuning.shelfQ, sampleRate)
+ }
+ val hz = sweep?.value(u1) ?: SegueFormat.SWEEP_OPEN_HZ
+ val wantFilter = if (hz < SegueFormat.SWEEP_OPEN_HZ * 0.999) 1.0 else 0.0
+ val q = sqrt(0.5) * (peak?.value(u1) ?: 1.0)
+ if (sweep != null) for (f in svf) f.tune(hz, q, sampleRate)
+ val roomSend0 = room?.value(u0) ?: 0.0; val roomSend1 = room?.value(u1) ?: 0.0
+ val echoSend0 = echo?.value(u0) ?: 0.0; val echoSend1 = echo?.value(u1) ?: 0.0
+ for (i in 0 until n) {
+ val p = (i + 1.0) / n
+ val gain = g0 + (g1 - g0) * p
+ val mix = filterMix + (wantFilter - filterMix) * p
+ holdMix = if (hold) min(1.0, holdMix + holdStep) else max(0.0, holdMix - holdStep)
+ for (c in 0 until channels) {
+ val k = (from + i) * channels + c
+ val dry = x[k].toDouble()
+ // Run even at 0 dB, where they return the input exactly, so a band's cut starts from a settled state.
+ var y = shelfTop[c].run(bellCore[c].run(shelfBass[c].run(dry)))
+ if (sweep != null) {
+ val filtered = svf[c].run(y)
+ y += (filtered - y) * mix
+ }
+ var out = y * gain
+ if (usesSends) {
+ // Sends tap the signal before the fader: a tail outlives the song's level.
+ echoes?.let { out += it[c].run(y * (echoSend0 + (echoSend1 - echoSend0) * p), tuning.echoFeedback) }
+ rooms?.let { out += it[c].run(y * (roomSend0 + (roomSend1 - roomSend0) * p)) }
+ }
+ x[k] = (if (holdMix > 0) dry * holdMix + out * (1 - holdMix) else if (gain == 1.0 && eqNeutral && mix == 0.0 && !usesSends) dry else out).toFloat()
+ }
+ }
+ lastGain = g1; filterMix = wantFilter
+ }
+
+ /** Shelves and a bell on one state-variable filter: stable while they move, and the identity at 0 dB. */
+ private class Shape {
+ private var a1 = 1.0; private var a2 = 0.0; private var a3 = 0.0
+ private var m0 = 1.0; private var m1 = 0.0; private var m2 = 0.0
+ private var ic1 = 0.0; private var ic2 = 0.0
+ private var set = Double.NaN
+ private fun prepare(g: Double, k: Double) { a1 = 1 / (1 + g * (g + k)); a2 = g * a1; a3 = g * a2 }
+ private fun w(hz: Double, rate: Int) = tan(PI * min(hz, rate * 0.45) / rate)
+ fun lowShelf(hz: Double, db: Double, q: Double, rate: Int) {
+ if (db == set) return; set = db
+ val a = 10.0.pow(db / 40); val k = 1 / q
+ prepare(w(hz, rate) / sqrt(a), k); m0 = 1.0; m1 = k * (a - 1); m2 = a * a - 1
+ }
+ fun highShelf(hz: Double, db: Double, q: Double, rate: Int) {
+ if (db == set) return; set = db
+ val a = 10.0.pow(db / 40); val k = 1 / q
+ prepare(w(hz, rate) * sqrt(a), k); m0 = a * a; m1 = k * (1 - a) * a; m2 = 1 - a * a
+ }
+ fun bell(hz: Double, db: Double, q: Double, rate: Int) {
+ if (db == set) return; set = db
+ val a = 10.0.pow(db / 40); val k = 1 / (q * a)
+ prepare(w(hz, rate), k); m0 = 1.0; m1 = k * (a * a - 1); m2 = 0.0
+ }
+ fun run(x: Double): Double {
+ val v3 = x - ic2
+ val v1 = a1 * ic1 + a2 * v3
+ val v2 = ic2 + a2 * ic1 + a3 * v3
+ ic1 = 2 * v1 - ic1; ic2 = 2 * v2 - ic2
+ return m0 * x + m1 * v1 + m2 * v2
+ }
+ }
+
+ /** A low-pass that stays stable while its cutoff moves. */
+ private class Svf {
+ private var g = 1.0; private var r = 1.414; private var h = 0.0
+ private var s1 = 0.0; private var s2 = 0.0
+ fun tune(hz: Double, q: Double, rate: Int) {
+ g = tan(PI * min(hz, rate * 0.45) / rate); r = 1 / max(0.1, q); h = 1 / (1 + r * g + g * g)
+ }
+ fun run(x: Double): Double {
+ val hp = (x - (r + g) * s1 - s2) * h
+ val bp = g * hp + s1; s1 = g * hp + bp
+ val lp = g * bp + s2; s2 = g * bp + lp
+ return lp
+ }
+ }
+
+ private class Delay(size: Int) {
+ private val line = DoubleArray(size); private var i = 0
+ fun run(x: Double, feedback: Double): Double {
+ val out = line[i]; line[i] = x + out * feedback; i = (i + 1) % line.size
+ return out
+ }
+ }
+
+ private class Room(t: SegueTuning, rate: Int) {
+ private val combs = t.roomCombUs.map { Delay(max(1, (it * rate / 1_000_000).toInt())) }
+ private val passes = t.roomAllPassUs.map { DoubleArray(max(1, (it * rate / 1_000_000).toInt())) }
+ private val at = IntArray(passes.size)
+ private val feedback = t.roomCombFeedback; private val pass = t.roomAllPassGain
+ private val scale = 1.0 / max(1, combs.size)
+ fun run(x: Double): Double {
+ var y = combs.sumOf { it.run(x, feedback) } * scale
+ for (j in passes.indices) {
+ val line = passes[j]; val d = line[at[j]]
+ val out = d - pass * y
+ line[at[j]] = y + pass * out
+ at[j] = (at[j] + 1) % line.size
+ y = out
+ }
+ return y
+ }
+ }
+
+ companion object {
+ /** What this engine can execute. Anything else is refused and the transition is left to normal playback. */
+ fun playable(p: SeguePlan): Boolean = p.span.clock == Clock.ELAPSED && p.gestures.isEmpty() && SegueValidator.structural(p).isEmpty()
+
+ /** How long past the window the outgoing song must keep running for its sends to ring out. */
+ fun tailUs(p: SeguePlan, t: SegueTuning = SegueTuning()): Long =
+ if (p.lanes.any { it.side == LaneSide.OUTGOING && (it.target == Target.SEND_ROOM || it.target == Target.SEND_ECHO) }) t.sendTailUs else 0
+ }
+}
diff --git a/base/automix/src/main/kotlin/app/myspoti/automix/segue/SegueTuning.kt b/base/automix/src/main/kotlin/app/myspoti/automix/segue/SegueTuning.kt
index e98f1218..332f2ff5 100644
--- a/base/automix/src/main/kotlin/app/myspoti/automix/segue/SegueTuning.kt
+++ b/base/automix/src/main/kotlin/app/myspoti/automix/segue/SegueTuning.kt
@@ -131,6 +131,28 @@ data class SegueTuning(
/** Tempo return after the window: share of the speed per beat [R], least beats [R]. */
val restoreRatePerBeat: Double = 0.001,
val restoreMinBeats: Double = 16.0,
+
+ // ── The engine's sound ──
+ /** Automation is read every this many frames, gains interpolated between [R]. */
+ val blockFrames: Int = 64,
+ /** Band edges of the shelves [R]. */
+ val shelfLowHz: Double = 180.0,
+ val shelfHighHz: Double = 2_500.0,
+ /** Slope of the shelves [U], width of the core bell between them [I]. */
+ val shelfQ: Double = 0.7071,
+ val coreQ: Double = 0.5,
+ /** Echo send: delay [I], feedback [I]. */
+ val echoDelayUs: Long = 375_000,
+ val echoFeedback: Double = 0.35,
+ /** Room send: comb delays and all-pass delays of a small Schroeder reverb [U], comb feedback [I], all-pass gain [U]. */
+ val roomCombUs: List<Long> = listOf(29_700, 37_100, 41_100, 43_700),
+ val roomAllPassUs: List<Long> = listOf(5_000, 1_700),
+ val roomCombFeedback: Double = 0.75,
+ val roomAllPassGain: Double = 0.7,
+ /** How long the outgoing player keeps running for a send's tail [I]. */
+ val sendTailUs: Long = 3_000_000,
+ /** Back to the plain song when the incoming one stalls [R]. */
+ val holdRampUs: Long = 400_000,
) {
companion object {
/** The band where two bass lines mask each other [U]. Fixed at analysis: not varied by the harness. */
diff --git a/base/automix/src/test/kotlin/app/myspoti/automix/segue/SegueDeckTest.kt b/base/automix/src/test/kotlin/app/myspoti/automix/segue/SegueDeckTest.kt
new file mode 100644
index 00000000..b031857f
--- /dev/null
+++ b/base/automix/src/test/kotlin/app/myspoti/automix/segue/SegueDeckTest.kt
@@ -0,0 +1,192 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+package app.myspoti.automix.segue
+
+import org.junit.Assert.assertArrayEquals
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import kotlin.math.PI
+import kotlin.math.abs
+import kotlin.math.log10
+import kotlin.math.sin
+import kotlin.math.sqrt
+
+class SegueDeckTest {
+ private val rate = 44_100
+ private val m = SegueFormat.T_MAX
+ private val step = KnotForm.Step
+ private val ramp = KnotForm.Ramp
+
+ private fun lane(side: LaneSide, target: Target, vararg k: SeguePlan.Knot) = SeguePlan.Lane(side, target, target.unit, k.toList())
+ private fun plan(vararg lanes: SeguePlan.Lane, lengthUs: Long = 1_000_000, anchorA: Long = 1_000_000, anchorB: Long = 1_000_000, rateB: Long = SegueFormat.RATE_NOMINAL) =
+ SeguePlan(SeguePlan.Origin("t", "t"), SeguePlan.Side("a", null, anchorA, SegueFormat.RATE_NOMINAL), SeguePlan.Side("b", null, anchorB, rateB),
+ SeguePlan.Span(lengthUs, null, UnitKind.BAR, Clock.ELAPSED), SeguePlan.Pulse(PulseState.FREE, null, null), lanes.toList())
+
+ private fun tone(hz: Double, seconds: Double, channels: Int = 1) = FloatArray((seconds * rate).toInt() * channels) { i ->
+ (0.5 * sin(2 * PI * hz * (i / channels) / rate)).toFloat()
+ }
+
+ private fun rms(x: FloatArray, from: Double, to: Double): Double {
+ val a = (from * rate).toInt(); val b = (to * rate).toInt()
+ var s = 0.0
+ for (i in a until b) s += x[i] * x[i]
+ return sqrt(s / (b - a))
+ }
+ private fun db(x: Double) = 20 * log10(x)
+
+ /** The source runs from 0 for [seconds]; the window starts at 1 s and lasts 1 s. */
+ private fun run(p: SeguePlan, side: LaneSide, x: FloatArray, channels: Int = 1, tuning: SegueTuning = SegueTuning()): FloatArray {
+ val out = x.copyOf()
+ SegueDeck(p, side, rate, channels, tuning).process(out, out.size / channels, 0)
+ return out
+ }
+
+ @Test fun neutralLanesLeaveTheSamplesExactly() {
+ val p = plan(lane(LaneSide.OUTGOING, Target.LEVEL, SeguePlan.Knot(0, 0, step), SeguePlan.Knot(m, 0, ramp)),
+ lane(LaneSide.OUTGOING, Target.SHELF_BOTTOM, SeguePlan.Knot(0, null, step), SeguePlan.Knot(m, null, step)))
+ val x = tone(440.0, 3.0)
+ assertArrayEquals(x, run(p, LaneSide.OUTGOING, x), 0f)
+ }
+
+ @Test fun aLaneOfTheOtherSideDoesNothing() {
+ val p = plan(lane(LaneSide.INCOMING, Target.LEVEL, SeguePlan.Knot(0, null, step), SeguePlan.Knot(m, null, step)))
+ val x = tone(440.0, 3.0)
+ assertArrayEquals(x, run(p, LaneSide.OUTGOING, x), 0f)
+ }
+
+ @Test fun beforeItsWindowAnIncomingSongIsSilentAndAfterItWhole() {
+ val p = plan(lane(LaneSide.INCOMING, Target.LEVEL, SeguePlan.Knot(0, null, step), SeguePlan.Knot(m, 0, ramp)))
+ val out = run(p, LaneSide.INCOMING, tone(440.0, 3.0))
+ // Automation is read per block, so the rise can begin up to one block early.
+ for (i in 0 until rate - SegueTuning().blockFrames) assertEquals(0f, out[i], 0f)
+ assertEquals(db(rms(tone(440.0, 3.0), 2.1, 2.9)), db(rms(out, 2.1, 2.9)), 0.01)
+ }
+
+ @Test fun afterItsWindowAnOutgoingSongIsSilent() {
+ val p = plan(lane(LaneSide.OUTGOING, Target.LEVEL, SeguePlan.Knot(0, 0, step), SeguePlan.Knot(m, null, ramp)))
+ val out = run(p, LaneSide.OUTGOING, tone(440.0, 3.0))
+ for (i in (2.01 * rate).toInt() until out.size) assertEquals(0f, out[i], 0f)
+ val whole = rms(tone(440.0, 3.0), 0.1, 0.9)
+ assertEquals(db(whole) - 30, db(rms(out, 1.49, 1.51)), 0.5) // half way to the −60 dB floor
+ }
+
+ @Test fun positionsAreSourceTimeUnderTheRate() {
+ // At 2× the window lasts 2 s of source: its middle is at 2 s from the anchor at 1 s... 1 + 1.
+ val p = plan(lane(LaneSide.INCOMING, Target.LEVEL, SeguePlan.Knot(0, 0, step), SeguePlan.Knot(m, -40_000, ramp)), rateB = 2_000_000)
+ val out = run(p, LaneSide.INCOMING, tone(440.0, 4.0))
+ assertEquals(db(rms(tone(440.0, 4.0), 0.1, 0.9)) - 20, db(rms(out, 1.99, 2.01)), 0.5)
+ }
+
+ @Test fun aSplitBlockSoundsTheSameAsAWholeOne() {
+ val p = plan(lane(LaneSide.INCOMING, Target.LEVEL, SeguePlan.Knot(0, null, step), SeguePlan.Knot(m, 0, ramp)),
+ lane(LaneSide.INCOMING, Target.SHELF_BOTTOM, SeguePlan.Knot(0, -30_000, step), SeguePlan.Knot(m, 0, ramp)))
+ val x = tone(100.0, 3.0)
+ val whole = x.copyOf(); SegueDeck(p, LaneSide.INCOMING, rate, 1).process(whole, whole.size, 0)
+ val parts = x.copyOf(); val d = SegueDeck(p, LaneSide.INCOMING, rate, 1)
+ // Whole numbers of blocks, as the sink's buffers mostly are: same reading points.
+ val chunk = 64 * 37
+ var at = 0
+ while (at < parts.size) {
+ val n = minOf(chunk, parts.size - at)
+ val piece = parts.copyOfRange(at, at + n)
+ d.process(piece, n, Math.round(at * 1e6 / rate))
+ piece.copyInto(parts, at); at += n
+ }
+ for (i in whole.indices) assertEquals(whole[i], parts[i], 1e-3f)
+ }
+
+ @Test fun theBassShelfCutsLowsAndSparesHighs() {
+ val p = plan(lane(LaneSide.OUTGOING, Target.SHELF_BOTTOM, SeguePlan.Knot(0, -30_000, step), SeguePlan.Knot(m, -30_000, step)))
+ val bass = tone(60.0, 2.0); val treble = tone(5_000.0, 2.0)
+ assertTrue(db(rms(run(p, LaneSide.OUTGOING, bass), 1.0, 1.9)) < db(rms(bass, 1.0, 1.9)) - 20)
+ assertEquals(db(rms(treble, 1.0, 1.9)), db(rms(run(p, LaneSide.OUTGOING, treble), 1.0, 1.9)), 1.0)
+ }
+
+ @Test fun theTopShelfAndTheCoreDoTheirOwnBands() {
+ val top = plan(lane(LaneSide.OUTGOING, Target.SHELF_TOP, SeguePlan.Knot(0, -20_000, step), SeguePlan.Knot(m, -20_000, step)))
+ val core = plan(lane(LaneSide.OUTGOING, Target.BAND_CORE, SeguePlan.Knot(0, -20_000, step), SeguePlan.Knot(m, -20_000, step)))
+ val treble = tone(10_000.0, 2.0); val middle = tone(700.0, 2.0)
+ assertTrue(db(rms(run(top, LaneSide.OUTGOING, treble), 1.0, 1.9)) < db(rms(treble, 1.0, 1.9)) - 15)
+ assertEquals(db(rms(middle, 1.0, 1.9)), db(rms(run(top, LaneSide.OUTGOING, middle), 1.0, 1.9)), 1.0)
+ assertTrue(db(rms(run(core, LaneSide.OUTGOING, middle), 1.0, 1.9)) < db(rms(middle, 1.0, 1.9)) - 15)
+ }
+
+ @Test fun theSweepClosesTheFilter() {
+ val p = plan(lane(LaneSide.OUTGOING, Target.SWEEP_HZ, SeguePlan.Knot(0, null, step), SeguePlan.Knot(m, 400_000, KnotForm.Octave)))
+ val x = tone(5_000.0, 3.0)
+ val out = run(p, LaneSide.OUTGOING, x)
+ assertEquals(db(rms(x, 0.2, 0.9)), db(rms(out, 0.2, 0.9)), 0.1)
+ assertTrue(db(rms(out, 2.1, 2.9)) < db(rms(x, 2.1, 2.9)) - 30)
+ val low = tone(100.0, 3.0)
+ assertEquals(db(rms(low, 2.1, 2.9)), db(rms(run(p, LaneSide.OUTGOING, low), 2.1, 2.9)), 1.0)
+ }
+
+ @Test fun theSweepsPeakAccentsItsCutoff() {
+ fun swept(peak: Long): Double {
+ val p = plan(lane(LaneSide.OUTGOING, Target.SWEEP_HZ, SeguePlan.Knot(0, 1_000_000, step), SeguePlan.Knot(m, 1_000_000, step)),
+ lane(LaneSide.OUTGOING, Target.SWEEP_PEAK, SeguePlan.Knot(0, peak, step), SeguePlan.Knot(m, peak, step)))
+ return db(rms(run(p, LaneSide.OUTGOING, tone(1_000.0, 2.0)), 1.0, 1.9))
+ }
+ assertTrue(swept(4_000) > swept(1_000) + 6)
+ }
+
+ @Test fun aMicroFadeHasNoClick() {
+ val microUs = 30_000L
+ val p = plan(lane(LaneSide.INCOMING, Target.LEVEL, SeguePlan.Knot(0, null, step), SeguePlan.Knot(m, 0, ramp)), lengthUs = microUs)
+ val out = run(p, LaneSide.INCOMING, tone(1_000.0, 2.0))
+ // The sample-to-sample step of the tone itself is about 2πf/sr × 0.5 ≈ 0.07.
+ var largest = 0f
+ for (i in rate - 10 until rate + 2_000) largest = maxOf(largest, abs(out[i + 1] - out[i]))
+ assertTrue("$largest", largest < 0.08f)
+ assertEquals(0f, out[rate - SegueTuning().blockFrames - 1], 0f)
+ assertEquals(db(rms(tone(1_000.0, 2.0), 1.2, 1.9)), db(rms(out, 1.2, 1.9)), 0.01)
+ }
+
+ @Test fun echoAndRoomRingOutAfterTheFader() {
+ val fader = lane(LaneSide.OUTGOING, Target.LEVEL, SeguePlan.Knot(0, 0, step), SeguePlan.Knot(m, null, ramp))
+ for (send in listOf(Target.SEND_ECHO, Target.SEND_ROOM)) {
+ val p = plan(fader, lane(LaneSide.OUTGOING, send, SeguePlan.Knot(0, 500, step), SeguePlan.Knot(m, null, ramp)))
+ val x = tone(440.0, 2.0) + FloatArray(rate)
+ val out = run(p, LaneSide.OUTGOING, x)
+ assertTrue("$send", rms(out, 2.05, 2.25) > 0.001)
+ }
+ val dry = run(plan(fader), LaneSide.OUTGOING, tone(440.0, 2.0) + FloatArray(rate))
+ assertEquals(0.0, rms(dry, 2.05, 2.25), 1e-9)
+ }
+
+ @Test fun holdBringsThePlainSongBack() {
+ val p = plan(lane(LaneSide.OUTGOING, Target.LEVEL, SeguePlan.Knot(0, null, step), SeguePlan.Knot(m, null, step)))
+ val d = SegueDeck(p, LaneSide.OUTGOING, rate, 1)
+ val x = tone(440.0, 1.0)
+ val silent = x.copyOf(); d.process(silent, silent.size, 0)
+ assertEquals(0.0, rms(silent, 0.1, 0.9), 0.0)
+ d.hold = true
+ val back = x.copyOf(); d.process(back, back.size, 1_000_000)
+ assertEquals(db(rms(x, 0.6, 0.9)), db(rms(back, 0.6, 0.9)), 0.01)
+ }
+
+ @Test fun stereoChannelsAreKeptApart() {
+ val p = plan(lane(LaneSide.OUTGOING, Target.SHELF_BOTTOM, SeguePlan.Knot(0, -30_000, step), SeguePlan.Knot(m, -30_000, step)))
+ val x = FloatArray(rate * 2 * 2) { i -> if (i % 2 == 0) (0.5 * sin(2 * PI * 60.0 * (i / 2) / rate)).toFloat() else (0.5 * sin(2 * PI * 5_000.0 * (i / 2) / rate)).toFloat() }
+ val out = run(p, LaneSide.OUTGOING, x, channels = 2)
+ val left = FloatArray(out.size / 2) { out[2 * it] }; val right = FloatArray(out.size / 2) { out[2 * it + 1] }
+ assertTrue(rms(left, 1.0, 1.9) < 0.1)
+ assertTrue(rms(right, 1.0, 1.9) > 0.3)
+ }
+
+ @Test fun theEngineRefusesWhatItCannotExecute() {
+ val fine = plan(lane(LaneSide.OUTGOING, Target.LEVEL, SeguePlan.Knot(0, 0, step), SeguePlan.Knot(m, null, ramp)))
+ assertTrue(SegueDeck.playable(fine))
+ assertFalse(SegueDeck.playable(fine.copy(span = fine.span.copy(clock = Clock.SOURCE))))
+ assertFalse(SegueDeck.playable(fine.copy(gestures = listOf(SeguePlan.Gesture(GestureKind.REPEAT, 0, 2)))))
+ assertFalse(SegueDeck.playable(fine.copy(span = fine.span.copy(lengthUs = 0))))
+ }
+
+ @Test fun onlySendsAskForATail() {
+ val fader = lane(LaneSide.OUTGOING, Target.LEVEL, SeguePlan.Knot(0, 0, step), SeguePlan.Knot(m, null, ramp))
+ assertEquals(0L, SegueDeck.tailUs(plan(fader)))
+ val t = SegueTuning()
+ assertEquals(t.sendTailUs, SegueDeck.tailUs(plan(fader, lane(LaneSide.OUTGOING, Target.SEND_ROOM, SeguePlan.Knot(0, 0, step), SeguePlan.Knot(m, 0, step)))))
+ }
+}
diff --git a/docs/automix/segue-design.md b/docs/automix/segue-design.md
index 7706abde..f17402dc 100644
--- a/docs/automix/segue-design.md
+++ b/docs/automix/segue-design.md
@@ -111,6 +111,34 @@ alone, `against` also needs the current analyses:
`null` has a meaning for all of today's targets, so that rule rejects nothing yet: each new target
must state its own in `Target`.
+## Engine
+
+The engine executes lanes and decides nothing. `SegueDeck` (pure Kotlin) is the sound, used both by
+the phone and by the desktop render, so what is measured is what plays.
+
+On the phone, `SegueProcessor` runs it at the head of each player's audio chain. An audio processor
+acts ahead of the player's buffer, so it would be heard late if it followed the clock; here every
+sample's gain is fixed by the sample's place in the song, which `SegueSink` reads from each buffer's
+presentation time. The lock on the beats nudges only the player's speed, downstream of the chain, so
+the lanes stay on the song's musical time. Unarmed, the stage copies its input exactly. It exists only
+in the Mix Lab build; other builds keep their chain as it was.
+
+- The incoming deck is armed when prepared: before its window its level lane is null, so its run-up is silent.
+- The outgoing side is armed `SEGUE_ARM_LEAD_MS` before the cue, once both songs are placed and
+ buffered, ahead of what the player has already buffered. Past `SEGUE_ARM_MIN_MS` without that, the
+ deck is dropped while the song is still whole, and the plan is computed again.
+- If the incoming song stalls during the window, the outgoing one returns to its plain sound
+ (`holdRampUs`), then both re-enter through the existing gentle fade.
+- After the window the incoming tempo returns to its own as with other plans (`restoreRatePerBeat`,
+ `restoreMinBeats`). This is not in the plan: it comes after the window and depends only on the rate.
+
+Shelves and the core bell are state-variable filters: stable while they move, and exactly the identity
+at 0 dB. Sends tap the signal ahead of the fader, so a tail outlives the song's level. The policy
+does not write sends yet, as no class's treatment calls for them.
+
+Next, and the provisional fade used while an analysis is missing, stay on the earlier plans: they
+have no analysis to fill `audioKey` from, or no time for a policy to run.
+
## Analysis the policy reads
Each quantity carries a reliability: an uncertain measure weighs less, it is not treated as an average.
@@ -188,3 +216,7 @@ marked `[R]`, reused from this repository.
| `simpleFadeUs`, `entryZoneUs`, `halfDoubleMaxBars` | 6 s, 40 s, 8 bars `[R]` | Values the player already uses |
| Lane shapes (`bassKillDb`, `outgoingTopDb`, `incomingBedGain`…) | see `SegueTuning` `[R]` | The curves the player already plays |
| `sweepClosedHz`, `sweepPeakRatio` | 400 Hz, 1.2 | The design asks for a filtered exit without values |
+| `blockFrames`, `shelfLowHz`, `shelfHighHz`, `holdRampUs` | 64, 180 Hz, 2.5 kHz, 400 ms `[R]` | Values the player and the render already use |
+| `shelfQ`, `coreQ` | 0.707 `[U]`, 0.5 | The slope of a shelf, and a bell wide enough to span the middle band |
+| `echoDelayUs`, `echoFeedback`, `sendTailUs` | 375 ms, 0.35, 3 s | The sends need a sound; the policy does not use them yet |
+| `roomCombUs`, `roomAllPassUs`, `roomCombFeedback`, `roomAllPassGain` | Schroeder delays `[U]`, 0.75, 0.7 `[U]` | Same |