Skip to content

Native Android client for Spotify, built with Jetpack Compose

AutoMix: segue plan format, canonical JSON, fingerprint and validation

kota-zo85b4959aecde
diff --git a/base/automix/src/main/kotlin/app/myspoti/automix/segue/SegueFormat.kt b/base/automix/src/main/kotlin/app/myspoti/automix/segue/SegueFormat.kt
new file mode 100644
index 00000000..55de44ff
--- /dev/null
+++ b/base/automix/src/main/kotlin/app/myspoti/automix/segue/SegueFormat.kt
@@ -0,0 +1,30 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+package app.myspoti.automix.segue
+
+/**
+ * The scales of the plan format. They define what a stored number means, so they are constants, not
+ * tuning; every value is justified in docs/automix/segue-design.md. Policy values are in [SegueTuning].
+ */
+object SegueFormat {
+ const val SCHEMA_PREFIX = "segue/"
+ const val MAJOR = 1
+ const val SCHEMA = "$SCHEMA_PREFIX$MAJOR"
+
+ /** Nominal speed on the rate scale: parts per million, so rounding stays under 32 µs over 64 s. */
+ const val RATE_NOMINAL = 1_000_000L
+
+ /** Knot positions run from 0 to this over the window. */
+ const val T_MAX = 1_000_000
+
+ /** Knot values are stored in thousandths of their unit. */
+ const val VALUE_SCALE = 1_000L
+
+ /** `ease:<k>` is position^(k / this). */
+ const val EASE_UNIT = 1_000
+
+ /** The number a silent knot stands for while a ramp runs towards or away from it. */
+ const val LEVEL_FLOOR_DB = -60.0
+
+ /** The cutoff a null sweep knot stands for: the filter is fully open. */
+ const val SWEEP_OPEN_HZ = 20_000.0
+}
diff --git a/base/automix/src/main/kotlin/app/myspoti/automix/segue/SegueJson.kt b/base/automix/src/main/kotlin/app/myspoti/automix/segue/SegueJson.kt
new file mode 100644
index 00000000..7235729d
--- /dev/null
+++ b/base/automix/src/main/kotlin/app/myspoti/automix/segue/SegueJson.kt
@@ -0,0 +1,214 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+package app.myspoti.automix.segue
+
+import java.math.BigDecimal
+import java.security.MessageDigest
+
+class SegueFormatException(message: String) : Exception(message)
+
+/** A strict JSON reader and a canonical writer: sorted keys, no spaces, one spelling per number. */
+internal object SegueJson {
+ fun write(value: Any?): String = StringBuilder().also { write(value, it) }.toString()
+
+ private fun write(v: Any?, o: StringBuilder) {
+ when (v) {
+ null -> o.append("null")
+ is Boolean -> o.append(v)
+ is Int, is Long -> o.append(v)
+ is BigDecimal -> o.append(canonical(v))
+ is String -> string(v, o)
+ is List<*> -> { o.append('['); v.forEachIndexed { i, x -> if (i > 0) o.append(','); write(x, o) }; o.append(']') }
+ is Map<*, *> -> {
+ o.append('{')
+ v.entries.map { it.key as String to it.value }.sortedBy { it.first }.forEachIndexed { i, (k, x) ->
+ if (i > 0) o.append(','); string(k, o); o.append(':'); write(x, o)
+ }
+ o.append('}')
+ }
+ else -> throw IllegalArgumentException("not JSON: ${v.javaClass}")
+ }
+ }
+
+ fun canonical(d: BigDecimal): String = if (d.signum() == 0) "0" else d.stripTrailingZeros().toPlainString()
+
+ private fun string(s: String, o: StringBuilder) {
+ o.append('"')
+ for (c in s) when {
+ c == '"' -> o.append("\\\"")
+ c == '\\' -> o.append("\\\\")
+ c == '\n' -> o.append("\\n")
+ c == '\r' -> o.append("\\r")
+ c == '\t' -> o.append("\\t")
+ c < ' ' -> o.append(String.format("\\u%04x", c.code))
+ else -> o.append(c)
+ }
+ o.append('"')
+ }
+
+ /** Objects become maps, numbers BigDecimal. Duplicate keys, exponents and trailing text are refused. */
+ fun read(text: String): Any? = Reader(text).document()
+
+ private class Reader(private val s: String) {
+ private var i = 0
+ fun document(): Any? { val v = value(0); space(); if (i != s.length) fail("trailing text"); return v }
+ private fun fail(why: String): Nothing = throw SegueFormatException("JSON at $i: $why")
+ private fun space() { while (i < s.length && s[i] in " \t\r\n") i++ }
+ private fun value(depth: Int): Any? {
+ if (depth > 16) fail("too deep")
+ space()
+ if (i >= s.length) fail("unexpected end")
+ return when (s[i]) {
+ '{' -> obj(depth)
+ '[' -> arr(depth)
+ '"' -> str()
+ 't' -> word("true", true)
+ 'f' -> word("false", false)
+ 'n' -> word("null", null)
+ else -> num()
+ }
+ }
+ private fun word(w: String, v: Any?): Any? { if (!s.startsWith(w, i)) fail("bad token"); i += w.length; return v }
+ private fun obj(depth: Int): Map<String, Any?> {
+ i++; val out = LinkedHashMap<String, Any?>(); space()
+ if (peek() == '}') { i++; return out }
+ while (true) {
+ space(); if (peek() != '"') fail("key expected")
+ val k = str(); space(); if (peek() != ':') fail("colon expected"); i++
+ if (out.containsKey(k)) fail("duplicate key $k")
+ out[k] = value(depth + 1); space()
+ when (peek()) { ',' -> i++; '}' -> { i++; return out } else -> fail("comma expected") }
+ }
+ }
+ private fun arr(depth: Int): List<Any?> {
+ i++; val out = ArrayList<Any?>(); space()
+ if (peek() == ']') { i++; return out }
+ while (true) {
+ out.add(value(depth + 1)); space()
+ when (peek()) { ',' -> i++; ']' -> { i++; return out } else -> fail("comma expected") }
+ }
+ }
+ private fun peek(): Char = if (i < s.length) s[i] else fail("unexpected end")
+ private fun str(): String {
+ i++; val o = StringBuilder()
+ while (true) {
+ val c = peek(); i++
+ when {
+ c == '"' -> return o.toString()
+ c < ' ' -> fail("control character")
+ c != '\\' -> o.append(c)
+ else -> {
+ val e = peek(); i++
+ when (e) {
+ '"' -> o.append('"'); '\\' -> o.append('\\'); '/' -> o.append('/')
+ 'n' -> o.append('\n'); 'r' -> o.append('\r'); 't' -> o.append('\t')
+ 'b' -> o.append('\b'); 'f' -> o.append('\u000c')
+ 'u' -> {
+ if (i + 4 > s.length) fail("bad escape")
+ o.append((s.substring(i, i + 4).toIntOrNull(16) ?: fail("bad escape")).toChar()); i += 4
+ }
+ else -> fail("bad escape")
+ }
+ }
+ }
+ }
+ }
+ private fun num(): BigDecimal {
+ val from = i
+ if (peek() == '-') i++
+ while (i < s.length && (s[i].isDigit() || s[i] == '.')) i++
+ val text = s.substring(from, i)
+ if (!text.matches(Regex("-?(0|[1-9][0-9]*)(\\.[0-9]+)?"))) fail("bad number")
+ return BigDecimal(text)
+ }
+ }
+}
+
+/** A plan to and from its canonical text, and its fingerprint. */
+object SegueCodec {
+ fun encode(plan: SeguePlan): String = SegueJson.write(tree(plan, withOrigin = true))
+
+ /** SHA-256 of the canonical JSON without `origin`: two engines writing the same plan agree on it. */
+ fun fingerprint(plan: SeguePlan): String = hex(SegueJson.write(tree(plan, withOrigin = false)).toByteArray(Charsets.UTF_8))
+
+ fun hex(bytes: ByteArray): String = MessageDigest.getInstance("SHA-256").digest(bytes).joinToString("") { "%02x".format(it) }
+
+ private fun tree(p: SeguePlan, withOrigin: Boolean): Map<String, Any?> = buildMap {
+ put("schema", p.schema)
+ if (withOrigin) put("origin", mapOf("engine" to p.origin.engine, "corpus" to p.origin.corpus))
+ put("outgoing", side(p.outgoing)); put("incoming", side(p.incoming))
+ put("span", mapOf("lengthUs" to p.span.lengthUs, "musicalUnits" to p.span.musicalUnits, "unitKind" to p.span.unitKind.wire, "clock" to p.span.clock.wire))
+ put("pulse", mapOf("state" to p.pulse.state.wire, "tempoMicroPerMinute" to p.pulse.tempoMicroPerMinute, "residualUs" to p.pulse.residualUs))
+ put("lanes", p.lanes.map { l ->
+ mapOf("side" to l.side.wire, "target" to l.target.wire, "unit" to l.unit.wire,
+ "knots" to l.knots.map { k -> listOf(k.t, k.valueMilli?.let { BigDecimal.valueOf(it, 3) }, k.form.wire) })
+ })
+ put("gestures", p.gestures.map { mapOf("kind" to it.kind.wire, "atUs" to it.atUs, "units" to it.units) })
+ }
+
+ private fun side(s: SeguePlan.Side) = mapOf("audioKey" to s.audioKey, "gridKey" to s.gridKey, "anchorUs" to s.anchorUs,
+ "ratePpm" to s.ratePpm, "listenerRate" to s.listenerRate)
+
+ /**
+ * Another major version is refused whole, whatever its fields. Within this major an unknown
+ * field is ignored, and so takes no part in the fingerprint.
+ */
+ fun decode(text: String): SeguePlan {
+ val root = SegueJson.read(text) as? Map<*, *> ?: throw SegueFormatException("not an object")
+ val schema = root["schema"] as? String ?: throw SegueFormatException("no schema")
+ if (!schema.startsWith(SegueFormat.SCHEMA_PREFIX)) throw SegueFormatException("not a segue plan: $schema")
+ val major = schema.removePrefix(SegueFormat.SCHEMA_PREFIX)
+ if (!major.matches(Regex("[1-9][0-9]*"))) throw SegueFormatException("bad schema: $schema")
+ if (major != SegueFormat.MAJOR.toString()) throw SegueFormatException("unsupported major version: $schema")
+ val origin = obj(root, "origin")
+ val span = obj(root, "span")
+ val pulse = obj(root, "pulse")
+ return SeguePlan(
+ SeguePlan.Origin(text(origin, "engine"), text(origin, "corpus")),
+ readSide(obj(root, "outgoing")), readSide(obj(root, "incoming")),
+ SeguePlan.Span(long(span, "lengthUs"), longOrNull(span, "musicalUnits")?.let(::toInt),
+ enum(span, "unitKind", UnitKind.values()) { it.wire }, enum(span, "clock", Clock.values()) { it.wire }),
+ SeguePlan.Pulse(enum(pulse, "state", PulseState.values()) { it.wire }, longOrNull(pulse, "tempoMicroPerMinute"), longOrNull(pulse, "residualUs")),
+ list(root, "lanes").map(::readLane),
+ list(root, "gestures").map { g ->
+ val m = g as? Map<*, *> ?: throw SegueFormatException("gesture is not an object")
+ SeguePlan.Gesture(enum(m, "kind", GestureKind.values()) { it.wire }, long(m, "atUs"), toInt(long(m, "units")))
+ },
+ schema,
+ )
+ }
+
+ private fun readSide(m: Map<*, *>) = SeguePlan.Side(text(m, "audioKey"), m["gridKey"]?.let { it as? String ?: throw SegueFormatException("gridKey") },
+ long(m, "anchorUs"), long(m, "ratePpm"), long(m, "listenerRate"))
+
+ private fun readLane(any: Any?): SeguePlan.Lane {
+ val m = any as? Map<*, *> ?: throw SegueFormatException("lane is not an object")
+ val knots = list(m, "knots").map { k ->
+ val a = k as? List<*> ?: throw SegueFormatException("knot is not an array")
+ if (a.size != 3) throw SegueFormatException("knot needs [t, value, form]")
+ val t = whole(a[0], "t")
+ val form = (a[2] as? String)?.let(KnotForm::parse) ?: throw SegueFormatException("bad form ${a[2]}")
+ SeguePlan.Knot(toInt(t), a[1]?.let(::milli), form)
+ }
+ return SeguePlan.Lane(enum(m, "side", LaneSide.values()) { it.wire }, enum(m, "target", Target.values()) { it.wire },
+ enum(m, "unit", SegueUnit.values()) { it.wire }, knots)
+ }
+
+ private fun milli(v: Any?): Long {
+ val d = v as? BigDecimal ?: throw SegueFormatException("knot value is not a number")
+ return try { d.movePointRight(3).longValueExact() } catch (e: ArithmeticException) { throw SegueFormatException("more than 3 decimals: $d") }
+ }
+ private fun obj(m: Map<*, *>, k: String) = m[k] as? Map<*, *> ?: throw SegueFormatException("$k is not an object")
+ private fun list(m: Map<*, *>, k: String) = m[k] as? List<*> ?: throw SegueFormatException("$k is not an array")
+ private fun text(m: Map<*, *>, k: String) = m[k] as? String ?: throw SegueFormatException("$k is not a string")
+ private fun long(m: Map<*, *>, k: String) = whole(m[k], k)
+ private fun longOrNull(m: Map<*, *>, k: String) = m[k]?.let { whole(it, k) }
+ private fun whole(v: Any?, k: String): Long {
+ val d = v as? BigDecimal ?: throw SegueFormatException("$k is not a number")
+ return try { d.longValueExact() } catch (e: ArithmeticException) { throw SegueFormatException("$k is not a whole number: $d") }
+ }
+ private fun toInt(v: Long): Int = if (v in Int.MIN_VALUE..Int.MAX_VALUE) v.toInt() else throw SegueFormatException("out of range: $v")
+ private fun <T> enum(m: Map<*, *>, k: String, values: Array<T>, wire: (T) -> String): T {
+ val s = text(m, k)
+ return values.firstOrNull { wire(it) == s } ?: throw SegueFormatException("bad $k: $s")
+ }
+}
diff --git a/base/automix/src/main/kotlin/app/myspoti/automix/segue/SeguePlan.kt b/base/automix/src/main/kotlin/app/myspoti/automix/segue/SeguePlan.kt
new file mode 100644
index 00000000..9fa2672f
--- /dev/null
+++ b/base/automix/src/main/kotlin/app/myspoti/automix/segue/SeguePlan.kt
@@ -0,0 +1,125 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+package app.myspoti.automix.segue
+
+/**
+ * A transition as data: the policy writes it, the audio engine executes it and decides nothing.
+ * Times are integer microseconds; modulations are physical quantities, never lookup indexes.
+ * See docs/automix/segue-design.md for why each field exists.
+ */
+data class SeguePlan(
+ val origin: Origin,
+ val outgoing: Side,
+ val incoming: Side,
+ val span: Span,
+ val pulse: Pulse,
+ val lanes: List<Lane>,
+ val gestures: List<Gesture> = emptyList(),
+ val schema: String = SegueFormat.SCHEMA,
+) {
+ data class Origin(val engine: String, val corpus: String)
+
+ data class Side(
+ val audioKey: String,
+ val gridKey: String?,
+ val anchorUs: Long,
+ val ratePpm: Long,
+ val listenerRate: Long = SegueFormat.RATE_NOMINAL,
+ )
+
+ data class Span(val lengthUs: Long, val musicalUnits: Int?, val unitKind: UnitKind, val clock: Clock)
+
+ data class Pulse(val state: PulseState, val tempoMicroPerMinute: Long?, val residualUs: Long?)
+
+ data class Lane(val side: LaneSide, val target: Target, val unit: SegueUnit, val knots: List<Knot>)
+
+ /** [valueMilli] is thousandths of the lane's unit; null is silence or neutrality (see [Target]). */
+ data class Knot(val t: Int, val valueMilli: Long?, val form: KnotForm)
+
+ data class Gesture(val kind: GestureKind, val atUs: Long, val units: Int)
+
+ fun side(which: LaneSide): Side = if (which == LaneSide.OUTGOING) outgoing else incoming
+ fun lanesOf(which: LaneSide): List<Lane> = lanes.filter { it.side == which }
+ /** A position in [which]'s source time, in elapsed microseconds from the start of the span. */
+ fun elapsedUs(which: LaneSide, sourceUs: Long): Long {
+ val s = side(which)
+ return Math.floorDiv((sourceUs - s.anchorUs) * SegueFormat.RATE_NOMINAL, s.ratePpm)
+ }
+}
+
+enum class UnitKind(val wire: String) { BAR("bar"), BEAT("beat") }
+enum class Clock(val wire: String) { ELAPSED("elapsed"), SOURCE("source") }
+enum class PulseState(val wire: String) { LOCKED("locked"), LOOSE("loose"), FREE("free") }
+enum class LaneSide(val wire: String) { OUTGOING("outgoing"), INCOMING("incoming") }
+enum class SegueUnit(val wire: String) { DB("db"), HZ("hz"), RATIO("ratio") }
+enum class GestureKind(val wire: String) { REPEAT("repeat") }
+
+/**
+ * What a lane modulates, its only permitted unit, what a null knot means, and the number a null
+ * stands for when a ramp reaches or leaves it.
+ */
+enum class Target(val wire: String, val unit: SegueUnit, val nullMeaning: String, val nullAs: Double) {
+ LEVEL("level", SegueUnit.DB, "silence", SegueFormat.LEVEL_FLOOR_DB),
+ SHELF_BOTTOM("shelfBottom", SegueUnit.DB, "neutral", 0.0),
+ BAND_CORE("bandCore", SegueUnit.DB, "neutral", 0.0),
+ SHELF_TOP("shelfTop", SegueUnit.DB, "neutral", 0.0),
+ SWEEP_HZ("sweepHz", SegueUnit.HZ, "filter open", SegueFormat.SWEEP_OPEN_HZ),
+ SWEEP_PEAK("sweepPeak", SegueUnit.RATIO, "neutral", 1.0),
+ SEND_ROOM("sendRoom", SegueUnit.RATIO, "no send", 0.0),
+ SEND_ECHO("sendEcho", SegueUnit.RATIO, "no send", 0.0),
+}
+
+/** How the lane arrives on a knot from the previous one. */
+sealed class KnotForm(val wire: String) {
+ object Step : KnotForm("step")
+ object Ramp : KnotForm("ramp")
+ object Octave : KnotForm("octave")
+ /** Curvature: position^(k / [SegueFormat.EASE_UNIT]), so k = EASE_UNIT is a plain ramp. */
+ data class Ease(val k: Int) : KnotForm("ease:$k")
+
+ override fun toString() = wire
+
+ companion object {
+ fun parse(text: String): KnotForm? = when {
+ text == "step" -> Step
+ text == "ramp" -> Ramp
+ text == "octave" -> Octave
+ text.startsWith("ease:") -> text.drop(5).takeIf { it.matches(Regex("[1-9][0-9]*")) }?.toIntOrNull()?.let(::Ease)
+ else -> null
+ }
+ }
+}
+
+/** A lane read at any point of the window. */
+class LaneCurve(private val lane: SeguePlan.Lane) {
+ private val ts = IntArray(lane.knots.size) { lane.knots[it].t }
+ private val nullAs = lane.target.nullAs
+
+ /** The numeric value at [t] (normalised), a null knot standing for its [Target.nullAs]. */
+ fun value(t: Double): Double {
+ val k = lane.knots
+ if (t <= ts.first()) return number(k.first())
+ if (t >= ts.last()) return number(k.last())
+ var lo = 0; var hi = ts.size - 1
+ while (hi - lo > 1) { val m = (lo + hi) ushr 1; if (ts[m] <= t) lo = m else hi = m }
+ val a = number(k[lo]); val b = number(k[hi])
+ val u = (t - ts[lo]) / (ts[hi] - ts[lo])
+ return when (val f = k[hi].form) {
+ KnotForm.Step -> a
+ KnotForm.Ramp -> a + (b - a) * u
+ KnotForm.Octave -> a * Math.pow(b / a, u)
+ is KnotForm.Ease -> a + (b - a) * Math.pow(u, f.k.toDouble() / SegueFormat.EASE_UNIT)
+ }
+ }
+
+ /** True at [t] exactly when the lane sits on a null knot: silence is not merely a very low level. */
+ fun isNull(t: Double): Boolean {
+ val k = lane.knots
+ if (t <= ts.first()) return k.first().valueMilli == null
+ if (t >= ts.last()) return k.last().valueMilli == null
+ var lo = 0; var hi = ts.size - 1
+ while (hi - lo > 1) { val m = (lo + hi) ushr 1; if (ts[m] <= t) lo = m else hi = m }
+ return k[lo].valueMilli == null && (k[hi].valueMilli == null || k[hi].form == KnotForm.Step)
+ }
+
+ private fun number(k: SeguePlan.Knot) = k.valueMilli?.let { it / SegueFormat.VALUE_SCALE.toDouble() } ?: nullAs
+}
diff --git a/base/automix/src/main/kotlin/app/myspoti/automix/segue/SegueValidator.kt b/base/automix/src/main/kotlin/app/myspoti/automix/segue/SegueValidator.kt
new file mode 100644
index 00000000..117c03d6
--- /dev/null
+++ b/base/automix/src/main/kotlin/app/myspoti/automix/segue/SegueValidator.kt
@@ -0,0 +1,95 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+package app.myspoti.automix.segue
+
+/** Every way a plan can be unusable; an empty list means it may be executed. */
+enum class SegueViolation {
+ SCHEMA,
+ AUDIO_KEY_MISSING,
+ RATE_NOT_POSITIVE,
+ LENGTH_NOT_POSITIVE,
+ ANCHOR_NEGATIVE,
+ LOCKED_NEEDS_GRID_KEYS,
+ LOCKED_NEEDS_TEMPO,
+ FREE_HAS_TEMPO,
+ DUPLICATE_LANE,
+ UNIT_MISMATCH,
+ KNOTS_NOT_INCREASING,
+ KNOTS_OUT_OF_RANGE,
+ KNOTS_NOT_SPANNING,
+ FORM_NEEDS_FREQUENCY,
+ FREQUENCY_NOT_POSITIVE,
+ EASE_NOT_POSITIVE,
+ GESTURE_INVALID,
+ WINDOW_PAST_OUTGOING,
+ WINDOW_PAST_INCOMING,
+ STALE_OUTGOING_AUDIO,
+ STALE_OUTGOING_GRID,
+ STALE_INCOMING_AUDIO,
+ STALE_INCOMING_GRID,
+}
+
+/** What the current analyses say a plan must match. */
+class SegueSideFacts(val audioKey: String, val gridKey: String?, val durationUs: Long)
+
+object SegueValidator {
+ /** The rules a plan can be judged on alone. */
+ fun structural(p: SeguePlan): List<SegueViolation> {
+ val out = LinkedHashSet<SegueViolation>()
+ if (p.schema != SegueFormat.SCHEMA) out += SegueViolation.SCHEMA
+ for (s in listOf(p.outgoing, p.incoming)) {
+ if (s.audioKey.isBlank()) out += SegueViolation.AUDIO_KEY_MISSING
+ if (s.ratePpm <= 0 || s.listenerRate <= 0) out += SegueViolation.RATE_NOT_POSITIVE
+ if (s.anchorUs < 0) out += SegueViolation.ANCHOR_NEGATIVE
+ }
+ if (p.span.lengthUs <= 0) out += SegueViolation.LENGTH_NOT_POSITIVE
+ when (p.pulse.state) {
+ PulseState.LOCKED -> {
+ if (p.outgoing.gridKey.isNullOrBlank() || p.incoming.gridKey.isNullOrBlank()) out += SegueViolation.LOCKED_NEEDS_GRID_KEYS
+ if ((p.pulse.tempoMicroPerMinute ?: 0) <= 0) out += SegueViolation.LOCKED_NEEDS_TEMPO
+ }
+ PulseState.FREE -> if (p.pulse.tempoMicroPerMinute != null) out += SegueViolation.FREE_HAS_TEMPO
+ PulseState.LOOSE -> Unit
+ }
+ if (p.lanes.map { it.side to it.target }.toSet().size != p.lanes.size) out += SegueViolation.DUPLICATE_LANE
+ for (lane in p.lanes) lane(lane, out)
+ for (g in p.gestures) if (g.atUs < 0 || g.units <= 0) out += SegueViolation.GESTURE_INVALID
+ return out.toList()
+ }
+
+ private fun lane(lane: SeguePlan.Lane, out: MutableSet<SegueViolation>) {
+ if (lane.unit != lane.target.unit) out += SegueViolation.UNIT_MISMATCH
+ val k = lane.knots
+ if (k.isEmpty() || k.first().t != 0 || k.last().t != SegueFormat.T_MAX) out += SegueViolation.KNOTS_NOT_SPANNING
+ for (i in k.indices) {
+ if (k[i].t !in 0..SegueFormat.T_MAX) out += SegueViolation.KNOTS_OUT_OF_RANGE
+ if (i > 0 && k[i].t <= k[i - 1].t) out += SegueViolation.KNOTS_NOT_INCREASING
+ val form = k[i].form
+ if (form == KnotForm.Octave && lane.unit != SegueUnit.HZ) out += SegueViolation.FORM_NEEDS_FREQUENCY
+ if (form is KnotForm.Ease && form.k <= 0) out += SegueViolation.EASE_NOT_POSITIVE
+ if (lane.unit == SegueUnit.HZ && (k[i].valueMilli ?: 1) <= 0) out += SegueViolation.FREQUENCY_NOT_POSITIVE
+ }
+ }
+
+ /** Structural rules, then the rules that need the songs: the window fits and the analyses are the plan's. */
+ fun against(p: SeguePlan, a: SegueSideFacts, b: SegueSideFacts): List<SegueViolation> {
+ val out = LinkedHashSet(structural(p))
+ if (out.isEmpty()) {
+ if (windowEnd(p, p.outgoing) > a.durationUs) out += SegueViolation.WINDOW_PAST_OUTGOING
+ if (windowEnd(p, p.incoming) > b.durationUs) out += SegueViolation.WINDOW_PAST_INCOMING
+ }
+ out += stale(p, a, b)
+ return out.toList()
+ }
+
+ /** A changed audio or grid key means the plan is recomputed, never replayed. */
+ fun stale(p: SeguePlan, a: SegueSideFacts, b: SegueSideFacts): List<SegueViolation> = buildList {
+ if (p.outgoing.audioKey != a.audioKey) add(SegueViolation.STALE_OUTGOING_AUDIO)
+ if (p.outgoing.gridKey != null && p.outgoing.gridKey != a.gridKey) add(SegueViolation.STALE_OUTGOING_GRID)
+ if (p.incoming.audioKey != b.audioKey) add(SegueViolation.STALE_INCOMING_AUDIO)
+ if (p.incoming.gridKey != null && p.incoming.gridKey != b.gridKey) add(SegueViolation.STALE_INCOMING_GRID)
+ }
+
+ /** Where the window ends in [s]'s source time, its speed applied. */
+ fun windowEnd(p: SeguePlan, s: SeguePlan.Side): Long =
+ s.anchorUs + if (p.span.clock == Clock.SOURCE) p.span.lengthUs else p.span.lengthUs * s.ratePpm / SegueFormat.RATE_NOMINAL
+}
diff --git a/base/automix/src/test/kotlin/app/myspoti/automix/segue/SegueFormatTest.kt b/base/automix/src/test/kotlin/app/myspoti/automix/segue/SegueFormatTest.kt
new file mode 100644
index 00000000..440aadcc
--- /dev/null
+++ b/base/automix/src/test/kotlin/app/myspoti/automix/segue/SegueFormatTest.kt
@@ -0,0 +1,237 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+package app.myspoti.automix.segue
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNotEquals
+import org.junit.Assert.assertThrows
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class SegueFormatTest {
+ private val ramp = KnotForm.Ramp
+ private fun plan(
+ state: PulseState = PulseState.FREE,
+ tempo: Long? = null,
+ gridA: String? = null,
+ rateA: Long = SegueFormat.RATE_NOMINAL,
+ listener: Long = SegueFormat.RATE_NOMINAL,
+ lengthUs: Long = 8_000_000,
+ anchorA: Long = 100_000_000,
+ audioA: String = "a",
+ lanes: List<SeguePlan.Lane> = listOf(level()),
+ gestures: List<SeguePlan.Gesture> = emptyList(),
+ schema: String = SegueFormat.SCHEMA,
+ ) = SeguePlan(SeguePlan.Origin("test", "none"),
+ SeguePlan.Side(audioA, gridA, anchorA, rateA, listener),
+ SeguePlan.Side("b", "gb", 0, 1_020_000, listener),
+ SeguePlan.Span(lengthUs, 4, UnitKind.BAR, Clock.ELAPSED),
+ SeguePlan.Pulse(state, tempo, if (state == PulseState.FREE) null else 1234), lanes, gestures, schema)
+
+ private fun level(vararg knots: SeguePlan.Knot = arrayOf(SeguePlan.Knot(0, 0, KnotForm.Step), SeguePlan.Knot(SegueFormat.T_MAX, null, ramp))) =
+ SeguePlan.Lane(LaneSide.OUTGOING, Target.LEVEL, SegueUnit.DB, knots.toList())
+
+ private fun violations(p: SeguePlan) = SegueValidator.structural(p)
+ private fun assertViolates(v: SegueViolation, p: SeguePlan) = assertTrue("$v in ${violations(p)}", v in violations(p))
+
+ // ── Validation: one test per rule ──
+
+ @Test fun aWellFormedPlanHasNoViolation() = assertEquals(emptyList<SegueViolation>(), violations(plan()))
+
+ @Test fun positionsMustStrictlyIncrease() {
+ assertViolates(SegueViolation.KNOTS_NOT_INCREASING, plan(lanes = listOf(level(SeguePlan.Knot(0, 0, ramp),
+ SeguePlan.Knot(5, 0, ramp), SeguePlan.Knot(5, 0, ramp), SeguePlan.Knot(SegueFormat.T_MAX, 0, ramp)))))
+ }
+
+ @Test fun positionsMustStayInTheNormalisedRange() {
+ assertViolates(SegueViolation.KNOTS_OUT_OF_RANGE, plan(lanes = listOf(level(SeguePlan.Knot(0, 0, ramp), SeguePlan.Knot(SegueFormat.T_MAX + 1, 0, ramp)))))
+ assertViolates(SegueViolation.KNOTS_OUT_OF_RANGE, plan(lanes = listOf(level(SeguePlan.Knot(-1, 0, ramp), SeguePlan.Knot(SegueFormat.T_MAX, 0, ramp)))))
+ }
+
+ @Test fun aLaneMustCoverTheWholeWindow() {
+ assertViolates(SegueViolation.KNOTS_NOT_SPANNING, plan(lanes = listOf(level(SeguePlan.Knot(10, 0, ramp), SeguePlan.Knot(SegueFormat.T_MAX, 0, ramp)))))
+ assertViolates(SegueViolation.KNOTS_NOT_SPANNING, plan(lanes = listOf(SeguePlan.Lane(LaneSide.OUTGOING, Target.LEVEL, SegueUnit.DB, emptyList()))))
+ }
+
+ @Test fun theUnitMustMatchTheTarget() {
+ val k = listOf(SeguePlan.Knot(0, 1000, ramp), SeguePlan.Knot(SegueFormat.T_MAX, 1000, ramp))
+ for (t in Target.values()) {
+ for (u in SegueUnit.values()) {
+ val v = violations(plan(lanes = listOf(SeguePlan.Lane(LaneSide.OUTGOING, t, u, k))))
+ assertEquals("$t in $u", u != t.unit, SegueViolation.UNIT_MISMATCH in v)
+ }
+ }
+ }
+
+ @Test fun lockedNeedsBothGridKeysAndATempo() {
+ assertViolates(SegueViolation.LOCKED_NEEDS_GRID_KEYS, plan(PulseState.LOCKED, 120_000_000, gridA = null))
+ assertViolates(SegueViolation.LOCKED_NEEDS_TEMPO, plan(PulseState.LOCKED, null, gridA = "ga"))
+ assertEquals(emptyList<SegueViolation>(), violations(plan(PulseState.LOCKED, 120_000_000, gridA = "ga")))
+ }
+
+ @Test fun freeHasNoTempo() = assertViolates(SegueViolation.FREE_HAS_TEMPO, plan(PulseState.FREE, 120_000_000))
+
+ @Test fun ratesMustBePositive() {
+ assertViolates(SegueViolation.RATE_NOT_POSITIVE, plan(rateA = 0))
+ assertViolates(SegueViolation.RATE_NOT_POSITIVE, plan(listener = -1))
+ }
+
+ @Test fun theWindowMustHaveALength() = assertViolates(SegueViolation.LENGTH_NOT_POSITIVE, plan(lengthUs = 0))
+
+ @Test fun anchorsAreSourcePositions() = assertViolates(SegueViolation.ANCHOR_NEGATIVE, plan(anchorA = -1))
+
+ @Test fun audioKeysAreRequired() = assertViolates(SegueViolation.AUDIO_KEY_MISSING, plan(audioA = ""))
+
+ @Test fun aLaneIsOnePerSideAndTarget() = assertViolates(SegueViolation.DUPLICATE_LANE, plan(lanes = listOf(level(), level())))
+
+ @Test fun octaveIsForFrequencies() {
+ val k = listOf(SeguePlan.Knot(0, 0, KnotForm.Step), SeguePlan.Knot(SegueFormat.T_MAX, 0, KnotForm.Octave))
+ assertViolates(SegueViolation.FORM_NEEDS_FREQUENCY, plan(lanes = listOf(SeguePlan.Lane(LaneSide.OUTGOING, Target.LEVEL, SegueUnit.DB, k))))
+ }
+
+ @Test fun frequenciesArePositiveButNullMeansOpen() {
+ fun sweep(v: Long?) = plan(lanes = listOf(SeguePlan.Lane(LaneSide.OUTGOING, Target.SWEEP_HZ, SegueUnit.HZ,
+ listOf(SeguePlan.Knot(0, v, KnotForm.Step), SeguePlan.Knot(SegueFormat.T_MAX, 400_000, KnotForm.Octave)))))
+ assertViolates(SegueViolation.FREQUENCY_NOT_POSITIVE, sweep(0))
+ assertEquals(emptyList<SegueViolation>(), violations(sweep(null)))
+ }
+
+ @Test fun nullHasAMeaningForEveryTarget() {
+ for (t in Target.values()) {
+ assertTrue(t.nullMeaning.isNotEmpty())
+ val k = listOf(SeguePlan.Knot(0, null, KnotForm.Step), SeguePlan.Knot(SegueFormat.T_MAX, null, KnotForm.Step))
+ assertEquals("$t", emptyList<SegueViolation>(), violations(plan(lanes = listOf(SeguePlan.Lane(LaneSide.OUTGOING, t, t.unit, k)))))
+ }
+ }
+
+ @Test fun easeNeedsAPositiveCurvature() {
+ assertEquals(null, KnotForm.parse("ease:0"))
+ assertEquals(null, KnotForm.parse("ease:-3"))
+ assertEquals(KnotForm.Ease(1500), KnotForm.parse("ease:1500"))
+ assertViolates(SegueViolation.EASE_NOT_POSITIVE, plan(lanes = listOf(level(SeguePlan.Knot(0, 0, KnotForm.Step), SeguePlan.Knot(SegueFormat.T_MAX, 0, KnotForm.Ease(0))))))
+ }
+
+ @Test fun gesturesNeedAPlaceAndALength() {
+ assertViolates(SegueViolation.GESTURE_INVALID, plan(gestures = listOf(SeguePlan.Gesture(GestureKind.REPEAT, -1, 2))))
+ assertViolates(SegueViolation.GESTURE_INVALID, plan(gestures = listOf(SeguePlan.Gesture(GestureKind.REPEAT, 5, 0))))
+ }
+
+ @Test fun theWindowWithItsSpeedMustFitBothSongs() {
+ val p = plan() // A: 100 s + 8 s; B: 0 + 8 s × 1.02 = 8.16 s
+ assertEquals(emptyList<SegueViolation>(), SegueValidator.against(p, facts("a", null, 108_000_000), facts("b", "gb", 8_160_000)))
+ assertTrue(SegueViolation.WINDOW_PAST_OUTGOING in SegueValidator.against(p, facts("a", null, 107_999_999), facts("b", "gb", 9_000_000)))
+ assertTrue(SegueViolation.WINDOW_PAST_INCOMING in SegueValidator.against(p, facts("a", null, 108_000_000), facts("b", "gb", 8_159_999)))
+ }
+
+ private fun facts(audio: String, grid: String?, duration: Long) = SegueSideFacts(audio, grid, duration)
+
+ // ── Invalidation ──
+
+ @Test fun aChangedKeyInvalidatesThePlan() {
+ val p = plan(PulseState.LOCKED, 120_000_000, gridA = "ga")
+ val a = facts("a", "ga", 200_000_000); val b = facts("b", "gb", 200_000_000)
+ assertEquals(emptyList<SegueViolation>(), SegueValidator.stale(p, a, b))
+ assertEquals(listOf(SegueViolation.STALE_OUTGOING_AUDIO), SegueValidator.stale(p, facts("x", "ga", 1), b))
+ assertEquals(listOf(SegueViolation.STALE_OUTGOING_GRID), SegueValidator.stale(p, facts("a", "x", 1), b))
+ assertEquals(listOf(SegueViolation.STALE_INCOMING_AUDIO), SegueValidator.stale(p, a, facts("x", "gb", 1)))
+ assertEquals(listOf(SegueViolation.STALE_INCOMING_GRID), SegueValidator.stale(p, a, facts("b", "x", 1)))
+ }
+
+ // ── Serialization ──
+
+ private fun full() = plan(PulseState.LOCKED, 123_456_789, gridA = "ga", lanes = listOf(
+ level(SeguePlan.Knot(0, -1500, KnotForm.Step), SeguePlan.Knot(250_000, 0, KnotForm.Ease(1800)), SeguePlan.Knot(SegueFormat.T_MAX, null, ramp)),
+ SeguePlan.Lane(LaneSide.INCOMING, Target.SWEEP_HZ, SegueUnit.HZ, listOf(SeguePlan.Knot(0, null, KnotForm.Step), SeguePlan.Knot(SegueFormat.T_MAX, 400_000, KnotForm.Octave))),
+ SeguePlan.Lane(LaneSide.INCOMING, Target.SEND_ECHO, SegueUnit.RATIO, listOf(SeguePlan.Knot(0, 125, KnotForm.Step), SeguePlan.Knot(SegueFormat.T_MAX, 1, ramp))),
+ ), gestures = listOf(SeguePlan.Gesture(GestureKind.REPEAT, 90_000_000, 4)))
+
+ @Test fun aPlanSurvivesARoundTrip() {
+ val p = full()
+ val text = SegueCodec.encode(p)
+ assertEquals(p, SegueCodec.decode(text))
+ assertEquals(text, SegueCodec.encode(SegueCodec.decode(text)))
+ }
+
+ @Test fun theCanonicalFormSortsKeysAndHasOneSpellingPerNumber() {
+ val text = SegueCodec.encode(full())
+ assertTrue(text, text.startsWith("{\"gestures\":"))
+ assertFalse(text, text.contains(' '))
+ assertTrue(text, text.contains("[0,-1.5,\"step\"]"))
+ assertTrue(text, text.contains("[250000,0,\"ease:1800\"]"))
+ assertTrue(text, text.contains("[1000000,0.001,\"ramp\"]"))
+ assertTrue(text, text.contains("[1000000,null,\"ramp\"]"))
+ }
+
+ @Test fun aFingerprintIsStableAndIgnoresOnlyTheOrigin() {
+ val p = full()
+ assertEquals(64, SegueCodec.fingerprint(p).length)
+ assertEquals(SegueCodec.fingerprint(p), SegueCodec.fingerprint(SegueCodec.decode(SegueCodec.encode(p))))
+ assertEquals(SegueCodec.fingerprint(p), SegueCodec.fingerprint(p.copy(origin = SeguePlan.Origin("other", "other"))))
+ assertNotEquals(SegueCodec.fingerprint(p), SegueCodec.fingerprint(p.copy(span = p.span.copy(lengthUs = 1))))
+ assertNotEquals(SegueCodec.fingerprint(p), SegueCodec.fingerprint(p.copy(outgoing = p.outgoing.copy(listenerRate = 1_250_000))))
+ }
+
+ @Test fun keyOrderInTheInputDoesNotChangeTheFingerprint() {
+ val text = SegueCodec.encode(plan())
+ val reordered = "{\"origin\":{\"corpus\":\"none\",\"engine\":\"test\"}," + text.removePrefix("{").replace("\"origin\":{\"corpus\":\"none\",\"engine\":\"test\"},", "")
+ assertEquals(SegueCodec.fingerprint(plan()), SegueCodec.fingerprint(SegueCodec.decode(reordered)))
+ }
+
+ @Test fun anotherMajorIsRefusedAndAnUnknownFieldIsIgnoredWithinThisOne() {
+ val text = SegueCodec.encode(plan())
+ assertThrows(SegueFormatException::class.java) { SegueCodec.decode(text.replace("\"segue/1\"", "\"segue/2\"")) }
+ assertThrows(SegueFormatException::class.java) { SegueCodec.decode(text.replace("\"segue/1\"", "\"other/1\"")) }
+ val extra = text.replace("\"gestures\":[]", "\"gestures\":[],\"later\":1")
+ assertEquals(plan(), SegueCodec.decode(extra))
+ assertEquals(SegueCodec.fingerprint(plan()), SegueCodec.fingerprint(SegueCodec.decode(extra)))
+ }
+
+ @Test fun malformedPlansAreRefused() {
+ val text = SegueCodec.encode(plan())
+ for (bad in listOf("", "[]", "{", text + "x", text.replace("\"lengthUs\":8000000", "\"lengthUs\":8.5"),
+ text.replace("\"lengthUs\":8000000", "\"lengthUs\":8e6"), text.replace("\"lengthUs\":8000000", "\"lengthUs\":\"8\""),
+ text.replace("\"state\":\"free\"", "\"state\":\"maybe\""), text.replace("\"step\"", "\"wobble\""),
+ text.replace("[0,0,\"step\"]", "[0,0.0001,\"step\"]"), text.replace("[0,0,\"step\"]", "[0,0]"),
+ text.replace("\"span\":", "\"span\":{},\"span\":"))) {
+ assertThrows(bad, SegueFormatException::class.java) { SegueCodec.decode(bad) }
+ }
+ }
+
+ // ── Reading a lane ──
+
+ private fun curve(vararg k: SeguePlan.Knot, target: Target = Target.LEVEL) =
+ LaneCurve(SeguePlan.Lane(LaneSide.OUTGOING, target, target.unit, k.toList()))
+
+ @Test fun formsDescribeTheArrivalOnTheirKnot() {
+ val m = SegueFormat.T_MAX
+ assertEquals(-5.0, curve(SeguePlan.Knot(0, 0, KnotForm.Step), SeguePlan.Knot(m, -10_000, ramp)).value(m / 2.0), 1e-9)
+ assertEquals(0.0, curve(SeguePlan.Knot(0, 0, KnotForm.Step), SeguePlan.Knot(m, -10_000, KnotForm.Step)).value(m - 1.0), 1e-9)
+ assertEquals(-10.0, curve(SeguePlan.Knot(0, 0, KnotForm.Step), SeguePlan.Knot(m, -10_000, KnotForm.Step)).value(m.toDouble()), 1e-9)
+ assertEquals(-2.5, curve(SeguePlan.Knot(0, 0, KnotForm.Step), SeguePlan.Knot(m, -10_000, KnotForm.Ease(2000))).value(m / 2.0), 1e-9)
+ val octave = curve(SeguePlan.Knot(0, 1_000_000, KnotForm.Step), SeguePlan.Knot(m, 250_000, KnotForm.Octave), target = Target.SWEEP_HZ)
+ assertEquals(500.0, octave.value(m / 2.0), 1e-9)
+ }
+
+ @Test fun outsideTheWindowALaneHoldsItsEnds() {
+ val m = SegueFormat.T_MAX
+ val c = curve(SeguePlan.Knot(0, -3000, KnotForm.Step), SeguePlan.Knot(m, -9000, ramp))
+ assertEquals(-3.0, c.value(-5.0), 1e-9)
+ assertEquals(-9.0, c.value(m + 5.0), 1e-9)
+ }
+
+ @Test fun nullIsSilenceOnLevelNotAVeryLowValue() {
+ val m = SegueFormat.T_MAX
+ val c = curve(SeguePlan.Knot(0, 0, KnotForm.Step), SeguePlan.Knot(m, null, ramp))
+ assertEquals(SegueFormat.LEVEL_FLOOR_DB / 2, c.value(m / 2.0), 1e-9)
+ assertFalse(c.isNull(m - 1.0))
+ assertTrue(c.isNull(m.toDouble()))
+ assertEquals(1.0, curve(SeguePlan.Knot(0, null, KnotForm.Step), SeguePlan.Knot(m, null, KnotForm.Step), target = Target.SWEEP_PEAK).value(10.0), 1e-9)
+ assertEquals(SegueFormat.SWEEP_OPEN_HZ, curve(SeguePlan.Knot(0, null, KnotForm.Step), SeguePlan.Knot(m, null, KnotForm.Step), target = Target.SWEEP_HZ).value(10.0), 1e-9)
+ }
+
+ @Test fun elapsedTimeFollowsEachSidesRate() {
+ val p = plan()
+ assertEquals(1_000_000, p.elapsedUs(LaneSide.OUTGOING, 101_000_000))
+ assertEquals(1_000_000, p.elapsedUs(LaneSide.INCOMING, 1_020_000))
+ }
+}
diff --git a/docs/automix/segue-design.md b/docs/automix/segue-design.md
new file mode 100644
index 00000000..b8753252
--- /dev/null
+++ b/docs/automix/segue-design.md
@@ -0,0 +1,112 @@
+# Segue: transition plans and the policy that writes them
+
+A segue is a transition between two songs described as data. The policy starts from two local
+analyses and writes a plan; the audio engine executes the plan and decides nothing. This file says
+why each field and each parameter exists.
+
+**No value here is a result.** Each number is a starting parameter to be confirmed by measurement.
+Labels: `[M]` measured on the project's corpus; `[U]` usual order of magnitude; `[I]` inferred, a
+design proposal; `[R]` reused from a value already in this repository. Today nothing is `[M]`.
+
+## Plan format
+
+Times are integer microseconds and modulations are stored as physical quantities, without a
+conversion table: a plan can be read and checked on its own, and a float never drifts between two
+runs. The format scales are in `SegueFormat.kt`.
+
+### `SeguePlan`
+
+| Field | Why |
+|---|---|
+| `schema` | `segue/<major>`: a reader knows at once whether it understands the plan |
+| `origin` | Engine and tuning corpus, so a plan can be reproduced; left out of the fingerprint |
+| `outgoing`, `incoming` | Two `Side` objects handled alike, so neither song is a special case in the format |
+| `span` | The common mixing window |
+| `pulse` | States the beat alignment explicitly, including its absence |
+| `lanes` | An extensible list of continuous modulations |
+| `gestures` | Discrete actions, which ramps cannot express |
+
+### `Side`
+
+| Field | Why |
+|---|---|
+| `audioKey` | SHA-256 of the decoded signal, so identity does not depend on any catalogue, path or token |
+| `gridKey` | SHA-256 of the beat grid used; the plan is invalid once that grid changes. Null without a grid |
+| `anchorUs` | Start of the window in this song's source time, independent of speed |
+| `ratePpm` | Alignment speed as an integer, 1 000 000 = nominal. A coarser scale is not enough: rounding at 0.1 % can reach 32 ms over 64 s, more than the phase limit, whereas parts per million stay under 32 µs |
+| `listenerRate` | The listener's speed setting on the same scale, kept apart so a plan can be recomputed without confusing it with alignment |
+
+### `Span`
+
+| Field | Why |
+|---|---|
+| `lengthUs` | Reference length for rendering |
+| `musicalUnits` | Musical length; null when it has no meaning (a fade in seconds) |
+| `unitKind` | `bar` or `beat` |
+| `clock` | `elapsed` or `source`, so the time base is never implied. `elapsed` is measured before `listenerRate`. The policy writes only `elapsed`; the engine refuses `source` for now |
+
+### `Pulse`
+
+| Field | Why |
+|---|---|
+| `state` | `locked`: alignment held through the window. `loose`: aligned on one strong beat, not held. `free`: no alignment |
+| `tempoMicroPerMinute` | Common target tempo, null if `free` |
+| `residualUs` | Expected phase error, comparable with what is measured on a render |
+
+### `Lane`
+
+| Field | Why |
+|---|---|
+| `side` | `outgoing` or `incoming` |
+| `target` | The quantity modulated, below |
+| `unit` | `db`, `hz` or `ratio`: rules out any implicit reading |
+| `knots` | `[t, value, form]`; `t` from 0 to 1 000 000 over the window, first and last knots required so a lane is defined everywhere |
+
+Values are decimals with at most 3 places, so each has one spelling. The `form` of a knot describes
+the arrival on it from the previous knot: `step` (holds, then jumps), `ramp` (linear in the unit),
+`octave` (geometric, for frequencies) and `ease:<k>` (position^(k/1000)).
+
+| `target` | Need | Unit | `null` means |
+|---|---|---|---|
+| `level` | The song's level ramp | `db` | Silence, which has no value in dB |
+| `shelfBottom`, `bandCore`, `shelfTop` | Sharing the spectrum, against clashing bass | `db` | Neutral |
+| `sweepHz` | Filter cutoff sweep | `hz` | Filter open |
+| `sweepPeak` | Accent of that sweep | `ratio` | Neutral |
+| `sendRoom`, `sendEcho` | A sound tail as the song leaves | `ratio` | No send |
+
+While a ramp runs to or from a null knot, null stands for `LEVEL_FLOOR_DB` (−60 dB `[I]`, inaudible
+under music) or `SWEEP_OPEN_HZ` (20 kHz `[I]`, the top of hearing).
+
+### `Gesture`
+
+| Field | Why |
+|---|---|
+| `kind` | `repeat` only in this version: extends an ending that is too short |
+| `atUs` | Position in source time |
+| `units` | Length in musical units |
+
+The format and the validation carry gestures; the policy does not emit them and the engine refuses
+a plan that has one, because a player's seek would leave a gap and the mix's progress follows the
+outgoing song's position.
+
+### Serialisation
+
+Canonical JSON in Unicode: sorted keys, no spaces, integers where possible. The fingerprint is the
+SHA-256 of that text without `origin`, so two engines writing the same plan agree on it.
+
+### Validation
+
+`SegueValidator` returns every violation; none means the plan may run. `structural` needs the plan
+alone, `against` also needs the current analyses:
+
+- knot positions strictly increase within the range, and cover the window;
+- the unit matches the target; `octave` applies to `hz` only; frequencies are positive;
+- `locked` needs both `gridKey`s and a tempo; `free` has no tempo;
+- rates are strictly positive;
+- the window, its speed applied, runs past neither song;
+- a changed `audioKey` or `gridKey` invalidates the plan: it is recomputed, never replayed;
+- another major version is refused whole; within this major an unknown field is ignored, and takes
+ no part in the fingerprint, so an older reader still agrees on it.
+
+`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`.